mirror of
https://github.com/sysadminsmedia/homebox.git
synced 2025-12-24 06:28:34 +01:00
Compare commits
1 Commits
fix/auto-s
...
fix/datepi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a89ac74888 |
@@ -1,5 +0,0 @@
|
||||
# [Choice] Node.js version (use -bullseye variants on local arm64/Apple Silicon): 18, 16, 14, 18-bullseye, 16-bullseye, 14-bullseye, 18-buster, 16-buster, 14-buster
|
||||
ARG VARIANT=16-bullseye
|
||||
FROM mcr.microsoft.com/vscode/devcontainers/typescript-node:0-${VARIANT}
|
||||
|
||||
RUN sh -c "$(curl --location https://taskfile.dev/install.sh)" -- -d -b ~/.local/bin
|
||||
@@ -1,40 +0,0 @@
|
||||
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
|
||||
// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/typescript-node
|
||||
{
|
||||
"name": "Node.js & TypeScript",
|
||||
"build": {
|
||||
"dockerfile": "Dockerfile",
|
||||
// Update 'VARIANT' to pick a Node version: 18, 16, 14.
|
||||
// Append -bullseye or -buster to pin to an OS version.
|
||||
// Use -bullseye variants on local on arm64/Apple Silicon.
|
||||
"args": {
|
||||
"VARIANT": "18-bullseye"
|
||||
}
|
||||
},
|
||||
|
||||
// Configure tool-specific properties.
|
||||
"customizations": {
|
||||
// Configure properties specific to VS Code.
|
||||
"vscode": {
|
||||
// Add the IDs of extensions you want installed when the container is created.
|
||||
"extensions": [
|
||||
"dbaeumer.vscode-eslint"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||
"forwardPorts": [
|
||||
7745,
|
||||
3000
|
||||
],
|
||||
|
||||
// Use 'postCreateCommand' to run commands after the container is created.
|
||||
"postCreateCommand": "go install github.com/go-task/task/v3/cmd/task@latest && npm install -g pnpm && task setup",
|
||||
|
||||
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
|
||||
"remoteUser": "node",
|
||||
"features": {
|
||||
"golang": "1.19"
|
||||
}
|
||||
}
|
||||
1
.github/FUNDING.yml
vendored
1
.github/FUNDING.yml
vendored
@@ -1 +0,0 @@
|
||||
github: [hay-kot]
|
||||
3
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
3
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -1,7 +1,6 @@
|
||||
---
|
||||
name: "Bug Report"
|
||||
description: "Submit a bug report for the current release"
|
||||
labels: ["bug"]
|
||||
description: "submit a bug report for the current release"
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
|
||||
3
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
3
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -1,7 +1,6 @@
|
||||
---
|
||||
name: "Feature Request"
|
||||
description: "Submit a feature request for the current release"
|
||||
labels: ["feature-request"]
|
||||
description: "submit a feature request for the current release"
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem-statement
|
||||
|
||||
31
.github/dependabot.yml
vendored
Normal file
31
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Fetch and update latest `npm` packages
|
||||
- package-ecosystem: npm
|
||||
directory: "/frontend"
|
||||
schedule:
|
||||
interval: daily
|
||||
time: "00:00"
|
||||
open-pull-requests-limit: 10
|
||||
reviewers:
|
||||
- hay-kot
|
||||
assignees:
|
||||
- hay-kot
|
||||
commit-message:
|
||||
prefix: fix
|
||||
prefix-development: chore
|
||||
include: scope
|
||||
- package-ecosystem: gomod
|
||||
directory: backend
|
||||
schedule:
|
||||
interval: daily
|
||||
time: "00:00"
|
||||
open-pull-requests-limit: 10
|
||||
reviewers:
|
||||
- hay-kot
|
||||
assignees:
|
||||
- hay-kot
|
||||
commit-message:
|
||||
prefix: fix
|
||||
prefix-development: chore
|
||||
include: scope
|
||||
10
.github/workflows/partial-backend.yaml
vendored
10
.github/workflows/partial-backend.yaml
vendored
@@ -7,17 +7,15 @@ jobs:
|
||||
Go:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.19
|
||||
|
||||
- name: Install Task
|
||||
uses: arduino/setup-task@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v3
|
||||
@@ -30,7 +28,7 @@ jobs:
|
||||
args: --timeout=6m
|
||||
|
||||
- name: Build API
|
||||
run: task go:build
|
||||
run: task api:build
|
||||
|
||||
- name: Test
|
||||
run: task go:coverage
|
||||
run: task api:coverage
|
||||
|
||||
8
.github/workflows/partial-frontend.yaml
vendored
8
.github/workflows/partial-frontend.yaml
vendored
@@ -8,17 +8,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install Task
|
||||
uses: arduino/setup-task@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.19
|
||||
|
||||
@@ -26,7 +24,7 @@ jobs:
|
||||
with:
|
||||
node-version: 18
|
||||
|
||||
- uses: pnpm/action-setup@v2.2.4
|
||||
- uses: pnpm/action-setup@v2.2.2
|
||||
with:
|
||||
version: 6.0.2
|
||||
|
||||
|
||||
9
.github/workflows/partial-publish.yaml
vendored
9
.github/workflows/partial-publish.yaml
vendored
@@ -20,22 +20,22 @@ jobs:
|
||||
name: "Publish Homebox"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.19
|
||||
|
||||
- name: Set up QEMU
|
||||
id: qemu
|
||||
uses: docker/setup-qemu-action@v2
|
||||
uses: docker/setup-qemu-action@v1
|
||||
with:
|
||||
image: tonistiigi/binfmt:latest
|
||||
platforms: all
|
||||
|
||||
- name: install buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v1
|
||||
with:
|
||||
install: true
|
||||
|
||||
@@ -60,7 +60,6 @@ jobs:
|
||||
--tag ghcr.io/hay-kot/homebox:nightly \
|
||||
--tag ghcr.io/hay-kot/homebox:latest \
|
||||
--tag ghcr.io/hay-kot/homebox:${{ inputs.tag }} \
|
||||
--build-arg VERSION=${{ inputs.tag }} \
|
||||
--build-arg COMMIT=$(git rev-parse HEAD) \
|
||||
--build-arg BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
|
||||
--platform linux/amd64,linux/arm64,linux/arm/v7 .
|
||||
|
||||
4
.github/workflows/publish.yaml
vendored
4
.github/workflows/publish.yaml
vendored
@@ -27,7 +27,7 @@ jobs:
|
||||
- backend-tests
|
||||
- frontend-tests
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v2
|
||||
- uses: superfly/flyctl-actions/setup-flyctl@master
|
||||
- run: flyctl deploy --remote-only
|
||||
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Deploy docs
|
||||
uses: mhausenblas/mkdocs-deploy-gh-pages@master
|
||||
|
||||
4
.github/workflows/pull-requests.yaml
vendored
4
.github/workflows/pull-requests.yaml
vendored
@@ -8,8 +8,8 @@ on:
|
||||
jobs:
|
||||
backend-tests:
|
||||
name: "Backend Server Tests"
|
||||
uses: ./.github/workflows/partial-backend.yaml
|
||||
uses: hay-kot/homebox/.github/workflows/partial-backend.yaml@main
|
||||
|
||||
frontend-tests:
|
||||
name: "Frontend and End-to-End Tests"
|
||||
uses: ./.github/workflows/partial-frontend.yaml
|
||||
uses: hay-kot/homebox/.github/workflows/partial-frontend.yaml@main
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -3,6 +3,7 @@ backend/.data/*
|
||||
config.yml
|
||||
homebox.db
|
||||
.idea
|
||||
|
||||
.DS_Store
|
||||
test-mailer.json
|
||||
node_modules
|
||||
@@ -31,7 +32,6 @@ node_modules
|
||||
go.work
|
||||
.task/
|
||||
backend/.env
|
||||
build/*
|
||||
|
||||
# Output Directory for Nuxt/Frontend during build step
|
||||
backend/app/api/public/*
|
||||
@@ -45,7 +45,3 @@ node_modules
|
||||
.output
|
||||
.env
|
||||
dist
|
||||
|
||||
.pnpm-store
|
||||
backend/app/api/app
|
||||
backend/app/api/__debug_bin
|
||||
47
.vscode/launch.json
vendored
47
.vscode/launch.json
vendored
@@ -1,47 +0,0 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"compounds": [
|
||||
{
|
||||
"name": "Full Stack",
|
||||
"configurations": ["Launch Backend", "Launch Frontend"],
|
||||
"stopAll": true
|
||||
}
|
||||
],
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch Backend",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "debug",
|
||||
"program": "${workspaceRoot}/backend/app/api/",
|
||||
"args": [],
|
||||
"env": {
|
||||
"HBOX_DEMO": "true",
|
||||
"HBOX_LOG_LEVEL": "debug",
|
||||
"HBOX_DEBUG_ENABLED": "true",
|
||||
"HBOX_STORAGE_DATA": "${workspaceRoot}/backend/.data",
|
||||
"HBOX_STORAGE_SQLITE_URL": "${workspaceRoot}/backend/.data/homebox.db?_fk=1"
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "Launch Frontend",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"runtimeExecutable": "pnpm",
|
||||
"runtimeArgs": [
|
||||
"run",
|
||||
"dev"
|
||||
],
|
||||
"cwd": "${workspaceFolder}/frontend",
|
||||
"serverReadyAction": {
|
||||
"action": "debugWithChrome",
|
||||
"pattern": "Local: http://localhost:([0-9]+)",
|
||||
"uriFormat": "http://localhost:%s",
|
||||
"webRoot": "${workspaceFolder}/frontend"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
27
.vscode/settings.json
vendored
27
.vscode/settings.json
vendored
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true
|
||||
},
|
||||
"yaml.schemas": {
|
||||
"https://squidfunk.github.io/mkdocs-material/schema.json": "mkdocs.yml"
|
||||
},
|
||||
@@ -7,27 +10,5 @@
|
||||
"package.json": "package-lock.json, yarn.lock, .eslintrc.js, tsconfig.json, .prettierrc, .editorconfig, pnpm-lock.yaml, postcss.config.js, tailwind.config.js",
|
||||
"docker-compose.yml": "Dockerfile, .dockerignore, docker-compose.dev.yml, docker-compose.yml",
|
||||
"README.md": "LICENSE, SECURITY.md"
|
||||
},
|
||||
"cSpell.words": [
|
||||
"debughandlers"
|
||||
],
|
||||
// use ESLint to format code on save
|
||||
"editor.formatOnSave": false,
|
||||
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
|
||||
},
|
||||
"eslint.format.enable": true,
|
||||
"css.validate": false,
|
||||
"tailwindCSS.includeLanguages": {
|
||||
"vue": "html",
|
||||
"vue-html": "html"
|
||||
},
|
||||
"editor.quickSuggestions": {
|
||||
"strings": true
|
||||
},
|
||||
"tailwindCSS.experimental.configFile": "./frontend/tailwind.config.js"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
## We Develop with Github
|
||||
|
||||
We use github to host code, to track issues and feature requests, as well as accept pull requests.
|
||||
|
||||
## Branch Flow
|
||||
|
||||
We use the `main` branch as the development branch. All PRs should be made to the `main` branch from a feature branch. To create a pull request you can use the following steps:
|
||||
|
||||
1. Fork the repository and create a new branch from `main`.
|
||||
2. If you've added code that should be tested, add tests.
|
||||
3. If you've changed API's, update the documentation.
|
||||
4. Ensure that the test suite and linters pass
|
||||
5. Issue your pull request
|
||||
|
||||
## How To Get Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
There is a devcontainer available for this project. If you are using VSCode, you can use the devcontainer to get started. If you are not using VSCode, you can need to ensure that you have the following tools installed:
|
||||
|
||||
- [Go 1.19+](https://golang.org/doc/install)
|
||||
- [Swaggo](https://github.com/swaggo/swag)
|
||||
- [Node.js 16+](https://nodejs.org/en/download/)
|
||||
- [pnpm](https://pnpm.io/installation)
|
||||
- [Taskfile](https://taskfile.dev/#/installation) (Optional but recommended)
|
||||
- For code generation, you'll need to have `python3` available on your path. In most cases, this is already installed and available.
|
||||
|
||||
If you're using `taskfile` you can run `task --list-all` for a list of all commands and their descriptions.
|
||||
|
||||
### Setup
|
||||
|
||||
If you're using the taskfile you can use the `task setup` command to run the required setup commands. Otherwise you can review the commands required in the `Taskfile.yml` file.
|
||||
|
||||
Note that when installing dependencies with pnpm you must use the `--shamefully-hoist` flag. If you don't use this flag you will get an error when running the the frontend server.
|
||||
|
||||
### API Development Notes
|
||||
|
||||
start command `task go:run`
|
||||
|
||||
1. API Server does not auto reload. You'll need to restart the server after making changes.
|
||||
2. Unit tests should be written in Go, however end-to-end or user story tests should be written in TypeScript using the client library in the frontend directory.
|
||||
|
||||
### Frontend Development Notes
|
||||
|
||||
start command `task: ui:dev`
|
||||
|
||||
1. The frontend is a Vue 3 app with Nuxt.js that uses Tailwind and DaisyUI for styling.
|
||||
2. We're using Vitest for our automated testing. you can run these with `task ui:watch`.
|
||||
3. Tests require the API server to be running and in some cases the first run will fail due to a race condition. If this happens just run the tests again and they should pass.
|
||||
@@ -12,7 +12,6 @@ RUN pnpm build
|
||||
FROM golang:alpine AS builder
|
||||
ARG BUILD_TIME
|
||||
ARG COMMIT
|
||||
ARG VERSION
|
||||
RUN apk update && \
|
||||
apk upgrade && \
|
||||
apk add --update git build-base gcc g++
|
||||
@@ -21,9 +20,9 @@ WORKDIR /go/src/app
|
||||
COPY ./backend .
|
||||
RUN go get -d -v ./...
|
||||
RUN rm -rf ./app/api/public
|
||||
COPY --from=frontend-builder /app/.output/public ./app/api/static/public
|
||||
COPY --from=frontend-builder /app/.output/public ./app/api/public
|
||||
RUN CGO_ENABLED=1 GOOS=linux go build \
|
||||
-ldflags "-s -w -X main.commit=$COMMIT -X main.buildTime=$BUILD_TIME -X main.version=$VERSION" \
|
||||
-ldflags "-s -w -X main.Commit=$COMMIT -X main.BuildTime=$BUILD_TIME" \
|
||||
-o /go/bin/api \
|
||||
-v ./app/api/*.go
|
||||
|
||||
|
||||
123
Taskfile.yml
123
Taskfile.yml
@@ -2,15 +2,8 @@ version: "3"
|
||||
|
||||
env:
|
||||
HBOX_STORAGE_SQLITE_URL: .data/homebox.db?_fk=1
|
||||
UNSAFE_DISABLE_PASSWORD_PROJECTION: "yes_i_am_sure"
|
||||
tasks:
|
||||
setup:
|
||||
desc: Install development dependencies
|
||||
cmds:
|
||||
- go install github.com/swaggo/swag/cmd/swag@latest
|
||||
- cd backend && go mod tidy
|
||||
- cd frontend && pnpm install --shamefully-hoist
|
||||
|
||||
tasks:
|
||||
generate:
|
||||
desc: |
|
||||
Generates collateral files from the backend project
|
||||
@@ -18,27 +11,26 @@ tasks:
|
||||
deps:
|
||||
- db:generate
|
||||
cmds:
|
||||
- cd backend/app/api/static && swag fmt --dir=../
|
||||
- cd backend/app/api/static && swag init --dir=../,../../../internal,../../../pkgs
|
||||
- cd backend/app/api/ && swag fmt
|
||||
- cd backend/app/api/ && swag init --dir=./,../../internal,../../pkgs
|
||||
- |
|
||||
npx swagger-typescript-api \
|
||||
--no-client \
|
||||
--modular \
|
||||
--path ./backend/app/api/static/docs/swagger.json \
|
||||
--path ./backend/app/api/docs/swagger.json \
|
||||
--output ./frontend/lib/api/types
|
||||
- go run ./scripts/process-types/*.go ./frontend/lib/api/types/data-contracts.ts
|
||||
- python3 ./scripts/process-types.py ./frontend/lib/api/types/data-contracts.ts
|
||||
sources:
|
||||
- "./backend/app/api/**/*"
|
||||
- "./backend/internal/data/**"
|
||||
- "./backend/internal/repo/**/*"
|
||||
- "./backend/internal/services/**/*"
|
||||
- "./scripts/process-types.py"
|
||||
generates:
|
||||
- "./frontend/lib/api/types/data-contracts.ts"
|
||||
- "./backend/internal/data/ent/schema"
|
||||
- "./backend/app/api/static/docs/swagger.json"
|
||||
- "./backend/app/api/static/docs/swagger.yaml"
|
||||
- "./backend/app/api/docs/swagger.json"
|
||||
- "./backend/app/api/docs/swagger.yaml"
|
||||
|
||||
go:run:
|
||||
api:
|
||||
desc: Starts the backend api server (depends on generate task)
|
||||
deps:
|
||||
- generate
|
||||
@@ -46,72 +38,57 @@ tasks:
|
||||
- cd backend && go run ./app/api/ {{ .CLI_ARGS }}
|
||||
silent: false
|
||||
|
||||
go:test:
|
||||
desc: Runs all go tests using gotestsum - supports passing gotestsum args
|
||||
api:build:
|
||||
cmds:
|
||||
- cd backend && gotestsum {{ .CLI_ARGS }} ./...
|
||||
- cd backend && go build ./app/api/
|
||||
silent: true
|
||||
|
||||
go:coverage:
|
||||
desc: Runs all go tests with -race flag and generates a coverage report
|
||||
api:test:
|
||||
cmds:
|
||||
- cd backend && go test ./app/api/
|
||||
silent: true
|
||||
|
||||
api:watch:
|
||||
cmds:
|
||||
- cd backend && gotestsum --watch ./...
|
||||
|
||||
api:coverage:
|
||||
cmds:
|
||||
- cd backend && go test -race -coverprofile=coverage.out -covermode=atomic ./app/... ./internal/... ./pkgs/... -v -cover
|
||||
silent: true
|
||||
|
||||
go:tidy:
|
||||
desc: Runs go mod tidy on the backend
|
||||
cmds:
|
||||
- cd backend && go mod tidy
|
||||
|
||||
go:lint:
|
||||
desc: Runs golangci-lint
|
||||
cmds:
|
||||
- cd backend && golangci-lint run ./...
|
||||
|
||||
go:all:
|
||||
desc: Runs all go test and lint related tasks
|
||||
cmds:
|
||||
- task: go:tidy
|
||||
- task: go:lint
|
||||
- task: go:test
|
||||
|
||||
go:build:
|
||||
desc: Builds the backend binary
|
||||
cmds:
|
||||
- cd backend && go build -o ../build/backend ./app/api
|
||||
|
||||
db:generate:
|
||||
desc: Run Entgo.io Code Generation
|
||||
cmds:
|
||||
- |
|
||||
cd backend/internal/ && go generate ./... \
|
||||
--template=./data/ent/schema/templates/has_id.tmpl
|
||||
sources:
|
||||
- "./backend/internal/data/ent/schema/**/*"
|
||||
generates:
|
||||
- "./backend/internal/ent/"
|
||||
|
||||
db:migration:
|
||||
desc: Runs the database diff engine to generate a SQL migration files
|
||||
deps:
|
||||
- db:generate
|
||||
cmds:
|
||||
- cd backend && go run app/tools/migrations/main.go {{ .CLI_ARGS }}
|
||||
|
||||
ui:watch:
|
||||
desc: Starts the vitest test runner in watch mode
|
||||
cmds:
|
||||
- cd frontend && pnpm run test:watch
|
||||
|
||||
ui:dev:
|
||||
desc: Run frontend development server
|
||||
cmds:
|
||||
- cd frontend && pnpm dev
|
||||
|
||||
test:ci:
|
||||
desc: Runs end-to-end test on a live server (only for use in CI)
|
||||
cmds:
|
||||
- cd backend && go build ./app/api
|
||||
- backend/api &
|
||||
- sleep 5
|
||||
- cd frontend && pnpm run test:ci
|
||||
silent: true
|
||||
|
||||
frontend:watch:
|
||||
desc: Starts the vitest test runner in watch mode
|
||||
cmds:
|
||||
- cd frontend && pnpm vitest --watch
|
||||
|
||||
frontend:
|
||||
desc: Run frontend development server
|
||||
cmds:
|
||||
- cd frontend && pnpm dev
|
||||
|
||||
db:generate:
|
||||
desc: Run Entgo.io Code Generation
|
||||
cmds:
|
||||
- |
|
||||
cd backend && go generate ./... \
|
||||
--template=ent/schema/templates/has_id.tmpl
|
||||
sources:
|
||||
- "./backend/ent/schema/**/*"
|
||||
generates:
|
||||
- "./backend/ent/"
|
||||
|
||||
db:migration:
|
||||
desc: Runs the database diff engine to generate a SQL migration files
|
||||
deps:
|
||||
- db:generate
|
||||
cmds:
|
||||
- cd backend && go run app/migrations/main.go {{ .CLI_ARGS }}
|
||||
|
||||
@@ -3,10 +3,10 @@ package main
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/config"
|
||||
"github.com/hay-kot/homebox/backend/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/config"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/mailer"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/csv"
|
||||
"strings"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
@@ -21,7 +21,7 @@ func (a *app) SetupDemo() {
|
||||
|
||||
var (
|
||||
registration = services.UserRegistration{
|
||||
Email: "demo@example.com",
|
||||
Email: "demo@email.com",
|
||||
Name: "Demo",
|
||||
Password: "demo",
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (a *app) SetupDemo() {
|
||||
log.Fatal().Msg("Failed to setup demo")
|
||||
}
|
||||
|
||||
_, err = a.services.Items.CsvImport(context.Background(), self.GroupID, records)
|
||||
err = a.services.Items.CsvImport(context.Background(), self.GroupID, records)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("Failed to import CSV")
|
||||
log.Fatal().Msg("Failed to setup demo")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -9,41 +9,6 @@ definitions:
|
||||
title:
|
||||
type: string
|
||||
type: object
|
||||
repo.Group:
|
||||
properties:
|
||||
createdAt:
|
||||
type: string
|
||||
currency:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
updatedAt:
|
||||
type: string
|
||||
type: object
|
||||
repo.GroupStatistics:
|
||||
properties:
|
||||
totalItemPrice:
|
||||
type: number
|
||||
totalItems:
|
||||
type: integer
|
||||
totalLabels:
|
||||
type: integer
|
||||
totalLocations:
|
||||
type: integer
|
||||
totalUsers:
|
||||
type: integer
|
||||
totalWithWarranty:
|
||||
type: integer
|
||||
type: object
|
||||
repo.GroupUpdate:
|
||||
properties:
|
||||
currency:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
repo.ItemAttachment:
|
||||
properties:
|
||||
createdAt:
|
||||
@@ -77,50 +42,17 @@ definitions:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
parentId:
|
||||
type: string
|
||||
x-nullable: true
|
||||
type: object
|
||||
repo.ItemField:
|
||||
properties:
|
||||
booleanValue:
|
||||
type: boolean
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
numberValue:
|
||||
type: integer
|
||||
textValue:
|
||||
type: string
|
||||
timeValue:
|
||||
type: string
|
||||
type:
|
||||
type: string
|
||||
type: object
|
||||
repo.ItemOut:
|
||||
properties:
|
||||
archived:
|
||||
type: boolean
|
||||
assetId:
|
||||
example: "0"
|
||||
type: string
|
||||
attachments:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ItemAttachment'
|
||||
type: array
|
||||
children:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ItemSummary'
|
||||
type: array
|
||||
createdAt:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
fields:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ItemField'
|
||||
type: array
|
||||
id:
|
||||
type: string
|
||||
insured:
|
||||
@@ -135,8 +67,6 @@ definitions:
|
||||
location:
|
||||
$ref: '#/definitions/repo.LocationSummary'
|
||||
description: Edges
|
||||
x-nullable: true
|
||||
x-omitempty: true
|
||||
manufacturer:
|
||||
type: string
|
||||
modelNumber:
|
||||
@@ -146,10 +76,6 @@ definitions:
|
||||
notes:
|
||||
description: Extras
|
||||
type: string
|
||||
parent:
|
||||
$ref: '#/definitions/repo.ItemSummary'
|
||||
x-nullable: true
|
||||
x-omitempty: true
|
||||
purchaseFrom:
|
||||
type: string
|
||||
purchasePrice:
|
||||
@@ -181,8 +107,6 @@ definitions:
|
||||
type: object
|
||||
repo.ItemSummary:
|
||||
properties:
|
||||
archived:
|
||||
type: boolean
|
||||
createdAt:
|
||||
type: string
|
||||
description:
|
||||
@@ -198,13 +122,8 @@ definitions:
|
||||
location:
|
||||
$ref: '#/definitions/repo.LocationSummary'
|
||||
description: Edges
|
||||
x-nullable: true
|
||||
x-omitempty: true
|
||||
name:
|
||||
type: string
|
||||
purchasePrice:
|
||||
example: "0"
|
||||
type: string
|
||||
quantity:
|
||||
type: integer
|
||||
updatedAt:
|
||||
@@ -212,16 +131,8 @@ definitions:
|
||||
type: object
|
||||
repo.ItemUpdate:
|
||||
properties:
|
||||
archived:
|
||||
type: boolean
|
||||
assetId:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
fields:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ItemField'
|
||||
type: array
|
||||
id:
|
||||
type: string
|
||||
insured:
|
||||
@@ -245,10 +156,6 @@ definitions:
|
||||
notes:
|
||||
description: Extras
|
||||
type: string
|
||||
parentId:
|
||||
type: string
|
||||
x-nullable: true
|
||||
x-omitempty: true
|
||||
purchaseFrom:
|
||||
type: string
|
||||
purchasePrice:
|
||||
@@ -275,7 +182,6 @@ definitions:
|
||||
warrantyDetails:
|
||||
type: string
|
||||
warrantyExpires:
|
||||
description: Sold
|
||||
type: string
|
||||
type: object
|
||||
repo.LabelCreate:
|
||||
@@ -323,16 +229,9 @@ definitions:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
parentId:
|
||||
type: string
|
||||
x-nullable: true
|
||||
type: object
|
||||
repo.LocationOut:
|
||||
properties:
|
||||
children:
|
||||
items:
|
||||
$ref: '#/definitions/repo.LocationSummary'
|
||||
type: array
|
||||
createdAt:
|
||||
type: string
|
||||
description:
|
||||
@@ -345,8 +244,6 @@ definitions:
|
||||
type: array
|
||||
name:
|
||||
type: string
|
||||
parent:
|
||||
$ref: '#/definitions/repo.LocationSummary'
|
||||
updatedAt:
|
||||
type: string
|
||||
type: object
|
||||
@@ -378,104 +275,6 @@ definitions:
|
||||
updatedAt:
|
||||
type: string
|
||||
type: object
|
||||
repo.LocationUpdate:
|
||||
properties:
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
parentId:
|
||||
type: string
|
||||
x-nullable: true
|
||||
type: object
|
||||
repo.MaintenanceEntry:
|
||||
properties:
|
||||
cost:
|
||||
example: "0"
|
||||
type: string
|
||||
date:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
repo.MaintenanceEntryCreate:
|
||||
properties:
|
||||
cost:
|
||||
example: "0"
|
||||
type: string
|
||||
date:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
repo.MaintenanceEntryUpdate:
|
||||
properties:
|
||||
cost:
|
||||
example: "0"
|
||||
type: string
|
||||
date:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
repo.MaintenanceLog:
|
||||
properties:
|
||||
costAverage:
|
||||
type: number
|
||||
costTotal:
|
||||
type: number
|
||||
entries:
|
||||
items:
|
||||
$ref: '#/definitions/repo.MaintenanceEntry'
|
||||
type: array
|
||||
itemId:
|
||||
type: string
|
||||
type: object
|
||||
repo.PaginationResult-repo_ItemSummary:
|
||||
properties:
|
||||
items:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ItemSummary'
|
||||
type: array
|
||||
page:
|
||||
type: integer
|
||||
pageSize:
|
||||
type: integer
|
||||
total:
|
||||
type: integer
|
||||
type: object
|
||||
repo.TotalsByOrganizer:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
total:
|
||||
type: number
|
||||
type: object
|
||||
repo.TreeItem:
|
||||
properties:
|
||||
children:
|
||||
items:
|
||||
$ref: '#/definitions/repo.TreeItem'
|
||||
type: array
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type:
|
||||
type: string
|
||||
type: object
|
||||
repo.UserOut:
|
||||
properties:
|
||||
email:
|
||||
@@ -500,39 +299,6 @@ definitions:
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
repo.ValueOverTime:
|
||||
properties:
|
||||
end:
|
||||
type: string
|
||||
entries:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ValueOverTimeEntry'
|
||||
type: array
|
||||
start:
|
||||
type: string
|
||||
valueAtEnd:
|
||||
type: number
|
||||
valueAtStart:
|
||||
type: number
|
||||
type: object
|
||||
repo.ValueOverTimeEntry:
|
||||
properties:
|
||||
date:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
value:
|
||||
type: number
|
||||
type: object
|
||||
server.ErrorResponse:
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
fields:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
type: object
|
||||
server.Result:
|
||||
properties:
|
||||
details: {}
|
||||
@@ -544,7 +310,15 @@ definitions:
|
||||
type: object
|
||||
server.Results:
|
||||
properties:
|
||||
items: {}
|
||||
items:
|
||||
type: any
|
||||
type: object
|
||||
server.ValidationError:
|
||||
properties:
|
||||
field:
|
||||
type: string
|
||||
reason:
|
||||
type: string
|
||||
type: object
|
||||
services.UserRegistration:
|
||||
properties:
|
||||
@@ -557,11 +331,6 @@ definitions:
|
||||
token:
|
||||
type: string
|
||||
type: object
|
||||
v1.ActionAmountResult:
|
||||
properties:
|
||||
completed:
|
||||
type: integer
|
||||
type: object
|
||||
v1.ApiSummary:
|
||||
properties:
|
||||
build:
|
||||
@@ -618,8 +387,6 @@ definitions:
|
||||
type: object
|
||||
v1.TokenResponse:
|
||||
properties:
|
||||
attachmentToken:
|
||||
type: string
|
||||
expiresAt:
|
||||
type: string
|
||||
token:
|
||||
@@ -636,88 +403,6 @@ info:
|
||||
title: Go API Templates
|
||||
version: "1.0"
|
||||
paths:
|
||||
/v1/actions/ensure-asset-ids:
|
||||
post:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/v1.ActionAmountResult'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Ensures all items in the database have an asset id
|
||||
tags:
|
||||
- Group
|
||||
/v1/actions/zero-item-time-fields:
|
||||
post:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/v1.ActionAmountResult'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Resets all item date fields to the beginning of the day
|
||||
tags:
|
||||
- Group
|
||||
/v1/assets/{id}:
|
||||
get:
|
||||
parameters:
|
||||
- description: Asset ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.PaginationResult-repo_ItemSummary'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Gets an item by Asset ID
|
||||
tags:
|
||||
- Assets
|
||||
/v1/groups:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.Group'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get the current user's group
|
||||
tags:
|
||||
- Group
|
||||
put:
|
||||
parameters:
|
||||
- description: User Data
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/repo.GroupUpdate'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.Group'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Updates some fields of the current users group
|
||||
tags:
|
||||
- Group
|
||||
/v1/groups/invitations:
|
||||
post:
|
||||
parameters:
|
||||
@@ -738,112 +423,23 @@ paths:
|
||||
- Bearer: []
|
||||
summary: Get the current user
|
||||
tags:
|
||||
- Group
|
||||
/v1/groups/statistics:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.GroupStatistics'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get the current user's group statistics
|
||||
tags:
|
||||
- Statistics
|
||||
/v1/groups/statistics/labels:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/repo.TotalsByOrganizer'
|
||||
type: array
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get the current user's group statistics
|
||||
tags:
|
||||
- Statistics
|
||||
/v1/groups/statistics/locations:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/repo.TotalsByOrganizer'
|
||||
type: array
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get the current user's group statistics
|
||||
tags:
|
||||
- Statistics
|
||||
/v1/groups/statistics/purchase-price:
|
||||
get:
|
||||
parameters:
|
||||
- description: start date
|
||||
in: query
|
||||
name: start
|
||||
type: string
|
||||
- description: end date
|
||||
in: query
|
||||
name: end
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.ValueOverTime'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Queries the changes overtime of the purchase price over time
|
||||
tags:
|
||||
- Statistics
|
||||
- User
|
||||
/v1/items:
|
||||
get:
|
||||
parameters:
|
||||
- description: search string
|
||||
in: query
|
||||
name: q
|
||||
type: string
|
||||
- description: page number
|
||||
in: query
|
||||
name: page
|
||||
type: integer
|
||||
- description: items per page
|
||||
in: query
|
||||
name: pageSize
|
||||
type: integer
|
||||
- collectionFormat: multi
|
||||
description: label Ids
|
||||
in: query
|
||||
items:
|
||||
type: string
|
||||
name: labels
|
||||
type: array
|
||||
- collectionFormat: multi
|
||||
description: location Ids
|
||||
in: query
|
||||
items:
|
||||
type: string
|
||||
name: locations
|
||||
type: array
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.PaginationResult-repo_ItemSummary'
|
||||
allOf:
|
||||
- $ref: '#/definitions/server.Results'
|
||||
- properties:
|
||||
items:
|
||||
items:
|
||||
$ref: '#/definitions/repo.ItemSummary'
|
||||
type: array
|
||||
type: object
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get All Items
|
||||
@@ -881,7 +477,7 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: deletes a item
|
||||
@@ -964,12 +560,14 @@ paths:
|
||||
"422":
|
||||
description: Unprocessable Entity
|
||||
schema:
|
||||
$ref: '#/definitions/server.ErrorResponse'
|
||||
items:
|
||||
$ref: '#/definitions/server.ValidationError'
|
||||
type: array
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: imports items into the database
|
||||
tags:
|
||||
- Items Attachments
|
||||
- Items
|
||||
/v1/items/{id}/attachments/{attachment_id}:
|
||||
delete:
|
||||
parameters:
|
||||
@@ -985,12 +583,12 @@ paths:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: retrieves an attachment for an item
|
||||
tags:
|
||||
- Items Attachments
|
||||
- Items
|
||||
get:
|
||||
parameters:
|
||||
- description: Item ID
|
||||
@@ -1014,7 +612,7 @@ paths:
|
||||
- Bearer: []
|
||||
summary: retrieves an attachment for an item
|
||||
tags:
|
||||
- Items Attachments
|
||||
- Items
|
||||
put:
|
||||
parameters:
|
||||
- description: Item ID
|
||||
@@ -1042,103 +640,28 @@ paths:
|
||||
- Bearer: []
|
||||
summary: retrieves an attachment for an item
|
||||
tags:
|
||||
- Items Attachments
|
||||
/v1/items/{id}/maintenance:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.MaintenanceLog'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get Maintenance Log
|
||||
tags:
|
||||
- Maintenance
|
||||
post:
|
||||
parameters:
|
||||
- description: Entry Data
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/repo.MaintenanceEntryCreate'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.MaintenanceEntry'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Create Maintenance Entry
|
||||
tags:
|
||||
- Maintenance
|
||||
/v1/items/{id}/maintenance/{entry_id}:
|
||||
delete:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Delete Maintenance Entry
|
||||
tags:
|
||||
- Maintenance
|
||||
put:
|
||||
parameters:
|
||||
- description: Entry Data
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/repo.MaintenanceEntryUpdate'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/repo.MaintenanceEntry'
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Update Maintenance Entry
|
||||
tags:
|
||||
- Maintenance
|
||||
/v1/items/fields:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: imports items into the database
|
||||
tags:
|
||||
- Items
|
||||
/v1/items/fields/values:
|
||||
/v1/items/{id}/attachments/download:
|
||||
get:
|
||||
parameters:
|
||||
- description: Item ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: string
|
||||
- description: Attachment token
|
||||
in: query
|
||||
name: token
|
||||
required: true
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
- application/octet-stream
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: imports items into the database
|
||||
summary: retrieves an attachment for an item
|
||||
tags:
|
||||
- Items
|
||||
/v1/items/import:
|
||||
@@ -1153,7 +676,7 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: imports items into the database
|
||||
@@ -1212,7 +735,7 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: deletes a label
|
||||
@@ -1258,11 +781,6 @@ paths:
|
||||
- Labels
|
||||
/v1/locations:
|
||||
get:
|
||||
parameters:
|
||||
- description: Filter locations with parents
|
||||
in: query
|
||||
name: filterChildren
|
||||
type: boolean
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
@@ -1314,7 +832,7 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: deletes a location
|
||||
@@ -1346,12 +864,6 @@ paths:
|
||||
name: id
|
||||
required: true
|
||||
type: string
|
||||
- description: Location Data
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/repo.LocationUpdate'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
@@ -1364,65 +876,6 @@ paths:
|
||||
summary: updates a location
|
||||
tags:
|
||||
- Locations
|
||||
/v1/locations/tree:
|
||||
get:
|
||||
parameters:
|
||||
- description: include items in response tree
|
||||
in: query
|
||||
name: withItems
|
||||
type: boolean
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/definitions/server.Results'
|
||||
- properties:
|
||||
items:
|
||||
items:
|
||||
$ref: '#/definitions/repo.TreeItem'
|
||||
type: array
|
||||
type: object
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Get All Locations
|
||||
tags:
|
||||
- Locations
|
||||
/v1/qrcode:
|
||||
get:
|
||||
parameters:
|
||||
- description: data to be encoded into qrcode
|
||||
in: query
|
||||
name: data
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: image/jpeg
|
||||
schema:
|
||||
type: string
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Encode data into QRCode
|
||||
tags:
|
||||
- Items
|
||||
/v1/reporting/bill-of-materials:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: text/csv
|
||||
schema:
|
||||
type: string
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Generates a Bill of Materials CSV
|
||||
tags:
|
||||
- Reporting
|
||||
/v1/status:
|
||||
get:
|
||||
produces:
|
||||
@@ -1446,7 +899,7 @@ paths:
|
||||
$ref: '#/definitions/v1.ChangePassword'
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Updates the users password
|
||||
@@ -1482,7 +935,7 @@ paths:
|
||||
post:
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: User Logout
|
||||
@@ -1495,7 +948,7 @@ paths:
|
||||
This does not validate that the user still exists within the database.
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: User Token Refresh
|
||||
@@ -1514,7 +967,7 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
summary: Get the current user
|
||||
tags:
|
||||
- User
|
||||
@@ -1524,7 +977,7 @@ paths:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: Deletes the user account
|
||||
@@ -1573,6 +1026,18 @@ paths:
|
||||
summary: Update the current user
|
||||
tags:
|
||||
- User
|
||||
/v1/users/self/password:
|
||||
put:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: ""
|
||||
security:
|
||||
- Bearer: []
|
||||
summary: 'Update the current user''s password // TODO:'
|
||||
tags:
|
||||
- User
|
||||
securityDefinitions:
|
||||
Bearer:
|
||||
description: '"Type ''Bearer TOKEN'' to correctly set the API Key"'
|
||||
@@ -1,16 +0,0 @@
|
||||
package debughandlers
|
||||
|
||||
import (
|
||||
"expvar"
|
||||
"net/http"
|
||||
"net/http/pprof"
|
||||
)
|
||||
|
||||
func New(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/debug/pprof", pprof.Index)
|
||||
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
||||
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
||||
mux.Handle("/debug/vars", expvar.Handler())
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.5 KiB |
@@ -1,27 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
)
|
||||
|
||||
// routeID extracts the ID from the request URL. If the ID is not in a valid
|
||||
// format, an error is returned. If a error is returned, it can be directly returned
|
||||
// from the handler. the validate.ErrInvalidID error is known by the error middleware
|
||||
// and will be handled accordingly.
|
||||
//
|
||||
// Example: /api/v1/ac614db5-d8b8-4659-9b14-6e913a6eb18a -> uuid.UUID{ac614db5-d8b8-4659-9b14-6e913a6eb18a}
|
||||
func (ctrl *V1Controller) routeID(r *http.Request) (uuid.UUID, error) {
|
||||
return ctrl.routeUUID(r, "id")
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) routeUUID(r *http.Request, key string) (uuid.UUID, error) {
|
||||
ID, err := uuid.Parse(chi.URLParam(r, key))
|
||||
if err != nil {
|
||||
return uuid.Nil, validate.NewInvalidRouteKeyError(key)
|
||||
}
|
||||
return ID, nil
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func queryUUIDList(params url.Values, key string) []uuid.UUID {
|
||||
var ids []uuid.UUID
|
||||
for _, id := range params[key] {
|
||||
uid, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, uid)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func queryIntOrNegativeOne(s string) int {
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
func queryBool(s string) bool {
|
||||
b, err := strconv.ParseBool(s)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type ActionAmountResult struct {
|
||||
Completed int `json:"completed"`
|
||||
}
|
||||
|
||||
// HandleGroupInvitationsCreate godoc
|
||||
// @Summary Ensures all items in the database have an asset id
|
||||
// @Tags Group
|
||||
// @Produce json
|
||||
// @Success 200 {object} ActionAmountResult
|
||||
// @Router /v1/actions/ensure-asset-ids [Post]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleEnsureAssetID() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
totalCompleted, err := ctrl.svc.Items.EnsureAssetID(ctx, ctx.GID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to ensure asset id")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, ActionAmountResult{Completed: totalCompleted})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemDateZeroOut godoc
|
||||
// @Summary Resets all item date fields to the beginning of the day
|
||||
// @Tags Group
|
||||
// @Produce json
|
||||
// @Success 200 {object} ActionAmountResult
|
||||
// @Router /v1/actions/zero-item-time-fields [Post]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemDateZeroOut() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
totalCompleted, err := ctrl.repo.Items.ZeroOutTimeFields(ctx, ctx.GID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to ensure asset id")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, ActionAmountResult{Completed: totalCompleted})
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleItemGet godocs
|
||||
// @Summary Gets an item by Asset ID
|
||||
// @Tags Assets
|
||||
// @Produce json
|
||||
// @Param id path string true "Asset ID"
|
||||
// @Success 200 {object} repo.PaginationResult[repo.ItemSummary]{}
|
||||
// @Router /v1/assets/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleAssetGet() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
assetIdParam := chi.URLParam(r, "id")
|
||||
assetIdParam = strings.ReplaceAll(assetIdParam, "-", "") // Remove dashes
|
||||
// Convert the asset ID to an int64
|
||||
assetId, err := strconv.ParseInt(assetIdParam, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pageParam := r.URL.Query().Get("page")
|
||||
var page int64 = -1
|
||||
if pageParam != "" {
|
||||
page, err = strconv.ParseInt(pageParam, 10, 64)
|
||||
if err != nil {
|
||||
return server.Respond(w, http.StatusBadRequest, "Invalid page number")
|
||||
}
|
||||
}
|
||||
|
||||
pageSizeParam := r.URL.Query().Get("pageSize")
|
||||
var pageSize int64 = -1
|
||||
if pageSizeParam != "" {
|
||||
pageSize, err = strconv.ParseInt(pageSizeParam, 10, 64)
|
||||
if err != nil {
|
||||
return server.Respond(w, http.StatusBadRequest, "Invalid page size")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetId), int(page), int(pageSize))
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, items)
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
TokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
AttachmentToken string `json:"attachmentToken"`
|
||||
}
|
||||
|
||||
LoginForm struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleAuthLogin godoc
|
||||
// @Summary User Login
|
||||
// @Tags Authentication
|
||||
// @Accept x-www-form-urlencoded
|
||||
// @Accept application/json
|
||||
// @Param username formData string false "string" example(admin@admin.com)
|
||||
// @Param password formData string false "string" example(admin)
|
||||
// @Produce json
|
||||
// @Success 200 {object} TokenResponse
|
||||
// @Router /v1/users/login [POST]
|
||||
func (ctrl *V1Controller) HandleAuthLogin() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
loginForm := &LoginForm{}
|
||||
|
||||
switch r.Header.Get("Content-Type") {
|
||||
case server.ContentFormUrlEncoded:
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
return server.Respond(w, http.StatusBadRequest, server.Wrap(err))
|
||||
}
|
||||
|
||||
loginForm.Username = r.PostFormValue("username")
|
||||
loginForm.Password = r.PostFormValue("password")
|
||||
case server.ContentJSON:
|
||||
err := server.Decode(r, loginForm)
|
||||
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to decode login form")
|
||||
}
|
||||
default:
|
||||
return server.Respond(w, http.StatusBadRequest, errors.New("invalid content type"))
|
||||
}
|
||||
|
||||
if loginForm.Username == "" || loginForm.Password == "" {
|
||||
return validate.NewFieldErrors(
|
||||
validate.FieldError{
|
||||
Field: "username",
|
||||
Error: "username or password is empty",
|
||||
},
|
||||
validate.FieldError{
|
||||
Field: "password",
|
||||
Error: "username or password is empty",
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
newToken, err := ctrl.svc.User.Login(r.Context(), strings.ToLower(loginForm.Username), loginForm.Password)
|
||||
|
||||
if err != nil {
|
||||
return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, TokenResponse{
|
||||
Token: "Bearer " + newToken.Raw,
|
||||
ExpiresAt: newToken.ExpiresAt,
|
||||
AttachmentToken: newToken.AttachmentToken,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAuthLogout godoc
|
||||
// @Summary User Logout
|
||||
// @Tags Authentication
|
||||
// @Success 204
|
||||
// @Router /v1/users/logout [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleAuthLogout() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
token := services.UseTokenCtx(r.Context())
|
||||
if token == "" {
|
||||
return validate.NewRequestError(errors.New("no token within request context"), http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
err := ctrl.svc.User.Logout(r.Context(), token)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAuthLogout godoc
|
||||
// @Summary User Token Refresh
|
||||
// @Description handleAuthRefresh returns a handler that will issue a new token from an existing token.
|
||||
// @Description This does not validate that the user still exists within the database.
|
||||
// @Tags Authentication
|
||||
// @Success 200
|
||||
// @Router /v1/users/refresh [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleAuthRefresh() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
requestToken := services.UseTokenCtx(r.Context())
|
||||
if requestToken == "" {
|
||||
return validate.NewRequestError(errors.New("no token within request context"), http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
newToken, err := ctrl.svc.User.RenewToken(r.Context(), requestToken)
|
||||
if err != nil {
|
||||
return validate.NewUnauthorizedError()
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, newToken)
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
GroupInvitationCreate struct {
|
||||
Uses int `json:"uses"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
GroupInvitation struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Uses int `json:"uses"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleGroupGet godoc
|
||||
// @Summary Get the current user's group
|
||||
// @Tags Group
|
||||
// @Produce json
|
||||
// @Success 200 {object} repo.Group
|
||||
// @Router /v1/groups [Get]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupGet() server.HandlerFunc {
|
||||
return ctrl.handleGroupGeneral()
|
||||
}
|
||||
|
||||
// HandleGroupUpdate godoc
|
||||
// @Summary Updates some fields of the current users group
|
||||
// @Tags Group
|
||||
// @Produce json
|
||||
// @Param payload body repo.GroupUpdate true "User Data"
|
||||
// @Success 200 {object} repo.Group
|
||||
// @Router /v1/groups [Put]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupUpdate() server.HandlerFunc {
|
||||
return ctrl.handleGroupGeneral()
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleGroupGeneral() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
group, err := ctrl.repo.Groups.GroupByID(ctx, ctx.GID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get group")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, group)
|
||||
|
||||
case http.MethodPut:
|
||||
data := repo.GroupUpdate{}
|
||||
if err := server.Decode(r, &data); err != nil {
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
group, err := ctrl.svc.Group.UpdateGroup(ctx, data)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to update group")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, group)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGroupInvitationsCreate godoc
|
||||
// @Summary Get the current user
|
||||
// @Tags Group
|
||||
// @Produce json
|
||||
// @Param payload body GroupInvitationCreate true "User Data"
|
||||
// @Success 200 {object} GroupInvitation
|
||||
// @Router /v1/groups/invitations [Post]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupInvitationsCreate() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
data := GroupInvitationCreate{}
|
||||
if err := server.Decode(r, &data); err != nil {
|
||||
log.Err(err).Msg("failed to decode user registration data")
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if data.ExpiresAt.IsZero() {
|
||||
data.ExpiresAt = time.Now().Add(time.Hour * 24)
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
token, err := ctrl.svc.Group.NewInvitation(ctx, data.Uses, data.ExpiresAt)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create new token")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusCreated, GroupInvitation{
|
||||
Token: token,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
Uses: data.Uses,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleItemsGetAll godoc
|
||||
// @Summary Get All Items
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param q query string false "search string"
|
||||
// @Param page query int false "page number"
|
||||
// @Param pageSize query int false "items per page"
|
||||
// @Param labels query []string false "label Ids" collectionFormat(multi)
|
||||
// @Param locations query []string false "location Ids" collectionFormat(multi)
|
||||
// @Success 200 {object} repo.PaginationResult[repo.ItemSummary]{}
|
||||
// @Router /v1/items [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemsGetAll() server.HandlerFunc {
|
||||
|
||||
extractQuery := func(r *http.Request) repo.ItemQuery {
|
||||
params := r.URL.Query()
|
||||
|
||||
filterFieldItems := func(raw []string) []repo.FieldQuery {
|
||||
var items []repo.FieldQuery
|
||||
|
||||
for _, v := range raw {
|
||||
parts := strings.SplitN(v, "=", 2)
|
||||
if len(parts) == 2 {
|
||||
items = append(items, repo.FieldQuery{
|
||||
Name: parts[0],
|
||||
Value: parts[1],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
v := repo.ItemQuery{
|
||||
Page: queryIntOrNegativeOne(params.Get("page")),
|
||||
PageSize: queryIntOrNegativeOne(params.Get("pageSize")),
|
||||
Search: params.Get("q"),
|
||||
LocationIDs: queryUUIDList(params, "locations"),
|
||||
LabelIDs: queryUUIDList(params, "labels"),
|
||||
IncludeArchived: queryBool(params.Get("includeArchived")),
|
||||
Fields: filterFieldItems(params["fields"]),
|
||||
}
|
||||
|
||||
if strings.HasPrefix(v.Search, "#") {
|
||||
aidStr := strings.TrimPrefix(v.Search, "#")
|
||||
|
||||
aid, ok := repo.ParseAssetID(aidStr)
|
||||
if ok {
|
||||
v.Search = ""
|
||||
v.AssetID = aid
|
||||
}
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GID, extractQuery(r))
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return server.Respond(w, http.StatusOK, repo.PaginationResult[repo.ItemSummary]{
|
||||
Items: []repo.ItemSummary{},
|
||||
})
|
||||
}
|
||||
log.Err(err).Msg("failed to get items")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, items)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemsCreate godoc
|
||||
// @Summary Create a new item
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param payload body repo.ItemCreate true "Item Data"
|
||||
// @Success 200 {object} repo.ItemSummary
|
||||
// @Router /v1/items [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemsCreate() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
createData := repo.ItemCreate{}
|
||||
if err := server.Decode(r, &createData); err != nil {
|
||||
log.Err(err).Msg("failed to decode request body")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
item, err := ctrl.svc.Items.Create(ctx, createData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusCreated, item)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemGet godocs
|
||||
// @Summary Gets a item and fields
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Router /v1/items/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemGet() server.HandlerFunc {
|
||||
return ctrl.handleItemsGeneral()
|
||||
}
|
||||
|
||||
// HandleItemDelete godocs
|
||||
// @Summary deletes a item
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Success 204
|
||||
// @Router /v1/items/{id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemDelete() server.HandlerFunc {
|
||||
return ctrl.handleItemsGeneral()
|
||||
}
|
||||
|
||||
// HandleItemUpdate godocs
|
||||
// @Summary updates a item
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param payload body repo.ItemUpdate true "Item Data"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Router /v1/items/{id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemUpdate() server.HandlerFunc {
|
||||
return ctrl.handleItemsGeneral()
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleItemsGeneral() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
ID, err := ctrl.routeID(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
items, err := ctrl.repo.Items.GetOneByGroup(r.Context(), ctx.GID, ID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, items)
|
||||
case http.MethodDelete:
|
||||
err = ctrl.repo.Items.DeleteByGroup(r.Context(), ctx.GID, ID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
case http.MethodPut:
|
||||
body := repo.ItemUpdate{}
|
||||
if err := server.Decode(r, &body); err != nil {
|
||||
log.Err(err).Msg("failed to decode request body")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
body.ID = ID
|
||||
result, err := ctrl.repo.Items.UpdateByGroup(r.Context(), ctx.GID, body)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to update item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGetAllCustomFieldNames godocs
|
||||
// @Summary imports items into the database
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Success 200
|
||||
// @Router /v1/items/fields [GET]
|
||||
// @Success 200 {object} []string
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGetAllCustomFieldNames() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
v, err := ctrl.repo.Items.GetAllCustomFieldNames(r.Context(), ctx.GID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, v)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGetAllCustomFieldValues godocs
|
||||
// @Summary imports items into the database
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Success 200
|
||||
// @Router /v1/items/fields/values [GET]
|
||||
// @Success 200 {object} []string
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGetAllCustomFieldValues() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
v, err := ctrl.repo.Items.GetAllCustomFieldValues(r.Context(), ctx.GID, r.URL.Query().Get("field"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, v)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemsImport godocs
|
||||
// @Summary imports items into the database
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Param csv formData file true "Image to upload"
|
||||
// @Router /v1/items/import [Post]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemsImport() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
|
||||
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to parse multipart form")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("csv")
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get file from form")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
data, err := services.ReadCsv(file)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to read csv")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
|
||||
_, err = ctrl.svc.Items.CsvImport(r.Context(), user.GroupID, data)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to import items")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
ItemAttachmentToken struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleItemsImport godocs
|
||||
// @Summary imports items into the database
|
||||
// @Tags Items Attachments
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param file formData file true "File attachment"
|
||||
// @Param type formData string true "Type of file"
|
||||
// @Param name formData string true "name of the file including extension"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Failure 422 {object} server.ErrorResponse
|
||||
// @Router /v1/items/{id}/attachments [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentCreate() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to parse multipart form")
|
||||
return validate.NewRequestError(errors.New("failed to parse multipart form"), http.StatusBadRequest)
|
||||
|
||||
}
|
||||
|
||||
errs := validate.NewFieldErrors()
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, http.ErrMissingFile):
|
||||
log.Debug().Msg("file for attachment is missing")
|
||||
errs = errs.Append("file", "file is required")
|
||||
default:
|
||||
log.Err(err).Msg("failed to get file from form")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
attachmentName := r.FormValue("name")
|
||||
if attachmentName == "" {
|
||||
log.Debug().Msg("failed to get name from form")
|
||||
errs = errs.Append("name", "name is required")
|
||||
}
|
||||
|
||||
if !errs.Nil() {
|
||||
return server.Respond(w, http.StatusUnprocessableEntity, errs)
|
||||
}
|
||||
|
||||
attachmentType := r.FormValue("type")
|
||||
if attachmentType == "" {
|
||||
attachmentType = attachment.TypeAttachment.String()
|
||||
}
|
||||
|
||||
id, err := ctrl.routeID(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
item, err := ctrl.svc.Items.AttachmentAdd(
|
||||
ctx,
|
||||
id,
|
||||
attachmentName,
|
||||
attachment.Type(attachmentType),
|
||||
file,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to add attachment")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusCreated, item)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemAttachmentGet godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items Attachments
|
||||
// @Produce application/octet-stream
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param attachment_id path string true "Attachment ID"
|
||||
// @Success 200 {object} ItemAttachmentToken
|
||||
// @Router /v1/items/{id}/attachments/{attachment_id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentGet() server.HandlerFunc {
|
||||
return ctrl.handleItemAttachmentsHandler
|
||||
}
|
||||
|
||||
// HandleItemAttachmentDelete godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items Attachments
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param attachment_id path string true "Attachment ID"
|
||||
// @Success 204
|
||||
// @Router /v1/items/{id}/attachments/{attachment_id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentDelete() server.HandlerFunc {
|
||||
return ctrl.handleItemAttachmentsHandler
|
||||
}
|
||||
|
||||
// HandleItemAttachmentUpdate godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items Attachments
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param attachment_id path string true "Attachment ID"
|
||||
// @Param payload body repo.ItemAttachmentUpdate true "Attachment Update"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Router /v1/items/{id}/attachments/{attachment_id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentUpdate() server.HandlerFunc {
|
||||
return ctrl.handleItemAttachmentsHandler
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleItemAttachmentsHandler(w http.ResponseWriter, r *http.Request) error {
|
||||
ID, err := ctrl.routeID(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
attachmentID, err := ctrl.routeUUID(r, "attachment_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
doc, err := ctrl.svc.Items.AttachmentPath(r.Context(), attachmentID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get attachment path")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
http.ServeFile(w, r, doc.Path)
|
||||
return nil
|
||||
|
||||
// Delete Attachment Handler
|
||||
case http.MethodDelete:
|
||||
err = ctrl.svc.Items.AttachmentDelete(r.Context(), ctx.GID, ID, attachmentID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete attachment")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
|
||||
// Update Attachment Handler
|
||||
case http.MethodPut:
|
||||
var attachment repo.ItemAttachmentUpdate
|
||||
err = server.Decode(r, &attachment)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to decode attachment")
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
attachment.ID = attachmentID
|
||||
val, err := ctrl.svc.Items.AttachmentUpdate(ctx, ID, &attachment)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete attachment")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, val)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleLabelsGetAll godoc
|
||||
// @Summary Get All Labels
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Results{items=[]repo.LabelOut}
|
||||
// @Router /v1/labels [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelsGetAll() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
user := services.UseUserCtx(r.Context())
|
||||
labels, err := ctrl.repo.Labels.GetAll(r.Context(), user.GroupID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error getting labels")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, server.Results{Items: labels})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLabelsCreate godoc
|
||||
// @Summary Create a new label
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param payload body repo.LabelCreate true "Label Data"
|
||||
// @Success 200 {object} repo.LabelSummary
|
||||
// @Router /v1/labels [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelsCreate() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
createData := repo.LabelCreate{}
|
||||
if err := server.Decode(r, &createData); err != nil {
|
||||
log.Err(err).Msg("error decoding label create data")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
label, err := ctrl.repo.Labels.Create(r.Context(), user.GroupID, createData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error creating label")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusCreated, label)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLabelDelete godocs
|
||||
// @Summary deletes a label
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param id path string true "Label ID"
|
||||
// @Success 204
|
||||
// @Router /v1/labels/{id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelDelete() server.HandlerFunc {
|
||||
return ctrl.handleLabelsGeneral()
|
||||
}
|
||||
|
||||
// HandleLabelGet godocs
|
||||
// @Summary Gets a label and fields
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param id path string true "Label ID"
|
||||
// @Success 200 {object} repo.LabelOut
|
||||
// @Router /v1/labels/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelGet() server.HandlerFunc {
|
||||
return ctrl.handleLabelsGeneral()
|
||||
}
|
||||
|
||||
// HandleLabelUpdate godocs
|
||||
// @Summary updates a label
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param id path string true "Label ID"
|
||||
// @Success 200 {object} repo.LabelOut
|
||||
// @Router /v1/labels/{id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelUpdate() server.HandlerFunc {
|
||||
return ctrl.handleLabelsGeneral()
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleLabelsGeneral() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
ID, err := ctrl.routeID(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
labels, err := ctrl.repo.Labels.GetOneByGroup(r.Context(), ctx.GID, ID)
|
||||
if err != nil {
|
||||
if ent.IsNotFound(err) {
|
||||
log.Err(err).
|
||||
Str("id", ID.String()).
|
||||
Msg("label not found")
|
||||
return validate.NewRequestError(err, http.StatusNotFound)
|
||||
}
|
||||
log.Err(err).Msg("error getting label")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, labels)
|
||||
|
||||
case http.MethodDelete:
|
||||
err = ctrl.repo.Labels.DeleteByGroup(ctx, ctx.GID, ID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error deleting label")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
|
||||
case http.MethodPut:
|
||||
body := repo.LabelUpdate{}
|
||||
if err := server.Decode(r, &body); err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
body.ID = ID
|
||||
result, err := ctrl.repo.Labels.UpdateByGroup(ctx, ctx.GID, body)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleLocationTreeQuery godoc
|
||||
// @Summary Get All Locations
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param withItems query bool false "include items in response tree"
|
||||
// @Success 200 {object} server.Results{items=[]repo.TreeItem}
|
||||
// @Router /v1/locations/tree [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationTreeQuery() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
user := services.UseUserCtx(r.Context())
|
||||
|
||||
q := r.URL.Query()
|
||||
|
||||
withItems := queryBool(q.Get("withItems"))
|
||||
|
||||
locTree, err := ctrl.repo.Locations.Tree(
|
||||
r.Context(),
|
||||
user.GroupID,
|
||||
repo.TreeQuery{
|
||||
WithItems: withItems,
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get locations tree")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, server.Results{Items: locTree})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationGetAll godoc
|
||||
// @Summary Get All Locations
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param filterChildren query bool false "Filter locations with parents"
|
||||
// @Success 200 {object} server.Results{items=[]repo.LocationOutCount}
|
||||
// @Router /v1/locations [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationGetAll() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
user := services.UseUserCtx(r.Context())
|
||||
|
||||
q := r.URL.Query()
|
||||
|
||||
filter := repo.LocationQuery{
|
||||
FilterChildren: queryBool(q.Get("filterChildren")),
|
||||
}
|
||||
|
||||
locations, err := ctrl.repo.Locations.GetAll(r.Context(), user.GroupID, filter)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get locations")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, server.Results{Items: locations})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationCreate godoc
|
||||
// @Summary Create a new location
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param payload body repo.LocationCreate true "Location Data"
|
||||
// @Success 200 {object} repo.LocationSummary
|
||||
// @Router /v1/locations [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationCreate() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
createData := repo.LocationCreate{}
|
||||
if err := server.Decode(r, &createData); err != nil {
|
||||
log.Err(err).Msg("failed to decode location create data")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
location, err := ctrl.repo.Locations.Create(r.Context(), user.GroupID, createData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create location")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusCreated, location)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationDelete godocs
|
||||
// @Summary deletes a location
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param id path string true "Location ID"
|
||||
// @Success 204
|
||||
// @Router /v1/locations/{id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationDelete() server.HandlerFunc {
|
||||
return ctrl.handleLocationGeneral()
|
||||
}
|
||||
|
||||
// HandleLocationGet godocs
|
||||
// @Summary Gets a location and fields
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param id path string true "Location ID"
|
||||
// @Success 200 {object} repo.LocationOut
|
||||
// @Router /v1/locations/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationGet() server.HandlerFunc {
|
||||
return ctrl.handleLocationGeneral()
|
||||
}
|
||||
|
||||
// HandleLocationUpdate godocs
|
||||
// @Summary updates a location
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param id path string true "Location ID"
|
||||
// @Param payload body repo.LocationUpdate true "Location Data"
|
||||
// @Success 200 {object} repo.LocationOut
|
||||
// @Router /v1/locations/{id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationUpdate() server.HandlerFunc {
|
||||
return ctrl.handleLocationGeneral()
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleLocationGeneral() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
ID, err := ctrl.routeID(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
location, err := ctrl.repo.Locations.GetOneByGroup(r.Context(), ctx.GID, ID)
|
||||
if err != nil {
|
||||
l := log.Err(err).
|
||||
Str("ID", ID.String()).
|
||||
Str("GID", ctx.GID.String())
|
||||
|
||||
if ent.IsNotFound(err) {
|
||||
l.Msg("location not found")
|
||||
return validate.NewRequestError(err, http.StatusNotFound)
|
||||
}
|
||||
|
||||
l.Msg("failed to get location")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, location)
|
||||
case http.MethodPut:
|
||||
body := repo.LocationUpdate{}
|
||||
if err := server.Decode(r, &body); err != nil {
|
||||
log.Err(err).Msg("failed to decode location update data")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
body.ID = ID
|
||||
|
||||
result, err := ctrl.repo.Locations.UpdateOneByGroup(r.Context(), ctx.GID, ID, body)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to update location")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, result)
|
||||
case http.MethodDelete:
|
||||
err = ctrl.repo.Locations.DeleteByGroup(r.Context(), ctx.GID, ID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete location")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleMaintenanceGetLog godoc
|
||||
// @Summary Get Maintenance Log
|
||||
// @Tags Maintenance
|
||||
// @Produce json
|
||||
// @Success 200 {object} repo.MaintenanceLog
|
||||
// @Router /v1/items/{id}/maintenance [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleMaintenanceLogGet() server.HandlerFunc {
|
||||
return ctrl.handleMaintenanceLog()
|
||||
}
|
||||
|
||||
// HandleMaintenanceEntryCreate godoc
|
||||
// @Summary Create Maintenance Entry
|
||||
// @Tags Maintenance
|
||||
// @Produce json
|
||||
// @Param payload body repo.MaintenanceEntryCreate true "Entry Data"
|
||||
// @Success 200 {object} repo.MaintenanceEntry
|
||||
// @Router /v1/items/{id}/maintenance [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleMaintenanceEntryCreate() server.HandlerFunc {
|
||||
return ctrl.handleMaintenanceLog()
|
||||
}
|
||||
|
||||
// HandleMaintenanceEntryDelete godoc
|
||||
// @Summary Delete Maintenance Entry
|
||||
// @Tags Maintenance
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Router /v1/items/{id}/maintenance/{entry_id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleMaintenanceEntryDelete() server.HandlerFunc {
|
||||
return ctrl.handleMaintenanceLog()
|
||||
}
|
||||
|
||||
// HandleMaintenanceEntryUpdate godoc
|
||||
// @Summary Update Maintenance Entry
|
||||
// @Tags Maintenance
|
||||
// @Produce json
|
||||
// @Param payload body repo.MaintenanceEntryUpdate true "Entry Data"
|
||||
// @Success 200 {object} repo.MaintenanceEntry
|
||||
// @Router /v1/items/{id}/maintenance/{entry_id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleMaintenanceEntryUpdate() server.HandlerFunc {
|
||||
return ctrl.handleMaintenanceLog()
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleMaintenanceLog() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
itemID, err := ctrl.routeID(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
mlog, err := ctrl.repo.MaintEntry.GetLog(ctx, itemID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get items")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
return server.Respond(w, http.StatusOK, mlog)
|
||||
case http.MethodPost:
|
||||
var create repo.MaintenanceEntryCreate
|
||||
err := server.Decode(r, &create)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
entry, err := ctrl.repo.MaintEntry.Create(ctx, itemID, create)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusCreated, entry)
|
||||
case http.MethodPut:
|
||||
entryID, err := ctrl.routeUUID(r, "entry_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var update repo.MaintenanceEntryUpdate
|
||||
err = server.Decode(r, &update)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
entry, err := ctrl.repo.MaintEntry.Update(ctx, entryID, update)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to update item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, entry)
|
||||
case http.MethodDelete:
|
||||
entryID, err := ctrl.routeUUID(r, "entry_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = ctrl.repo.MaintEntry.Delete(ctx, entryID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete item")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/yeqown/go-qrcode/v2"
|
||||
"github.com/yeqown/go-qrcode/writer/standard"
|
||||
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
//go:embed assets/QRIcon.png
|
||||
var qrcodeLogo []byte
|
||||
|
||||
// HandleGenerateQRCode godoc
|
||||
//
|
||||
// @Summary Encode data into QRCode
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param data query string false "data to be encoded into qrcode"
|
||||
// @Success 200 {string} string "image/jpeg"
|
||||
// @Router /v1/qrcode [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGenerateQRCode() server.HandlerFunc {
|
||||
const MaxLength = 4_296 // assume alphanumeric characters only
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
data := r.URL.Query().Get("data")
|
||||
|
||||
image, err := png.Decode(bytes.NewReader(qrcodeLogo))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if len(data) > MaxLength {
|
||||
return validate.NewFieldErrors(validate.FieldError{
|
||||
Field: "data",
|
||||
Error: "max length is 4,296 characters exceeded",
|
||||
})
|
||||
}
|
||||
|
||||
qrc, err := qrcode.New(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
toWriteCloser := struct {
|
||||
io.Writer
|
||||
io.Closer
|
||||
}{
|
||||
Writer: w,
|
||||
Closer: io.NopCloser(nil),
|
||||
}
|
||||
|
||||
qrwriter := standard.NewWithWriter(toWriteCloser, standard.WithLogoImage(image))
|
||||
|
||||
// Return the QR code as a jpeg image
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=qrcode.jpg")
|
||||
return qrc.Save(qrwriter)
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
)
|
||||
|
||||
// HandleBillOfMaterialsExport godoc
|
||||
//
|
||||
// @Summary Generates a Bill of Materials CSV
|
||||
// @Tags Reporting
|
||||
// @Produce json
|
||||
// @Success 200 {string} string "text/csv"
|
||||
// @Router /v1/reporting/bill-of-materials [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleBillOfMaterialsExport() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
actor := services.UseUserCtx(r.Context())
|
||||
|
||||
csv, err := ctrl.svc.Reporting.BillOfMaterialsTSV(r.Context(), actor.GroupID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/csv")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=bom.csv")
|
||||
_, err = w.Write(csv)
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
)
|
||||
|
||||
// HandleGroupGet godoc
|
||||
// @Summary Get the current user's group statistics
|
||||
// @Tags Statistics
|
||||
// @Produce json
|
||||
// @Success 200 {object} []repo.TotalsByOrganizer
|
||||
// @Router /v1/groups/statistics/locations [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupStatisticsLocations() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
stats, err := ctrl.repo.Groups.StatsLocationsByPurchasePrice(ctx, ctx.GID)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, stats)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGroupGet godoc
|
||||
// @Summary Get the current user's group statistics
|
||||
// @Tags Statistics
|
||||
// @Produce json
|
||||
// @Success 200 {object} []repo.TotalsByOrganizer
|
||||
// @Router /v1/groups/statistics/labels [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupStatisticsLabels() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
stats, err := ctrl.repo.Groups.StatsLabelsByPurchasePrice(ctx, ctx.GID)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, stats)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGroupGet godoc
|
||||
// @Summary Get the current user's group statistics
|
||||
// @Tags Statistics
|
||||
// @Produce json
|
||||
// @Success 200 {object} repo.GroupStatistics
|
||||
// @Router /v1/groups/statistics [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupStatistics() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
stats, err := ctrl.repo.Groups.StatsGroup(ctx, ctx.GID)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, stats)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGroupGet godoc
|
||||
// @Summary Queries the changes overtime of the purchase price over time
|
||||
// @Tags Statistics
|
||||
// @Produce json
|
||||
// @Success 200 {object} repo.ValueOverTime
|
||||
// @Param start query string false "start date"
|
||||
// @Param end query string false "end date"
|
||||
// @Router /v1/groups/statistics/purchase-price [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupStatisticsPriceOverTime() server.HandlerFunc {
|
||||
parseDate := func(datestr string, defaultDate time.Time) (time.Time, error) {
|
||||
if datestr == "" {
|
||||
return defaultDate, nil
|
||||
}
|
||||
return time.Parse("2006-01-02", datestr)
|
||||
}
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
startDate, err := parseDate(r.URL.Query().Get("start"), time.Now().AddDate(0, -1, 0))
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
endDate, err := parseDate(r.URL.Query().Get("end"), time.Now())
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
stats, err := ctrl.repo.Groups.StatsPurchasePrice(ctx, ctx.GID, startDate, endDate)
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, stats)
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleUserSelf godoc
|
||||
// @Summary Get the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Param payload body services.UserRegistration true "User Data"
|
||||
// @Success 204
|
||||
// @Router /v1/users/register [Post]
|
||||
func (ctrl *V1Controller) HandleUserRegistration() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
regData := services.UserRegistration{}
|
||||
|
||||
if err := server.Decode(r, ®Data); err != nil {
|
||||
log.Err(err).Msg("failed to decode user registration data")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
if !ctrl.allowRegistration && regData.GroupToken == "" {
|
||||
return validate.NewRequestError(fmt.Errorf("user registration disabled"), http.StatusForbidden)
|
||||
}
|
||||
|
||||
_, err := ctrl.svc.User.RegisterUser(r.Context(), regData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to register user")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelf godoc
|
||||
// @Summary Get the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Result{item=repo.UserOut}
|
||||
// @Router /v1/users/self [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelf() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
token := services.UseTokenCtx(r.Context())
|
||||
usr, err := ctrl.svc.User.GetSelf(r.Context(), token)
|
||||
if usr.ID == uuid.Nil || err != nil {
|
||||
log.Err(err).Msg("failed to get user")
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, server.Wrap(usr))
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelfUpdate godoc
|
||||
// @Summary Update the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Param payload body repo.UserUpdate true "User Data"
|
||||
// @Success 200 {object} server.Result{item=repo.UserUpdate}
|
||||
// @Router /v1/users/self [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfUpdate() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
updateData := repo.UserUpdate{}
|
||||
if err := server.Decode(r, &updateData); err != nil {
|
||||
log.Err(err).Msg("failed to decode user update data")
|
||||
return validate.NewRequestError(err, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
actor := services.UseUserCtx(r.Context())
|
||||
newData, err := ctrl.svc.User.UpdateSelf(r.Context(), actor.ID, updateData)
|
||||
|
||||
if err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusOK, server.Wrap(newData))
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelfDelete godoc
|
||||
// @Summary Deletes the user account
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Router /v1/users/self [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfDelete() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
if ctrl.isDemo {
|
||||
return validate.NewRequestError(nil, http.StatusForbidden)
|
||||
}
|
||||
|
||||
actor := services.UseUserCtx(r.Context())
|
||||
if err := ctrl.svc.User.DeleteSelf(r.Context(), actor.ID); err != nil {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
type (
|
||||
ChangePassword struct {
|
||||
Current string `json:"current,omitempty"`
|
||||
New string `json:"new,omitempty"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleUserSelfChangePassword godoc
|
||||
// @Summary Updates the users password
|
||||
// @Tags User
|
||||
// @Success 204
|
||||
// @Param payload body ChangePassword true "Password Payload"
|
||||
// @Router /v1/users/change-password [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfChangePassword() server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
if ctrl.isDemo {
|
||||
return validate.NewRequestError(nil, http.StatusForbidden)
|
||||
}
|
||||
|
||||
var cp ChangePassword
|
||||
err := server.Decode(r, &cp)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("user failed to change password")
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
ok := ctrl.svc.User.ChangePassword(ctx, cp.Current, cp.New)
|
||||
if !ok {
|
||||
return validate.NewRequestError(err, http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/config"
|
||||
"github.com/hay-kot/homebox/backend/internal/config"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -15,7 +15,7 @@ func (a *app) setupLogger() {
|
||||
// Logger Init
|
||||
// zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
if a.conf.Log.Format != config.LogFormatJSON {
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).With().Caller().Logger()
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
}
|
||||
|
||||
log.Level(getLevel(a.conf.Log.Level))
|
||||
|
||||
@@ -2,41 +2,39 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
atlas "ariga.io/atlas/sql/migrate"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"github.com/hay-kot/homebox/backend/app/api/static/docs"
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/migrations"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/config"
|
||||
"github.com/hay-kot/homebox/backend/internal/web/mid"
|
||||
"github.com/hay-kot/homebox/backend/app/api/docs"
|
||||
"github.com/hay-kot/homebox/backend/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/config"
|
||||
"github.com/hay-kot/homebox/backend/internal/migrations"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "nightly"
|
||||
commit = "HEAD"
|
||||
buildTime = "now"
|
||||
Version = "0.1.0"
|
||||
Commit = "HEAD"
|
||||
BuildTime = "now"
|
||||
)
|
||||
|
||||
// @title Go API Templates
|
||||
// @version 1.0
|
||||
// @description This is a simple Rest API Server Template that implements some basic User and Authentication patterns to help you get started and bootstrap your next project!.
|
||||
// @contact.name Don't
|
||||
// @license.name MIT
|
||||
// @BasePath /api
|
||||
// @securityDefinitions.apikey Bearer
|
||||
// @in header
|
||||
// @name Authorization
|
||||
// @description "Type 'Bearer TOKEN' to correctly set the API Key"
|
||||
// @title Go API Templates
|
||||
// @version 1.0
|
||||
// @description This is a simple Rest API Server Template that implements some basic User and Authentication patterns to help you get started and bootstrap your next project!.
|
||||
// @contact.name Don't
|
||||
// @license.name MIT
|
||||
// @BasePath /api
|
||||
// @securityDefinitions.apikey Bearer
|
||||
// @in header
|
||||
// @name Authorization
|
||||
// @description "Type 'Bearer TOKEN' to correctly set the API Key"
|
||||
func main() {
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
@@ -112,31 +110,20 @@ func run(cfg *config.Config) error {
|
||||
|
||||
app.db = c
|
||||
app.repos = repo.New(c, cfg.Storage.Data)
|
||||
app.services = services.New(
|
||||
app.repos,
|
||||
services.WithAutoIncrementAssetID(cfg.Options.AutoIncrementAssetID),
|
||||
)
|
||||
app.services = services.NewServices(app.repos)
|
||||
|
||||
// =========================================================================
|
||||
// Start Server\
|
||||
logger := log.With().Caller().Logger()
|
||||
|
||||
mwLogger := mid.Logger(logger)
|
||||
if app.conf.Mode == config.ModeDevelopment {
|
||||
mwLogger = mid.SugarLogger(logger)
|
||||
}
|
||||
|
||||
// Start Server
|
||||
app.server = server.NewServer(
|
||||
server.WithHost(app.conf.Web.Host),
|
||||
server.WithPort(app.conf.Web.Port),
|
||||
server.WithMiddleware(
|
||||
mwLogger,
|
||||
mid.Errors(logger),
|
||||
mid.Panic(app.conf.Mode == config.ModeDevelopment),
|
||||
),
|
||||
)
|
||||
|
||||
app.mountRoutes(app.repos)
|
||||
routes := app.newRouter(app.repos)
|
||||
|
||||
if app.conf.Mode != config.ModeDevelopment {
|
||||
app.logRoutes(routes)
|
||||
}
|
||||
|
||||
log.Info().Msgf("Starting HTTP Server on %s:%s", app.server.Host, app.server.Port)
|
||||
|
||||
@@ -151,14 +138,6 @@ func run(cfg *config.Config) error {
|
||||
Msg("failed to purge expired tokens")
|
||||
}
|
||||
})
|
||||
go app.startBgTask(time.Duration(24)*time.Hour, func() {
|
||||
_, err := app.repos.Groups.InvitationPurge(context.Background())
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Msg("failed to purge expired invitations")
|
||||
}
|
||||
})
|
||||
|
||||
// TODO: Remove through external API that does setup
|
||||
if cfg.Demo {
|
||||
@@ -166,14 +145,5 @@ func run(cfg *config.Config) error {
|
||||
app.SetupDemo()
|
||||
}
|
||||
|
||||
if cfg.Debug.Enabled {
|
||||
debugrouter := app.debugRouter()
|
||||
go func() {
|
||||
if err := http.ListenAndServe(":"+cfg.Debug.Port, debugrouter); err != nil {
|
||||
log.Fatal().Err(err).Msg("failed to start debug server")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return app.server.Start()
|
||||
return app.server.Start(routes)
|
||||
}
|
||||
|
||||
@@ -1,105 +1,160 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/hay-kot/homebox/backend/internal/config"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type tokenHasKey struct {
|
||||
key string
|
||||
}
|
||||
func (a *app) setGlobalMiddleware(r *chi.Mux) {
|
||||
// =========================================================================
|
||||
// Middleware
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(mwStripTrailingSlash)
|
||||
|
||||
var (
|
||||
hashedToken = tokenHasKey{key: "hashedToken"}
|
||||
)
|
||||
|
||||
type RoleMode int
|
||||
|
||||
const (
|
||||
RoleModeOr RoleMode = 0
|
||||
RoleModeAnd RoleMode = 1
|
||||
)
|
||||
|
||||
// mwRoles is a middleware that will validate the required roles are met. All roles
|
||||
// are required to be met for the request to be allowed. If the user does not have
|
||||
// the required roles, a 403 Forbidden will be returned.
|
||||
//
|
||||
// WARNING: This middleware _MUST_ be called after mwAuthToken or else it will panic
|
||||
func (a *app) mwRoles(rm RoleMode, required ...string) server.Middleware {
|
||||
return func(next server.Handler) server.Handler {
|
||||
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx := r.Context()
|
||||
|
||||
maybeToken := ctx.Value(hashedToken)
|
||||
if maybeToken == nil {
|
||||
panic("mwRoles: token not found in context, you must call mwAuthToken before mwRoles")
|
||||
}
|
||||
|
||||
token := maybeToken.(string)
|
||||
|
||||
roles, err := a.repos.AuthTokens.GetRoles(r.Context(), token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
outer:
|
||||
switch rm {
|
||||
case RoleModeOr:
|
||||
for _, role := range required {
|
||||
if roles.Contains(role) {
|
||||
break outer
|
||||
}
|
||||
}
|
||||
return validate.NewRequestError(errors.New("Forbidden"), http.StatusForbidden)
|
||||
case RoleModeAnd:
|
||||
for _, req := range required {
|
||||
if !roles.Contains(req) {
|
||||
return validate.NewRequestError(errors.New("Unauthorized"), http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return next.ServeHTTP(w, r)
|
||||
})
|
||||
// Use struct logger in production for requests, but use
|
||||
// pretty console logger in development.
|
||||
if a.conf.Mode == config.ModeDevelopment {
|
||||
r.Use(a.mwSummaryLogger)
|
||||
} else {
|
||||
r.Use(a.mwStructLogger)
|
||||
}
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
// Set a timeout value on the request context (ctx), that will signal
|
||||
// through ctx.Done() that the request has timed out and further
|
||||
// processing should be stopped.
|
||||
r.Use(middleware.Timeout(60 * time.Second))
|
||||
}
|
||||
|
||||
// mwAuthToken is a middleware that will check the database for a stateful token
|
||||
// and attach it's user to the request context, or return an appropriate error.
|
||||
// Authorization support is by token via Headers or Query Parameter
|
||||
//
|
||||
// Example:
|
||||
// - header = "Bearer 1234567890"
|
||||
// - query = "?access_token=1234567890"
|
||||
func (a *app) mwAuthToken(next server.Handler) server.Handler {
|
||||
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||
// and attach it to the request context with the user, or return a 401 if it doesn't exist.
|
||||
func (a *app) mwAuthToken(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestToken := r.Header.Get("Authorization")
|
||||
|
||||
if requestToken == "" {
|
||||
// check for query param
|
||||
requestToken = r.URL.Query().Get("access_token")
|
||||
if requestToken == "" {
|
||||
return validate.NewRequestError(errors.New("Authorization header or query is required"), http.StatusUnauthorized)
|
||||
}
|
||||
server.RespondUnauthorized(w)
|
||||
return
|
||||
}
|
||||
|
||||
requestToken = strings.TrimPrefix(requestToken, "Bearer ")
|
||||
|
||||
r = r.WithContext(context.WithValue(r.Context(), hashedToken, requestToken))
|
||||
|
||||
usr, err := a.services.User.GetSelf(r.Context(), requestToken)
|
||||
|
||||
// Check the database for the token
|
||||
|
||||
if err != nil {
|
||||
return validate.NewRequestError(errors.New("Authorization header is required"), http.StatusUnauthorized)
|
||||
server.RespondUnauthorized(w)
|
||||
return
|
||||
}
|
||||
|
||||
r = r.WithContext(services.SetUserCtx(r.Context(), &usr, requestToken))
|
||||
return next.ServeHTTP(w, r)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// mwAdminOnly is a middleware that extends the mwAuthToken middleware to only allow
|
||||
// requests from superusers.
|
||||
// func (a *app) mwAdminOnly(next http.Handler) http.Handler {
|
||||
// mw := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// usr := services.UseUserCtx(r.Context())
|
||||
|
||||
// if !usr.IsSuperuser {
|
||||
// server.RespondUnauthorized(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// next.ServeHTTP(w, r)
|
||||
// })
|
||||
// return a.mwAuthToken(mw)
|
||||
// }
|
||||
|
||||
// mqStripTrailingSlash is a middleware that will strip trailing slashes from the request path.
|
||||
func mwStripTrailingSlash(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type StatusRecorder struct {
|
||||
http.ResponseWriter
|
||||
Status int
|
||||
}
|
||||
|
||||
func (r *StatusRecorder) WriteHeader(status int) {
|
||||
r.Status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (a *app) mwStructLogger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
record := &StatusRecorder{ResponseWriter: w, Status: http.StatusOK}
|
||||
next.ServeHTTP(record, r)
|
||||
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s://%s%s %s", scheme, r.Host, r.RequestURI, r.Proto)
|
||||
|
||||
log.Info().
|
||||
Str("id", middleware.GetReqID(r.Context())).
|
||||
Str("url", url).
|
||||
Str("method", r.Method).
|
||||
Str("remote_addr", r.RemoteAddr).
|
||||
Int("status", record.Status).
|
||||
Msg(url)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *app) mwSummaryLogger(next http.Handler) http.Handler {
|
||||
bold := func(s string) string { return "\033[1m" + s + "\033[0m" }
|
||||
orange := func(s string) string { return "\033[33m" + s + "\033[0m" }
|
||||
aqua := func(s string) string { return "\033[36m" + s + "\033[0m" }
|
||||
red := func(s string) string { return "\033[31m" + s + "\033[0m" }
|
||||
green := func(s string) string { return "\033[32m" + s + "\033[0m" }
|
||||
|
||||
fmtCode := func(code int) string {
|
||||
switch {
|
||||
case code >= 500:
|
||||
return red(fmt.Sprintf("%d", code))
|
||||
case code >= 400:
|
||||
return orange(fmt.Sprintf("%d", code))
|
||||
case code >= 300:
|
||||
return aqua(fmt.Sprintf("%d", code))
|
||||
default:
|
||||
return green(fmt.Sprintf("%d", code))
|
||||
}
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
record := &StatusRecorder{ResponseWriter: w, Status: http.StatusOK}
|
||||
next.ServeHTTP(record, r) // Blocks until the next handler returns.
|
||||
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s://%s%s %s", scheme, r.Host, r.RequestURI, r.Proto)
|
||||
|
||||
log.Info().
|
||||
Msgf("%s %s %s",
|
||||
bold(orange(""+r.Method+"")),
|
||||
aqua(url),
|
||||
bold(fmtCode(record.Status)),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,12 +10,11 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/app/api/handlers/debughandlers"
|
||||
v1 "github.com/hay-kot/homebox/backend/app/api/handlers/v1"
|
||||
_ "github.com/hay-kot/homebox/backend/app/api/static/docs"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authroles"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/go-chi/chi/v5"
|
||||
_ "github.com/hay-kot/homebox/backend/app/api/docs"
|
||||
v1 "github.com/hay-kot/homebox/backend/app/api/v1"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/rs/zerolog/log"
|
||||
httpSwagger "github.com/swaggo/http-swagger" // http-swagger middleware
|
||||
)
|
||||
|
||||
@@ -24,122 +23,102 @@ const prefix = "/api"
|
||||
var (
|
||||
ErrDir = errors.New("path is dir")
|
||||
|
||||
//go:embed all:static/public/*
|
||||
//go:embed all:public/*
|
||||
public embed.FS
|
||||
)
|
||||
|
||||
func (a *app) debugRouter() *http.ServeMux {
|
||||
dbg := http.NewServeMux()
|
||||
debughandlers.New(dbg)
|
||||
|
||||
return dbg
|
||||
}
|
||||
|
||||
// registerRoutes registers all the routes for the API
|
||||
func (a *app) mountRoutes(repos *repo.AllRepos) {
|
||||
func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
|
||||
registerMimes()
|
||||
|
||||
a.server.Get("/swagger/*", server.ToHandler(httpSwagger.Handler(
|
||||
r := chi.NewRouter()
|
||||
a.setGlobalMiddleware(r)
|
||||
|
||||
r.Get("/swagger/*", httpSwagger.Handler(
|
||||
httpSwagger.URL(fmt.Sprintf("%s://%s/swagger/doc.json", a.conf.Swagger.Scheme, a.conf.Swagger.Host)),
|
||||
)))
|
||||
))
|
||||
|
||||
// =========================================================================
|
||||
// API Version 1
|
||||
|
||||
v1Base := v1.BaseUrlFunc(prefix)
|
||||
|
||||
v1Ctrl := v1.NewControllerV1(
|
||||
a.services,
|
||||
a.repos,
|
||||
v1Ctrl := v1.NewControllerV1(a.services,
|
||||
v1.WithMaxUploadSize(a.conf.Web.MaxUploadSize),
|
||||
v1.WithRegistration(a.conf.Options.AllowRegistration),
|
||||
v1.WithDemoStatus(a.conf.Demo), // Disable Password Change in Demo Mode
|
||||
)
|
||||
|
||||
a.server.Get(v1Base("/status"), v1Ctrl.HandleBase(func() bool { return true }, v1.Build{
|
||||
Version: version,
|
||||
Commit: commit,
|
||||
BuildTime: buildTime,
|
||||
r.Get(v1Base("/status"), v1Ctrl.HandleBase(func() bool { return true }, v1.Build{
|
||||
Version: Version,
|
||||
Commit: Commit,
|
||||
BuildTime: BuildTime,
|
||||
}))
|
||||
|
||||
a.server.Post(v1Base("/users/register"), v1Ctrl.HandleUserRegistration())
|
||||
a.server.Post(v1Base("/users/login"), v1Ctrl.HandleAuthLogin())
|
||||
r.Post(v1Base("/users/register"), v1Ctrl.HandleUserRegistration())
|
||||
r.Post(v1Base("/users/login"), v1Ctrl.HandleAuthLogin())
|
||||
|
||||
userMW := []server.Middleware{
|
||||
a.mwAuthToken,
|
||||
a.mwRoles(RoleModeOr, authroles.RoleUser.String()),
|
||||
// Attachment download URl needs a `token` query param to be passed in the request.
|
||||
// and also needs to be outside of the `auth` middleware.
|
||||
r.Get(v1Base("/items/{id}/attachments/download"), v1Ctrl.HandleItemAttachmentDownload())
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(a.mwAuthToken)
|
||||
r.Get(v1Base("/users/self"), v1Ctrl.HandleUserSelf())
|
||||
r.Put(v1Base("/users/self"), v1Ctrl.HandleUserSelfUpdate())
|
||||
r.Delete(v1Base("/users/self"), v1Ctrl.HandleUserSelfDelete())
|
||||
r.Put(v1Base("/users/self/password"), v1Ctrl.HandleUserUpdatePassword())
|
||||
r.Post(v1Base("/users/logout"), v1Ctrl.HandleAuthLogout())
|
||||
r.Get(v1Base("/users/refresh"), v1Ctrl.HandleAuthRefresh())
|
||||
r.Put(v1Base("/users/self/change-password"), v1Ctrl.HandleUserSelfChangePassword())
|
||||
|
||||
r.Post(v1Base("/groups/invitations"), v1Ctrl.HandleGroupInvitationsCreate())
|
||||
|
||||
r.Get(v1Base("/locations"), v1Ctrl.HandleLocationGetAll())
|
||||
r.Post(v1Base("/locations"), v1Ctrl.HandleLocationCreate())
|
||||
r.Get(v1Base("/locations/{id}"), v1Ctrl.HandleLocationGet())
|
||||
r.Put(v1Base("/locations/{id}"), v1Ctrl.HandleLocationUpdate())
|
||||
r.Delete(v1Base("/locations/{id}"), v1Ctrl.HandleLocationDelete())
|
||||
|
||||
r.Get(v1Base("/labels"), v1Ctrl.HandleLabelsGetAll())
|
||||
r.Post(v1Base("/labels"), v1Ctrl.HandleLabelsCreate())
|
||||
r.Get(v1Base("/labels/{id}"), v1Ctrl.HandleLabelGet())
|
||||
r.Put(v1Base("/labels/{id}"), v1Ctrl.HandleLabelUpdate())
|
||||
r.Delete(v1Base("/labels/{id}"), v1Ctrl.HandleLabelDelete())
|
||||
|
||||
r.Get(v1Base("/items"), v1Ctrl.HandleItemsGetAll())
|
||||
r.Post(v1Base("/items/import"), v1Ctrl.HandleItemsImport())
|
||||
r.Post(v1Base("/items"), v1Ctrl.HandleItemsCreate())
|
||||
r.Get(v1Base("/items/{id}"), v1Ctrl.HandleItemGet())
|
||||
r.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate())
|
||||
r.Delete(v1Base("/items/{id}"), v1Ctrl.HandleItemDelete())
|
||||
|
||||
r.Post(v1Base("/items/{id}/attachments"), v1Ctrl.HandleItemAttachmentCreate())
|
||||
r.Get(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentToken())
|
||||
r.Put(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentUpdate())
|
||||
r.Delete(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentDelete())
|
||||
})
|
||||
|
||||
r.NotFound(notFoundHandler())
|
||||
return r
|
||||
}
|
||||
|
||||
// logRoutes logs the routes of the server that are registered within Server.registerRoutes(). This is useful for debugging.
|
||||
// See https://github.com/go-chi/chi/issues/332 for details and inspiration.
|
||||
func (a *app) logRoutes(r *chi.Mux) {
|
||||
desiredSpaces := 10
|
||||
|
||||
walkFunc := func(method string, route string, handler http.Handler, middleware ...func(http.Handler) http.Handler) error {
|
||||
text := "[" + method + "]"
|
||||
|
||||
for len(text) < desiredSpaces {
|
||||
text = text + " "
|
||||
}
|
||||
|
||||
fmt.Printf("Registered Route: %s%s\n", text, route)
|
||||
return nil
|
||||
}
|
||||
|
||||
a.server.Get(v1Base("/users/self"), v1Ctrl.HandleUserSelf(), userMW...)
|
||||
a.server.Put(v1Base("/users/self"), v1Ctrl.HandleUserSelfUpdate(), userMW...)
|
||||
a.server.Delete(v1Base("/users/self"), v1Ctrl.HandleUserSelfDelete(), userMW...)
|
||||
a.server.Post(v1Base("/users/logout"), v1Ctrl.HandleAuthLogout(), userMW...)
|
||||
a.server.Get(v1Base("/users/refresh"), v1Ctrl.HandleAuthRefresh(), userMW...)
|
||||
a.server.Put(v1Base("/users/self/change-password"), v1Ctrl.HandleUserSelfChangePassword(), userMW...)
|
||||
|
||||
a.server.Post(v1Base("/groups/invitations"), v1Ctrl.HandleGroupInvitationsCreate(), userMW...)
|
||||
a.server.Get(v1Base("/groups/statistics"), v1Ctrl.HandleGroupStatistics(), userMW...)
|
||||
a.server.Get(v1Base("/groups/statistics/purchase-price"), v1Ctrl.HandleGroupStatisticsPriceOverTime(), userMW...)
|
||||
a.server.Get(v1Base("/groups/statistics/locations"), v1Ctrl.HandleGroupStatisticsLocations(), userMW...)
|
||||
a.server.Get(v1Base("/groups/statistics/labels"), v1Ctrl.HandleGroupStatisticsLabels(), userMW...)
|
||||
|
||||
// TODO: I don't like /groups being the URL for users
|
||||
a.server.Get(v1Base("/groups"), v1Ctrl.HandleGroupGet(), userMW...)
|
||||
a.server.Put(v1Base("/groups"), v1Ctrl.HandleGroupUpdate(), userMW...)
|
||||
|
||||
a.server.Post(v1Base("/actions/ensure-asset-ids"), v1Ctrl.HandleEnsureAssetID(), userMW...)
|
||||
a.server.Post(v1Base("/actions/zero-item-time-fields"), v1Ctrl.HandleItemDateZeroOut(), userMW...)
|
||||
|
||||
a.server.Get(v1Base("/locations"), v1Ctrl.HandleLocationGetAll(), userMW...)
|
||||
a.server.Post(v1Base("/locations"), v1Ctrl.HandleLocationCreate(), userMW...)
|
||||
a.server.Get(v1Base("/locations/tree"), v1Ctrl.HandleLocationTreeQuery(), userMW...)
|
||||
a.server.Get(v1Base("/locations/{id}"), v1Ctrl.HandleLocationGet(), userMW...)
|
||||
a.server.Put(v1Base("/locations/{id}"), v1Ctrl.HandleLocationUpdate(), userMW...)
|
||||
a.server.Delete(v1Base("/locations/{id}"), v1Ctrl.HandleLocationDelete(), userMW...)
|
||||
|
||||
a.server.Get(v1Base("/labels"), v1Ctrl.HandleLabelsGetAll(), userMW...)
|
||||
a.server.Post(v1Base("/labels"), v1Ctrl.HandleLabelsCreate(), userMW...)
|
||||
a.server.Get(v1Base("/labels/{id}"), v1Ctrl.HandleLabelGet(), userMW...)
|
||||
a.server.Put(v1Base("/labels/{id}"), v1Ctrl.HandleLabelUpdate(), userMW...)
|
||||
a.server.Delete(v1Base("/labels/{id}"), v1Ctrl.HandleLabelDelete(), userMW...)
|
||||
|
||||
a.server.Get(v1Base("/items"), v1Ctrl.HandleItemsGetAll(), userMW...)
|
||||
a.server.Post(v1Base("/items"), v1Ctrl.HandleItemsCreate(), userMW...)
|
||||
a.server.Post(v1Base("/items/import"), v1Ctrl.HandleItemsImport(), userMW...)
|
||||
a.server.Get(v1Base("/items/fields"), v1Ctrl.HandleGetAllCustomFieldNames(), userMW...)
|
||||
a.server.Get(v1Base("/items/fields/values"), v1Ctrl.HandleGetAllCustomFieldValues(), userMW...)
|
||||
|
||||
a.server.Get(v1Base("/items/{id}"), v1Ctrl.HandleItemGet(), userMW...)
|
||||
a.server.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate(), userMW...)
|
||||
a.server.Delete(v1Base("/items/{id}"), v1Ctrl.HandleItemDelete(), userMW...)
|
||||
|
||||
a.server.Post(v1Base("/items/{id}/attachments"), v1Ctrl.HandleItemAttachmentCreate(), userMW...)
|
||||
a.server.Put(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentUpdate(), userMW...)
|
||||
a.server.Delete(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentDelete(), userMW...)
|
||||
|
||||
a.server.Get(v1Base("/items/{id}/maintenance"), v1Ctrl.HandleMaintenanceEntryCreate(), userMW...)
|
||||
a.server.Post(v1Base("/items/{id}/maintenance"), v1Ctrl.HandleMaintenanceEntryCreate(), userMW...)
|
||||
a.server.Put(v1Base("/items/{id}/maintenance/{entry_id}"), v1Ctrl.HandleMaintenanceEntryUpdate(), userMW...)
|
||||
a.server.Delete(v1Base("/items/{id}/maintenance/{entry_id}"), v1Ctrl.HandleMaintenanceEntryDelete(), userMW...)
|
||||
|
||||
a.server.Get(v1Base("/asset/{id}"), v1Ctrl.HandleAssetGet(), userMW...)
|
||||
|
||||
// Asset-Like endpoints
|
||||
a.server.Get(
|
||||
v1Base("/qrcode"),
|
||||
v1Ctrl.HandleGenerateQRCode(),
|
||||
a.mwAuthToken, a.mwRoles(RoleModeOr, authroles.RoleUser.String(), authroles.RoleAttachments.String()),
|
||||
)
|
||||
a.server.Get(
|
||||
v1Base("/items/{id}/attachments/{attachment_id}"),
|
||||
v1Ctrl.HandleItemAttachmentGet(),
|
||||
a.mwAuthToken, a.mwRoles(RoleModeOr, authroles.RoleUser.String(), authroles.RoleAttachments.String()),
|
||||
)
|
||||
|
||||
// Reporting Services
|
||||
a.server.Get(v1Base("/reporting/bill-of-materials"), v1Ctrl.HandleBillOfMaterialsExport(), userMW...)
|
||||
|
||||
a.server.NotFound(notFoundHandler())
|
||||
if err := chi.Walk(r, walkFunc); err != nil {
|
||||
fmt.Printf("Logging err: %s\n", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func registerMimes() {
|
||||
@@ -156,7 +135,7 @@ func registerMimes() {
|
||||
|
||||
// notFoundHandler perform the main logic around handling the internal SPA embed and ensuring that
|
||||
// the client side routing is handled correctly.
|
||||
func notFoundHandler() server.HandlerFunc {
|
||||
func notFoundHandler() http.HandlerFunc {
|
||||
tryRead := func(fs embed.FS, prefix, requestedPath string, w http.ResponseWriter) error {
|
||||
f, err := fs.Open(path.Join(prefix, requestedPath))
|
||||
if err != nil {
|
||||
@@ -175,16 +154,17 @@ func notFoundHandler() server.HandlerFunc {
|
||||
return err
|
||||
}
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
err := tryRead(public, "static/public", r.URL.Path, w)
|
||||
if err != nil {
|
||||
// Fallback to the index.html file.
|
||||
// should succeed in all cases.
|
||||
err = tryRead(public, "static/public", "index.html", w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
err := tryRead(public, "public", r.URL.Path, w)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
log.Debug().
|
||||
Str("path", r.URL.Path).
|
||||
Msg("served from embed not found - serving index.html")
|
||||
err = tryRead(public, "public", "index.html", w)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,7 @@ package v1
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/core/services"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
)
|
||||
|
||||
@@ -20,23 +19,13 @@ func WithDemoStatus(demoStatus bool) func(*V1Controller) {
|
||||
}
|
||||
}
|
||||
|
||||
func WithRegistration(allowRegistration bool) func(*V1Controller) {
|
||||
return func(ctrl *V1Controller) {
|
||||
ctrl.allowRegistration = allowRegistration
|
||||
}
|
||||
}
|
||||
|
||||
type V1Controller struct {
|
||||
repo *repo.AllRepos
|
||||
svc *services.AllServices
|
||||
maxUploadSize int64
|
||||
isDemo bool
|
||||
allowRegistration bool
|
||||
svc *services.AllServices
|
||||
maxUploadSize int64
|
||||
isDemo bool
|
||||
}
|
||||
|
||||
type (
|
||||
ReadyFunc func() bool
|
||||
|
||||
Build struct {
|
||||
Version string `json:"version"`
|
||||
Commit string `json:"commit"`
|
||||
@@ -54,16 +43,17 @@ type (
|
||||
)
|
||||
|
||||
func BaseUrlFunc(prefix string) func(s string) string {
|
||||
return func(s string) string {
|
||||
return prefix + "/v1" + s
|
||||
v1Base := prefix + "/v1"
|
||||
prefixFunc := func(s string) string {
|
||||
return v1Base + s
|
||||
}
|
||||
|
||||
return prefixFunc
|
||||
}
|
||||
|
||||
func NewControllerV1(svc *services.AllServices, repos *repo.AllRepos, options ...func(*V1Controller)) *V1Controller {
|
||||
func NewControllerV1(svc *services.AllServices, options ...func(*V1Controller)) *V1Controller {
|
||||
ctrl := &V1Controller{
|
||||
repo: repos,
|
||||
svc: svc,
|
||||
allowRegistration: true,
|
||||
svc: svc,
|
||||
}
|
||||
|
||||
for _, opt := range options {
|
||||
@@ -73,15 +63,17 @@ func NewControllerV1(svc *services.AllServices, repos *repo.AllRepos, options ..
|
||||
return ctrl
|
||||
}
|
||||
|
||||
type ReadyFunc func() bool
|
||||
|
||||
// HandleBase godoc
|
||||
// @Summary Retrieves the basic information about the API
|
||||
// @Tags Base
|
||||
// @Produce json
|
||||
// @Success 200 {object} ApiSummary
|
||||
// @Router /v1/status [GET]
|
||||
func (ctrl *V1Controller) HandleBase(ready ReadyFunc, build Build) server.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
return server.Respond(w, http.StatusOK, ApiSummary{
|
||||
// @Summary Retrieves the basic information about the API
|
||||
// @Tags Base
|
||||
// @Produce json
|
||||
// @Success 200 {object} ApiSummary
|
||||
// @Router /v1/status [GET]
|
||||
func (ctrl *V1Controller) HandleBase(ready ReadyFunc, build Build) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
server.Respond(w, http.StatusOK, ApiSummary{
|
||||
Healthy: ready(),
|
||||
Title: "Go API Template",
|
||||
Message: "Welcome to the Go API Template Application!",
|
||||
34
backend/app/api/v1/partials.go
Normal file
34
backend/app/api/v1/partials.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
/*
|
||||
This is where we put partial snippets/functions for actions that are commonly
|
||||
used within the controller class. This _hopefully_ helps with code duplication
|
||||
and makes it a little more consistent when error handling and logging.
|
||||
*/
|
||||
|
||||
// partialParseIdAndUser parses the ID from the requests URL and pulls the user
|
||||
// from the context. If either of these fail, it will return an error. When an error
|
||||
// occurs it will also write the error to the response. As such, if an error is returned
|
||||
// from this function you can return immediately without writing to the response.
|
||||
func (ctrl *V1Controller) partialParseIdAndUser(w http.ResponseWriter, r *http.Request) (uuid.UUID, *repo.UserOut, error) {
|
||||
uid, err := uuid.Parse(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to parse id")
|
||||
server.RespondError(w, http.StatusBadRequest, err)
|
||||
return uuid.Nil, &repo.UserOut{}, err
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
return uid, user, nil
|
||||
}
|
||||
134
backend/app/api/v1/v1_ctrl_auth.go
Normal file
134
backend/app/api/v1/v1_ctrl_auth.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
TokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
LoginForm struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleAuthLogin godoc
|
||||
// @Summary User Login
|
||||
// @Tags Authentication
|
||||
// @Accept x-www-form-urlencoded
|
||||
// @Accept application/json
|
||||
// @Param username formData string false "string" example(admin@admin.com)
|
||||
// @Param password formData string false "string" example(admin)
|
||||
// @Produce json
|
||||
// @Success 200 {object} TokenResponse
|
||||
// @Router /v1/users/login [POST]
|
||||
func (ctrl *V1Controller) HandleAuthLogin() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
loginForm := &LoginForm{}
|
||||
|
||||
switch r.Header.Get("Content-Type") {
|
||||
case server.ContentFormUrlEncoded:
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
server.Respond(w, http.StatusBadRequest, server.Wrap(err))
|
||||
log.Error().Err(err).Msg("failed to parse form")
|
||||
return
|
||||
}
|
||||
|
||||
loginForm.Username = r.PostFormValue("username")
|
||||
loginForm.Password = r.PostFormValue("password")
|
||||
case server.ContentJSON:
|
||||
err := server.Decode(r, loginForm)
|
||||
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to decode login form")
|
||||
server.Respond(w, http.StatusBadRequest, server.Wrap(err))
|
||||
return
|
||||
}
|
||||
default:
|
||||
server.Respond(w, http.StatusBadRequest, errors.New("invalid content type"))
|
||||
return
|
||||
}
|
||||
|
||||
if loginForm.Username == "" || loginForm.Password == "" {
|
||||
server.RespondError(w, http.StatusBadRequest, errors.New("username and password are required"))
|
||||
return
|
||||
}
|
||||
|
||||
newToken, err := ctrl.svc.User.Login(r.Context(), loginForm.Username, loginForm.Password)
|
||||
|
||||
if err != nil {
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, TokenResponse{
|
||||
Token: "Bearer " + newToken.Raw,
|
||||
ExpiresAt: newToken.ExpiresAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAuthLogout godoc
|
||||
// @Summary User Logout
|
||||
// @Tags Authentication
|
||||
// @Success 204
|
||||
// @Router /v1/users/logout [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleAuthLogout() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := services.UseTokenCtx(r.Context())
|
||||
|
||||
if token == "" {
|
||||
server.RespondError(w, http.StatusUnauthorized, errors.New("no token within request context"))
|
||||
return
|
||||
}
|
||||
|
||||
err := ctrl.svc.User.Logout(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleAuthLogout godoc
|
||||
// @Summary User Token Refresh
|
||||
// @Description handleAuthRefresh returns a handler that will issue a new token from an existing token.
|
||||
// @Description This does not validate that the user still exists within the database.
|
||||
// @Tags Authentication
|
||||
// @Success 200
|
||||
// @Router /v1/users/refresh [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleAuthRefresh() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestToken := services.UseTokenCtx(r.Context())
|
||||
|
||||
if requestToken == "" {
|
||||
server.RespondError(w, http.StatusUnauthorized, errors.New("no user token found"))
|
||||
return
|
||||
}
|
||||
|
||||
newToken, err := ctrl.svc.User.RenewToken(r.Context(), requestToken)
|
||||
|
||||
if err != nil {
|
||||
server.RespondUnauthorized(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, newToken)
|
||||
}
|
||||
}
|
||||
62
backend/app/api/v1/v1_ctrl_group.go
Normal file
62
backend/app/api/v1/v1_ctrl_group.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
GroupInvitationCreate struct {
|
||||
Uses int `json:"uses"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
GroupInvitation struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Uses int `json:"uses"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleUserSelf godoc
|
||||
// @Summary Get the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Param payload body GroupInvitationCreate true "User Data"
|
||||
// @Success 200 {object} GroupInvitation
|
||||
// @Router /v1/groups/invitations [Post]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleGroupInvitationsCreate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
data := GroupInvitationCreate{}
|
||||
|
||||
if err := server.Decode(r, &data); err != nil {
|
||||
log.Err(err).Msg("failed to decode user registration data")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
if data.ExpiresAt.IsZero() {
|
||||
data.ExpiresAt = time.Now().Add(time.Hour * 24)
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
token, err := ctrl.svc.User.NewInvitation(ctx, data.Uses, data.ExpiresAt)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create new token")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusCreated, GroupInvitation{
|
||||
Token: token,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
Uses: data.Uses,
|
||||
})
|
||||
}
|
||||
}
|
||||
189
backend/app/api/v1/v1_ctrl_items.go
Normal file
189
backend/app/api/v1/v1_ctrl_items.go
Normal file
@@ -0,0 +1,189 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleItemsGetAll godoc
|
||||
// @Summary Get All Items
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Results{items=[]repo.ItemSummary}
|
||||
// @Router /v1/items [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemsGetAll() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := services.UseUserCtx(r.Context())
|
||||
items, err := ctrl.svc.Items.GetAll(r.Context(), user.GroupID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get items")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, server.Results{Items: items})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemsCreate godoc
|
||||
// @Summary Create a new item
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param payload body repo.ItemCreate true "Item Data"
|
||||
// @Success 200 {object} repo.ItemSummary
|
||||
// @Router /v1/items [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemsCreate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
createData := repo.ItemCreate{}
|
||||
if err := server.Decode(r, &createData); err != nil {
|
||||
log.Err(err).Msg("failed to decode request body")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
item, err := ctrl.svc.Items.Create(r.Context(), user.GroupID, createData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create item")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusCreated, item)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemDelete godocs
|
||||
// @Summary deletes a item
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Success 204
|
||||
// @Router /v1/items/{id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemDelete() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = ctrl.svc.Items.Delete(r.Context(), user.GroupID, uid)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete item")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemGet godocs
|
||||
// @Summary Gets a item and fields
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Router /v1/items/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemGet() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
items, err := ctrl.svc.Items.GetOne(r.Context(), user.GroupID, uid)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get item")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, items)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemUpdate godocs
|
||||
// @Summary updates a item
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param payload body repo.ItemUpdate true "Item Data"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Router /v1/items/{id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemUpdate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
body := repo.ItemUpdate{}
|
||||
if err := server.Decode(r, &body); err != nil {
|
||||
log.Err(err).Msg("failed to decode request body")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
body.ID = uid
|
||||
result, err := ctrl.svc.Items.Update(r.Context(), user.GroupID, body)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to update item")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemsImport godocs
|
||||
// @Summary imports items into the database
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Param csv formData file true "Image to upload"
|
||||
// @Router /v1/items/import [Post]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemsImport() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to parse multipart form")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("csv")
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get file from form")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
reader := csv.NewReader(file)
|
||||
data, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to read csv")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
|
||||
err = ctrl.svc.Items.CsvImport(r.Context(), user.GroupID, data)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to import items")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
242
backend/app/api/v1/v1_ctrl_items_attachments.go
Normal file
242
backend/app/api/v1/v1_ctrl_items_attachments.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
ItemAttachmentToken struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleItemsImport godocs
|
||||
// @Summary imports items into the database
|
||||
// @Tags Items
|
||||
// @Produce json
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param file formData file true "File attachment"
|
||||
// @Param type formData string true "Type of file"
|
||||
// @Param name formData string true "name of the file including extension"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Failure 422 {object} []server.ValidationError
|
||||
// @Router /v1/items/{id}/attachments [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentCreate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to parse multipart form")
|
||||
server.RespondError(w, http.StatusBadRequest, errors.New("failed to parse multipart form"))
|
||||
return
|
||||
}
|
||||
|
||||
errs := make(server.ValidationErrors, 0)
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, http.ErrMissingFile):
|
||||
log.Debug().Msg("file for attachment is missing")
|
||||
errs = errs.Append("file", "file is required")
|
||||
default:
|
||||
log.Err(err).Msg("failed to get file from form")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
attachmentName := r.FormValue("name")
|
||||
if attachmentName == "" {
|
||||
log.Debug().Msg("failed to get name from form")
|
||||
errs = errs.Append("name", "name is required")
|
||||
}
|
||||
|
||||
if errs.HasErrors() {
|
||||
server.Respond(w, http.StatusUnprocessableEntity, errs)
|
||||
return
|
||||
}
|
||||
|
||||
attachmentType := r.FormValue("type")
|
||||
if attachmentType == "" {
|
||||
attachmentType = attachment.TypeAttachment.String()
|
||||
}
|
||||
|
||||
id, _, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
item, err := ctrl.svc.Items.AttachmentAdd(
|
||||
ctx,
|
||||
id,
|
||||
attachmentName,
|
||||
attachment.Type(attachmentType),
|
||||
file,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to add attachment")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusCreated, item)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemAttachmentGet godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items
|
||||
// @Produce application/octet-stream
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param token query string true "Attachment token"
|
||||
// @Success 200
|
||||
// @Router /v1/items/{id}/attachments/download [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentDownload() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := server.GetParam(r, "token", "")
|
||||
|
||||
doc, err := ctrl.svc.Items.AttachmentPath(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get attachment")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", doc.Title))
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
http.ServeFile(w, r, doc.Path)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleItemAttachmentToken godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items
|
||||
// @Produce application/octet-stream
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param attachment_id path string true "Attachment ID"
|
||||
// @Success 200 {object} ItemAttachmentToken
|
||||
// @Router /v1/items/{id}/attachments/{attachment_id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentToken() http.HandlerFunc {
|
||||
return ctrl.handleItemAttachmentsHandler
|
||||
}
|
||||
|
||||
// HandleItemAttachmentDelete godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param attachment_id path string true "Attachment ID"
|
||||
// @Success 204
|
||||
// @Router /v1/items/{id}/attachments/{attachment_id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentDelete() http.HandlerFunc {
|
||||
return ctrl.handleItemAttachmentsHandler
|
||||
}
|
||||
|
||||
// HandleItemAttachmentUpdate godocs
|
||||
// @Summary retrieves an attachment for an item
|
||||
// @Tags Items
|
||||
// @Param id path string true "Item ID"
|
||||
// @Param attachment_id path string true "Attachment ID"
|
||||
// @Param payload body repo.ItemAttachmentUpdate true "Attachment Update"
|
||||
// @Success 200 {object} repo.ItemOut
|
||||
// @Router /v1/items/{id}/attachments/{attachment_id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleItemAttachmentUpdate() http.HandlerFunc {
|
||||
return ctrl.handleItemAttachmentsHandler
|
||||
}
|
||||
|
||||
func (ctrl *V1Controller) handleItemAttachmentsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
attachmentId, err := uuid.Parse(chi.URLParam(r, "attachment_id"))
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to parse attachment_id param")
|
||||
server.RespondError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
switch r.Method {
|
||||
|
||||
// Token Handler
|
||||
case http.MethodGet:
|
||||
token, err := ctrl.svc.Items.AttachmentToken(ctx, uid, attachmentId)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case services.ErrNotFound:
|
||||
log.Err(err).
|
||||
Str("id", attachmentId.String()).
|
||||
Msg("failed to find attachment with id")
|
||||
|
||||
server.RespondError(w, http.StatusNotFound, err)
|
||||
|
||||
case services.ErrFileNotFound:
|
||||
log.Err(err).
|
||||
Str("id", attachmentId.String()).
|
||||
Msg("failed to find file path for attachment with id")
|
||||
log.Warn().Msg("attachment with no file path removed from database")
|
||||
|
||||
server.RespondError(w, http.StatusNotFound, err)
|
||||
|
||||
default:
|
||||
log.Err(err).Msg("failed to get attachment")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, ItemAttachmentToken{Token: token})
|
||||
|
||||
// Delete Attachment Handler
|
||||
case http.MethodDelete:
|
||||
err = ctrl.svc.Items.AttachmentDelete(r.Context(), user.GroupID, uid, attachmentId)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete attachment")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
|
||||
// Update Attachment Handler
|
||||
case http.MethodPut:
|
||||
var attachment repo.ItemAttachmentUpdate
|
||||
err = server.Decode(r, &attachment)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to decode attachment")
|
||||
server.RespondError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
attachment.ID = attachmentId
|
||||
val, err := ctrl.svc.Items.AttachmentUpdate(ctx, uid, &attachment)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete attachment")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, val)
|
||||
}
|
||||
}
|
||||
150
backend/app/api/v1/v1_ctrl_labels.go
Normal file
150
backend/app/api/v1/v1_ctrl_labels.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleLabelsGetAll godoc
|
||||
// @Summary Get All Labels
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Results{items=[]repo.LabelOut}
|
||||
// @Router /v1/labels [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelsGetAll() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := services.UseUserCtx(r.Context())
|
||||
labels, err := ctrl.svc.Labels.GetAll(r.Context(), user.GroupID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error getting labels")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, server.Results{Items: labels})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLabelsCreate godoc
|
||||
// @Summary Create a new label
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param payload body repo.LabelCreate true "Label Data"
|
||||
// @Success 200 {object} repo.LabelSummary
|
||||
// @Router /v1/labels [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelsCreate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
createData := repo.LabelCreate{}
|
||||
if err := server.Decode(r, &createData); err != nil {
|
||||
log.Err(err).Msg("error decoding label create data")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
label, err := ctrl.svc.Labels.Create(r.Context(), user.GroupID, createData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error creating label")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusCreated, label)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLabelDelete godocs
|
||||
// @Summary deletes a label
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param id path string true "Label ID"
|
||||
// @Success 204
|
||||
// @Router /v1/labels/{id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelDelete() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = ctrl.svc.Labels.Delete(r.Context(), user.GroupID, uid)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error deleting label")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLabelGet godocs
|
||||
// @Summary Gets a label and fields
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param id path string true "Label ID"
|
||||
// @Success 200 {object} repo.LabelOut
|
||||
// @Router /v1/labels/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelGet() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
labels, err := ctrl.svc.Labels.Get(r.Context(), user.GroupID, uid)
|
||||
if err != nil {
|
||||
if ent.IsNotFound(err) {
|
||||
log.Err(err).
|
||||
Str("id", uid.String()).
|
||||
Msg("label not found")
|
||||
server.RespondError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
log.Err(err).Msg("error getting label")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, labels)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLabelUpdate godocs
|
||||
// @Summary updates a label
|
||||
// @Tags Labels
|
||||
// @Produce json
|
||||
// @Param id path string true "Label ID"
|
||||
// @Success 200 {object} repo.LabelOut
|
||||
// @Router /v1/labels/{id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLabelUpdate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
body := repo.LabelUpdate{}
|
||||
if err := server.Decode(r, &body); err != nil {
|
||||
log.Err(err).Msg("error decoding label update data")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
body.ID = uid
|
||||
result, err := ctrl.svc.Labels.Update(r.Context(), user.GroupID, body)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("error updating label")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
157
backend/app/api/v1/v1_ctrl_locations.go
Normal file
157
backend/app/api/v1/v1_ctrl_locations.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleLocationGetAll godoc
|
||||
// @Summary Get All Locations
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Results{items=[]repo.LocationOutCount}
|
||||
// @Router /v1/locations [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationGetAll() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := services.UseUserCtx(r.Context())
|
||||
locations, err := ctrl.svc.Location.GetAll(r.Context(), user.GroupID)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to get locations")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, server.Results{Items: locations})
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationCreate godoc
|
||||
// @Summary Create a new location
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param payload body repo.LocationCreate true "Location Data"
|
||||
// @Success 200 {object} repo.LocationSummary
|
||||
// @Router /v1/locations [POST]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationCreate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
createData := repo.LocationCreate{}
|
||||
if err := server.Decode(r, &createData); err != nil {
|
||||
log.Err(err).Msg("failed to decode location create data")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
user := services.UseUserCtx(r.Context())
|
||||
location, err := ctrl.svc.Location.Create(r.Context(), user.GroupID, createData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to create location")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusCreated, location)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationDelete godocs
|
||||
// @Summary deletes a location
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param id path string true "Location ID"
|
||||
// @Success 204
|
||||
// @Router /v1/locations/{id} [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationDelete() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = ctrl.svc.Location.Delete(r.Context(), user.GroupID, uid)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to delete location")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationGet godocs
|
||||
// @Summary Gets a location and fields
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param id path string true "Location ID"
|
||||
// @Success 200 {object} repo.LocationOut
|
||||
// @Router /v1/locations/{id} [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationGet() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
location, err := ctrl.svc.Location.GetOne(r.Context(), user.GroupID, uid)
|
||||
if err != nil {
|
||||
if ent.IsNotFound(err) {
|
||||
log.Err(err).
|
||||
Str("id", uid.String()).
|
||||
Str("gid", user.GroupID.String()).
|
||||
Msg("location not found")
|
||||
server.RespondError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Err(err).
|
||||
Str("id", uid.String()).
|
||||
Str("gid", user.GroupID.String()).
|
||||
Msg("failed to get location")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, location)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleLocationUpdate godocs
|
||||
// @Summary updates a location
|
||||
// @Tags Locations
|
||||
// @Produce json
|
||||
// @Param id path string true "Location ID"
|
||||
// @Success 200 {object} repo.LocationOut
|
||||
// @Router /v1/locations/{id} [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleLocationUpdate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
body := repo.LocationUpdate{}
|
||||
if err := server.Decode(r, &body); err != nil {
|
||||
log.Err(err).Msg("failed to decode location update data")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
uid, user, err := ctrl.partialParseIdAndUser(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
body.ID = uid
|
||||
|
||||
result, err := ctrl.svc.Location.Update(r.Context(), user.GroupID, body)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to update location")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
server.Respond(w, http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
160
backend/app/api/v1/v1_ctrl_user.go
Normal file
160
backend/app/api/v1/v1_ctrl_user.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/repo"
|
||||
"github.com/hay-kot/homebox/backend/internal/services"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// HandleUserSelf godoc
|
||||
// @Summary Get the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Param payload body services.UserRegistration true "User Data"
|
||||
// @Success 204
|
||||
// @Router /v1/users/register [Post]
|
||||
func (ctrl *V1Controller) HandleUserRegistration() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
regData := services.UserRegistration{}
|
||||
|
||||
if err := server.Decode(r, ®Data); err != nil {
|
||||
log.Err(err).Msg("failed to decode user registration data")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := ctrl.svc.User.RegisterUser(r.Context(), regData)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to register user")
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelf godoc
|
||||
// @Summary Get the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Success 200 {object} server.Result{item=repo.UserOut}
|
||||
// @Router /v1/users/self [GET]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelf() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := services.UseTokenCtx(r.Context())
|
||||
usr, err := ctrl.svc.User.GetSelf(r.Context(), token)
|
||||
if usr.ID == uuid.Nil || err != nil {
|
||||
log.Err(err).Msg("failed to get user")
|
||||
server.RespondServerError(w)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, server.Wrap(usr))
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelfUpdate godoc
|
||||
// @Summary Update the current user
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Param payload body repo.UserUpdate true "User Data"
|
||||
// @Success 200 {object} server.Result{item=repo.UserUpdate}
|
||||
// @Router /v1/users/self [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfUpdate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
updateData := repo.UserUpdate{}
|
||||
if err := server.Decode(r, &updateData); err != nil {
|
||||
log.Err(err).Msg("failed to decode user update data")
|
||||
server.RespondError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
actor := services.UseUserCtx(r.Context())
|
||||
newData, err := ctrl.svc.User.UpdateSelf(r.Context(), actor.ID, updateData)
|
||||
|
||||
if err != nil {
|
||||
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusOK, server.Wrap(newData))
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserUpdatePassword godoc
|
||||
// @Summary Update the current user's password // TODO:
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Router /v1/users/self/password [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserUpdatePassword() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUserSelfDelete godoc
|
||||
// @Summary Deletes the user account
|
||||
// @Tags User
|
||||
// @Produce json
|
||||
// @Success 204
|
||||
// @Router /v1/users/self [DELETE]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfDelete() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
actor := services.UseUserCtx(r.Context())
|
||||
if err := ctrl.svc.User.DeleteSelf(r.Context(), actor.ID); err != nil {
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
|
||||
type (
|
||||
ChangePassword struct {
|
||||
Current string `json:"current,omitempty"`
|
||||
New string `json:"new,omitempty"`
|
||||
}
|
||||
)
|
||||
|
||||
// HandleUserSelfChangePassword godoc
|
||||
// @Summary Updates the users password
|
||||
// @Tags User
|
||||
// @Success 204
|
||||
// @Param payload body ChangePassword true "Password Payload"
|
||||
// @Router /v1/users/change-password [PUT]
|
||||
// @Security Bearer
|
||||
func (ctrl *V1Controller) HandleUserSelfChangePassword() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if ctrl.isDemo {
|
||||
server.RespondError(w, http.StatusForbidden, nil)
|
||||
return
|
||||
}
|
||||
|
||||
var cp ChangePassword
|
||||
err := server.Decode(r, &cp)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("user failed to change password")
|
||||
}
|
||||
|
||||
ctx := services.NewContext(r.Context())
|
||||
|
||||
ok := ctrl.svc.User.ChangePassword(ctx, cp.Current, cp.New)
|
||||
if !ok {
|
||||
server.RespondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
server.Respond(w, http.StatusNoContent, nil)
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,10 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/migrate"
|
||||
"github.com/hay-kot/homebox/backend/ent/migrate"
|
||||
|
||||
atlas "ariga.io/atlas/sql/migrate"
|
||||
_ "ariga.io/atlas/sql/sqlite"
|
||||
@@ -18,7 +17,7 @@ import (
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
// Create a local migration directory able to understand Atlas migration file format for replay.
|
||||
dir, err := atlas.NewLocalDir("internal/data/migrations/migrations")
|
||||
dir, err := atlas.NewLocalDir("internal/migrations/migrations")
|
||||
if err != nil {
|
||||
log.Fatalf("failed creating atlas migration directory: %v", err)
|
||||
}
|
||||
@@ -40,6 +39,4 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatalf("failed generating migration file: %v", err)
|
||||
}
|
||||
|
||||
fmt.Println("Migration file generated successfully.")
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
)
|
||||
|
||||
// Attachment is the model entity for the Attachment schema.
|
||||
@@ -144,19 +144,19 @@ func (a *Attachment) assignValues(columns []string, values []any) error {
|
||||
|
||||
// QueryItem queries the "item" edge of the Attachment entity.
|
||||
func (a *Attachment) QueryItem() *ItemQuery {
|
||||
return NewAttachmentClient(a.config).QueryItem(a)
|
||||
return (&AttachmentClient{config: a.config}).QueryItem(a)
|
||||
}
|
||||
|
||||
// QueryDocument queries the "document" edge of the Attachment entity.
|
||||
func (a *Attachment) QueryDocument() *DocumentQuery {
|
||||
return NewAttachmentClient(a.config).QueryDocument(a)
|
||||
return (&AttachmentClient{config: a.config}).QueryDocument(a)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Attachment.
|
||||
// Note that you need to call Attachment.Unwrap() before calling this method if this Attachment
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (a *Attachment) Update() *AttachmentUpdateOne {
|
||||
return NewAttachmentClient(a.config).UpdateOne(a)
|
||||
return (&AttachmentClient{config: a.config}).UpdateOne(a)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Attachment entity that was returned from a transaction after it was closed,
|
||||
@@ -95,7 +95,6 @@ const (
|
||||
TypeManual Type = "manual"
|
||||
TypeWarranty Type = "warranty"
|
||||
TypeAttachment Type = "attachment"
|
||||
TypeReceipt Type = "receipt"
|
||||
)
|
||||
|
||||
func (_type Type) String() string {
|
||||
@@ -105,7 +104,7 @@ func (_type Type) String() string {
|
||||
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
|
||||
func TypeValidator(_type Type) error {
|
||||
switch _type {
|
||||
case TypePhoto, TypeManual, TypeWarranty, TypeAttachment, TypeReceipt:
|
||||
case TypePhoto, TypeManual, TypeWarranty, TypeAttachment:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("attachment: invalid enum value for type field: %q", _type)
|
||||
@@ -8,162 +8,256 @@ import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNEQ(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldIn(FieldID, ids...))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.In(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNotIn(FieldID, ids...))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.NotIn(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldGT(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldGTE(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldLT(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldLTE(FieldID, id))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldGT(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldGTE(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldLT(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldLTE(FieldCreatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldGT(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldLT(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TypeEQ applies the EQ predicate on the "type" field.
|
||||
func TypeEQ(v Type) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldEQ(FieldType, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldType), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TypeNEQ applies the NEQ predicate on the "type" field.
|
||||
func TypeNEQ(v Type) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNEQ(FieldType, v))
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldType), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TypeIn applies the In predicate on the "type" field.
|
||||
func TypeIn(vs ...Type) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldIn(FieldType, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldType), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TypeNotIn applies the NotIn predicate on the "type" field.
|
||||
func TypeNotIn(vs ...Type) predicate.Attachment {
|
||||
return predicate.Attachment(sql.FieldNotIn(FieldType, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldType), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// HasItem applies the HasEdge predicate on the "item" edge.
|
||||
@@ -171,6 +265,7 @@ func HasItem() predicate.Attachment {
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(ItemTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, ItemTable, ItemColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -198,6 +293,7 @@ func HasDocument() predicate.Attachment {
|
||||
return predicate.Attachment(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DocumentTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
)
|
||||
|
||||
// AttachmentCreate is the builder for creating a Attachment entity.
|
||||
@@ -108,8 +108,50 @@ func (ac *AttachmentCreate) Mutation() *AttachmentMutation {
|
||||
|
||||
// Save creates the Attachment in the database.
|
||||
func (ac *AttachmentCreate) Save(ctx context.Context) (*Attachment, error) {
|
||||
var (
|
||||
err error
|
||||
node *Attachment
|
||||
)
|
||||
ac.defaults()
|
||||
return withHooks[*Attachment, AttachmentMutation](ctx, ac.sqlSave, ac.mutation, ac.hooks)
|
||||
if len(ac.hooks) == 0 {
|
||||
if err = ac.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = ac.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AttachmentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = ac.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ac.mutation = mutation
|
||||
if node, err = ac.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(ac.hooks) - 1; i >= 0; i-- {
|
||||
if ac.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = ac.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, ac.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Attachment)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from AttachmentMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
@@ -180,9 +222,6 @@ func (ac *AttachmentCreate) check() error {
|
||||
}
|
||||
|
||||
func (ac *AttachmentCreate) sqlSave(ctx context.Context) (*Attachment, error) {
|
||||
if err := ac.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := ac.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, ac.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
@@ -197,8 +236,6 @@ func (ac *AttachmentCreate) sqlSave(ctx context.Context) (*Attachment, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ac.mutation.id = &_node.ID
|
||||
ac.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
@@ -218,15 +255,27 @@ func (ac *AttachmentCreate) createSpec() (*Attachment, *sqlgraph.CreateSpec) {
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := ac.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(attachment.FieldCreatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: attachment.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := ac.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(attachment.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: attachment.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := ac.mutation.GetType(); ok {
|
||||
_spec.SetField(attachment.FieldType, field.TypeEnum, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeEnum,
|
||||
Value: value,
|
||||
Column: attachment.FieldType,
|
||||
})
|
||||
_node.Type = value
|
||||
}
|
||||
if nodes := ac.mutation.ItemIDs(); len(nodes) > 0 {
|
||||
@@ -4,12 +4,13 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// AttachmentDelete is the builder for deleting a Attachment entity.
|
||||
@@ -27,7 +28,34 @@ func (ad *AttachmentDelete) Where(ps ...predicate.Attachment) *AttachmentDelete
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (ad *AttachmentDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks[int, AttachmentMutation](ctx, ad.sqlExec, ad.mutation, ad.hooks)
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
if len(ad.hooks) == 0 {
|
||||
affected, err = ad.sqlExec(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AttachmentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
ad.mutation = mutation
|
||||
affected, err = ad.sqlExec(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(ad.hooks) - 1; i >= 0; i-- {
|
||||
if ad.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = ad.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, ad.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
@@ -60,7 +88,6 @@ func (ad *AttachmentDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
ad.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
@@ -69,12 +96,6 @@ type AttachmentDeleteOne struct {
|
||||
ad *AttachmentDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AttachmentDelete builder.
|
||||
func (ado *AttachmentDeleteOne) Where(ps ...predicate.Attachment) *AttachmentDeleteOne {
|
||||
ado.ad.mutation.Where(ps...)
|
||||
return ado
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (ado *AttachmentDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := ado.ad.Exec(ctx)
|
||||
@@ -90,7 +111,5 @@ func (ado *AttachmentDeleteOne) Exec(ctx context.Context) error {
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ado *AttachmentDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := ado.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ado.ad.ExecX(ctx)
|
||||
}
|
||||
@@ -11,18 +11,20 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// AttachmentQuery is the builder for querying Attachment entities.
|
||||
type AttachmentQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
limit *int
|
||||
offset *int
|
||||
unique *bool
|
||||
order []OrderFunc
|
||||
inters []Interceptor
|
||||
fields []string
|
||||
predicates []predicate.Attachment
|
||||
withItem *ItemQuery
|
||||
withDocument *DocumentQuery
|
||||
@@ -38,26 +40,26 @@ func (aq *AttachmentQuery) Where(ps ...predicate.Attachment) *AttachmentQuery {
|
||||
return aq
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
// Limit adds a limit step to the query.
|
||||
func (aq *AttachmentQuery) Limit(limit int) *AttachmentQuery {
|
||||
aq.ctx.Limit = &limit
|
||||
aq.limit = &limit
|
||||
return aq
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
// Offset adds an offset step to the query.
|
||||
func (aq *AttachmentQuery) Offset(offset int) *AttachmentQuery {
|
||||
aq.ctx.Offset = &offset
|
||||
aq.offset = &offset
|
||||
return aq
|
||||
}
|
||||
|
||||
// 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 (aq *AttachmentQuery) Unique(unique bool) *AttachmentQuery {
|
||||
aq.ctx.Unique = &unique
|
||||
aq.unique = &unique
|
||||
return aq
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
// Order adds an order step to the query.
|
||||
func (aq *AttachmentQuery) Order(o ...OrderFunc) *AttachmentQuery {
|
||||
aq.order = append(aq.order, o...)
|
||||
return aq
|
||||
@@ -65,7 +67,7 @@ func (aq *AttachmentQuery) Order(o ...OrderFunc) *AttachmentQuery {
|
||||
|
||||
// QueryItem chains the current query on the "item" edge.
|
||||
func (aq *AttachmentQuery) QueryItem() *ItemQuery {
|
||||
query := (&ItemClient{config: aq.config}).Query()
|
||||
query := &ItemQuery{config: aq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := aq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -87,7 +89,7 @@ func (aq *AttachmentQuery) QueryItem() *ItemQuery {
|
||||
|
||||
// QueryDocument chains the current query on the "document" edge.
|
||||
func (aq *AttachmentQuery) QueryDocument() *DocumentQuery {
|
||||
query := (&DocumentClient{config: aq.config}).Query()
|
||||
query := &DocumentQuery{config: aq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := aq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -110,7 +112,7 @@ func (aq *AttachmentQuery) QueryDocument() *DocumentQuery {
|
||||
// First returns the first Attachment entity from the query.
|
||||
// Returns a *NotFoundError when no Attachment was found.
|
||||
func (aq *AttachmentQuery) First(ctx context.Context) (*Attachment, error) {
|
||||
nodes, err := aq.Limit(1).All(setContextOp(ctx, aq.ctx, "First"))
|
||||
nodes, err := aq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -133,7 +135,7 @@ func (aq *AttachmentQuery) FirstX(ctx context.Context) *Attachment {
|
||||
// Returns a *NotFoundError when no Attachment ID was found.
|
||||
func (aq *AttachmentQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = aq.Limit(1).IDs(setContextOp(ctx, aq.ctx, "FirstID")); err != nil {
|
||||
if ids, err = aq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
@@ -156,7 +158,7 @@ func (aq *AttachmentQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
// Returns a *NotSingularError when more than one Attachment entity is found.
|
||||
// Returns a *NotFoundError when no Attachment entities are found.
|
||||
func (aq *AttachmentQuery) Only(ctx context.Context) (*Attachment, error) {
|
||||
nodes, err := aq.Limit(2).All(setContextOp(ctx, aq.ctx, "Only"))
|
||||
nodes, err := aq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -184,7 +186,7 @@ func (aq *AttachmentQuery) OnlyX(ctx context.Context) *Attachment {
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (aq *AttachmentQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = aq.Limit(2).IDs(setContextOp(ctx, aq.ctx, "OnlyID")); err != nil {
|
||||
if ids, err = aq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
@@ -209,12 +211,10 @@ func (aq *AttachmentQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
|
||||
// All executes the query and returns a list of Attachments.
|
||||
func (aq *AttachmentQuery) All(ctx context.Context) ([]*Attachment, error) {
|
||||
ctx = setContextOp(ctx, aq.ctx, "All")
|
||||
if err := aq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Attachment, *AttachmentQuery]()
|
||||
return withInterceptors[[]*Attachment](ctx, aq, qr, aq.inters)
|
||||
return aq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
@@ -229,7 +229,6 @@ func (aq *AttachmentQuery) AllX(ctx context.Context) []*Attachment {
|
||||
// IDs executes the query and returns a list of Attachment IDs.
|
||||
func (aq *AttachmentQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
var ids []uuid.UUID
|
||||
ctx = setContextOp(ctx, aq.ctx, "IDs")
|
||||
if err := aq.Select(attachment.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -247,11 +246,10 @@ func (aq *AttachmentQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (aq *AttachmentQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, aq.ctx, "Count")
|
||||
if err := aq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, aq, querierCount[*AttachmentQuery](), aq.inters)
|
||||
return aq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
@@ -265,15 +263,10 @@ func (aq *AttachmentQuery) CountX(ctx context.Context) int {
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (aq *AttachmentQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, aq.ctx, "Exist")
|
||||
switch _, err := aq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
if err := aq.prepareQuery(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return aq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
@@ -293,22 +286,23 @@ func (aq *AttachmentQuery) Clone() *AttachmentQuery {
|
||||
}
|
||||
return &AttachmentQuery{
|
||||
config: aq.config,
|
||||
ctx: aq.ctx.Clone(),
|
||||
limit: aq.limit,
|
||||
offset: aq.offset,
|
||||
order: append([]OrderFunc{}, aq.order...),
|
||||
inters: append([]Interceptor{}, aq.inters...),
|
||||
predicates: append([]predicate.Attachment{}, aq.predicates...),
|
||||
withItem: aq.withItem.Clone(),
|
||||
withDocument: aq.withDocument.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: aq.sql.Clone(),
|
||||
path: aq.path,
|
||||
sql: aq.sql.Clone(),
|
||||
path: aq.path,
|
||||
unique: aq.unique,
|
||||
}
|
||||
}
|
||||
|
||||
// WithItem tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "item" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (aq *AttachmentQuery) WithItem(opts ...func(*ItemQuery)) *AttachmentQuery {
|
||||
query := (&ItemClient{config: aq.config}).Query()
|
||||
query := &ItemQuery{config: aq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -319,7 +313,7 @@ func (aq *AttachmentQuery) WithItem(opts ...func(*ItemQuery)) *AttachmentQuery {
|
||||
// WithDocument tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "document" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (aq *AttachmentQuery) WithDocument(opts ...func(*DocumentQuery)) *AttachmentQuery {
|
||||
query := (&DocumentClient{config: aq.config}).Query()
|
||||
query := &DocumentQuery{config: aq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -342,11 +336,16 @@ func (aq *AttachmentQuery) WithDocument(opts ...func(*DocumentQuery)) *Attachmen
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (aq *AttachmentQuery) GroupBy(field string, fields ...string) *AttachmentGroupBy {
|
||||
aq.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &AttachmentGroupBy{build: aq}
|
||||
grbuild.flds = &aq.ctx.Fields
|
||||
grbuild := &AttachmentGroupBy{config: aq.config}
|
||||
grbuild.fields = append([]string{field}, fields...)
|
||||
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
|
||||
if err := aq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return aq.sqlQuery(ctx), nil
|
||||
}
|
||||
grbuild.label = attachment.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
@@ -363,30 +362,15 @@ func (aq *AttachmentQuery) GroupBy(field string, fields ...string) *AttachmentGr
|
||||
// Select(attachment.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (aq *AttachmentQuery) Select(fields ...string) *AttachmentSelect {
|
||||
aq.ctx.Fields = append(aq.ctx.Fields, fields...)
|
||||
sbuild := &AttachmentSelect{AttachmentQuery: aq}
|
||||
sbuild.label = attachment.Label
|
||||
sbuild.flds, sbuild.scan = &aq.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a AttachmentSelect configured with the given aggregations.
|
||||
func (aq *AttachmentQuery) Aggregate(fns ...AggregateFunc) *AttachmentSelect {
|
||||
return aq.Select().Aggregate(fns...)
|
||||
aq.fields = append(aq.fields, fields...)
|
||||
selbuild := &AttachmentSelect{AttachmentQuery: aq}
|
||||
selbuild.label = attachment.Label
|
||||
selbuild.flds, selbuild.scan = &aq.fields, selbuild.Scan
|
||||
return selbuild
|
||||
}
|
||||
|
||||
func (aq *AttachmentQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range aq.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, aq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range aq.ctx.Fields {
|
||||
for _, f := range aq.fields {
|
||||
if !attachment.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
@@ -463,9 +447,6 @@ func (aq *AttachmentQuery) loadItem(ctx context.Context, query *ItemQuery, nodes
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(item.IDIn(ids...))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
@@ -495,9 +476,6 @@ func (aq *AttachmentQuery) loadDocument(ctx context.Context, query *DocumentQuer
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(document.IDIn(ids...))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
@@ -517,13 +495,24 @@ func (aq *AttachmentQuery) loadDocument(ctx context.Context, query *DocumentQuer
|
||||
|
||||
func (aq *AttachmentQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := aq.querySpec()
|
||||
_spec.Node.Columns = aq.ctx.Fields
|
||||
if len(aq.ctx.Fields) > 0 {
|
||||
_spec.Unique = aq.ctx.Unique != nil && *aq.ctx.Unique
|
||||
_spec.Node.Columns = aq.fields
|
||||
if len(aq.fields) > 0 {
|
||||
_spec.Unique = aq.unique != nil && *aq.unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, aq.driver, _spec)
|
||||
}
|
||||
|
||||
func (aq *AttachmentQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
switch _, err := aq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (aq *AttachmentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := &sqlgraph.QuerySpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
@@ -537,10 +526,10 @@ func (aq *AttachmentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
From: aq.sql,
|
||||
Unique: true,
|
||||
}
|
||||
if unique := aq.ctx.Unique; unique != nil {
|
||||
if unique := aq.unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
}
|
||||
if fields := aq.ctx.Fields; len(fields) > 0 {
|
||||
if fields := aq.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, attachment.FieldID)
|
||||
for i := range fields {
|
||||
@@ -556,10 +545,10 @@ func (aq *AttachmentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := aq.ctx.Limit; limit != nil {
|
||||
if limit := aq.limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := aq.ctx.Offset; offset != nil {
|
||||
if offset := aq.offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := aq.order; len(ps) > 0 {
|
||||
@@ -575,7 +564,7 @@ func (aq *AttachmentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
func (aq *AttachmentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(aq.driver.Dialect())
|
||||
t1 := builder.Table(attachment.Table)
|
||||
columns := aq.ctx.Fields
|
||||
columns := aq.fields
|
||||
if len(columns) == 0 {
|
||||
columns = attachment.Columns
|
||||
}
|
||||
@@ -584,7 +573,7 @@ func (aq *AttachmentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
selector = aq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if aq.ctx.Unique != nil && *aq.ctx.Unique {
|
||||
if aq.unique != nil && *aq.unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range aq.predicates {
|
||||
@@ -593,12 +582,12 @@ func (aq *AttachmentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
for _, p := range aq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := aq.ctx.Offset; offset != nil {
|
||||
if offset := aq.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 := aq.ctx.Limit; limit != nil {
|
||||
if limit := aq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
@@ -606,8 +595,13 @@ func (aq *AttachmentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
|
||||
// AttachmentGroupBy is the group-by builder for Attachment entities.
|
||||
type AttachmentGroupBy struct {
|
||||
config
|
||||
selector
|
||||
build *AttachmentQuery
|
||||
fields []string
|
||||
fns []AggregateFunc
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
@@ -616,77 +610,74 @@ func (agb *AttachmentGroupBy) Aggregate(fns ...AggregateFunc) *AttachmentGroupBy
|
||||
return agb
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
// Scan applies the group-by query and scans the result into the given value.
|
||||
func (agb *AttachmentGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, agb.build.ctx, "GroupBy")
|
||||
if err := agb.build.prepareQuery(ctx); err != nil {
|
||||
query, err := agb.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*AttachmentQuery, *AttachmentGroupBy](ctx, agb.build, agb, agb.build.inters, v)
|
||||
agb.sql = query
|
||||
return agb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (agb *AttachmentGroupBy) sqlScan(ctx context.Context, root *AttachmentQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(agb.fns))
|
||||
for _, fn := range agb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*agb.flds)+len(agb.fns))
|
||||
for _, f := range *agb.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
func (agb *AttachmentGroupBy) sqlScan(ctx context.Context, v any) error {
|
||||
for _, f := range agb.fields {
|
||||
if !attachment.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*agb.flds...)...)
|
||||
selector := agb.sqlQuery()
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := agb.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
if err := agb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (agb *AttachmentGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := agb.sql.Select()
|
||||
aggregation := make([]string, 0, len(agb.fns))
|
||||
for _, fn := range agb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
// If no columns were selected in a custom aggregation function, the default
|
||||
// selection is the fields used for "group-by", and the aggregation functions.
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(agb.fields)+len(agb.fns))
|
||||
for _, f := range agb.fields {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
return selector.GroupBy(selector.Columns(agb.fields...)...)
|
||||
}
|
||||
|
||||
// AttachmentSelect is the builder for selecting fields of Attachment entities.
|
||||
type AttachmentSelect struct {
|
||||
*AttachmentQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (as *AttachmentSelect) Aggregate(fns ...AggregateFunc) *AttachmentSelect {
|
||||
as.fns = append(as.fns, fns...)
|
||||
return as
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (as *AttachmentSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, as.ctx, "Select")
|
||||
if err := as.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*AttachmentQuery, *AttachmentSelect](ctx, as.AttachmentQuery, as, as.inters, v)
|
||||
as.sql = as.AttachmentQuery.sqlQuery(ctx)
|
||||
return as.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (as *AttachmentSelect) sqlScan(ctx context.Context, root *AttachmentQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(as.fns))
|
||||
for _, fn := range as.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*as.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
func (as *AttachmentSelect) sqlScan(ctx context.Context, v any) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
query, args := as.sql.Query()
|
||||
if err := as.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// AttachmentUpdate is the builder for updating Attachment entities.
|
||||
@@ -92,8 +92,41 @@ func (au *AttachmentUpdate) ClearDocument() *AttachmentUpdate {
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (au *AttachmentUpdate) Save(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
au.defaults()
|
||||
return withHooks[int, AttachmentMutation](ctx, au.sqlSave, au.mutation, au.hooks)
|
||||
if len(au.hooks) == 0 {
|
||||
if err = au.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err = au.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AttachmentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = au.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
au.mutation = mutation
|
||||
affected, err = au.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(au.hooks) - 1; i >= 0; i-- {
|
||||
if au.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = au.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, au.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -143,9 +176,6 @@ func (au *AttachmentUpdate) check() error {
|
||||
}
|
||||
|
||||
func (au *AttachmentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if err := au.check(); err != nil {
|
||||
return n, err
|
||||
}
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: attachment.Table,
|
||||
@@ -164,10 +194,18 @@ func (au *AttachmentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
}
|
||||
if value, ok := au.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(attachment.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: attachment.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := au.mutation.GetType(); ok {
|
||||
_spec.SetField(attachment.FieldType, field.TypeEnum, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeEnum,
|
||||
Value: value,
|
||||
Column: attachment.FieldType,
|
||||
})
|
||||
}
|
||||
if au.mutation.ItemCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -247,7 +285,6 @@ func (au *AttachmentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
au.mutation.done = true
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@@ -327,8 +364,47 @@ func (auo *AttachmentUpdateOne) Select(field string, fields ...string) *Attachme
|
||||
|
||||
// Save executes the query and returns the updated Attachment entity.
|
||||
func (auo *AttachmentUpdateOne) Save(ctx context.Context) (*Attachment, error) {
|
||||
var (
|
||||
err error
|
||||
node *Attachment
|
||||
)
|
||||
auo.defaults()
|
||||
return withHooks[*Attachment, AttachmentMutation](ctx, auo.sqlSave, auo.mutation, auo.hooks)
|
||||
if len(auo.hooks) == 0 {
|
||||
if err = auo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = auo.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AttachmentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = auo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
auo.mutation = mutation
|
||||
node, err = auo.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(auo.hooks) - 1; i >= 0; i-- {
|
||||
if auo.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = auo.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, auo.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Attachment)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from AttachmentMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -378,9 +454,6 @@ func (auo *AttachmentUpdateOne) check() error {
|
||||
}
|
||||
|
||||
func (auo *AttachmentUpdateOne) sqlSave(ctx context.Context) (_node *Attachment, err error) {
|
||||
if err := auo.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: attachment.Table,
|
||||
@@ -416,10 +489,18 @@ func (auo *AttachmentUpdateOne) sqlSave(ctx context.Context) (_node *Attachment,
|
||||
}
|
||||
}
|
||||
if value, ok := auo.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(attachment.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: attachment.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := auo.mutation.GetType(); ok {
|
||||
_spec.SetField(attachment.FieldType, field.TypeEnum, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeEnum,
|
||||
Value: value,
|
||||
Column: attachment.FieldType,
|
||||
})
|
||||
}
|
||||
if auo.mutation.ItemCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -502,6 +583,5 @@ func (auo *AttachmentUpdateOne) sqlSave(ctx context.Context) (_node *Attachment,
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
auo.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -9,9 +9,8 @@ import (
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authroles"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// AuthTokens is the model entity for the AuthTokens schema.
|
||||
@@ -37,11 +36,9 @@ type AuthTokens struct {
|
||||
type AuthTokensEdges struct {
|
||||
// User holds the value of the user edge.
|
||||
User *User `json:"user,omitempty"`
|
||||
// Roles holds the value of the roles edge.
|
||||
Roles *AuthRoles `json:"roles,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]bool
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// UserOrErr returns the User value or an error if the edge
|
||||
@@ -57,19 +54,6 @@ func (e AuthTokensEdges) UserOrErr() (*User, error) {
|
||||
return nil, &NotLoadedError{edge: "user"}
|
||||
}
|
||||
|
||||
// RolesOrErr returns the Roles value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e AuthTokensEdges) RolesOrErr() (*AuthRoles, error) {
|
||||
if e.loadedTypes[1] {
|
||||
if e.Roles == nil {
|
||||
// Edge was loaded but was not found.
|
||||
return nil, &NotFoundError{label: authroles.Label}
|
||||
}
|
||||
return e.Roles, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "roles"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*AuthTokens) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
@@ -142,19 +126,14 @@ func (at *AuthTokens) assignValues(columns []string, values []any) error {
|
||||
|
||||
// QueryUser queries the "user" edge of the AuthTokens entity.
|
||||
func (at *AuthTokens) QueryUser() *UserQuery {
|
||||
return NewAuthTokensClient(at.config).QueryUser(at)
|
||||
}
|
||||
|
||||
// QueryRoles queries the "roles" edge of the AuthTokens entity.
|
||||
func (at *AuthTokens) QueryRoles() *AuthRolesQuery {
|
||||
return NewAuthTokensClient(at.config).QueryRoles(at)
|
||||
return (&AuthTokensClient{config: at.config}).QueryUser(at)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this AuthTokens.
|
||||
// Note that you need to call AuthTokens.Unwrap() before calling this method if this AuthTokens
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (at *AuthTokens) Update() *AuthTokensUpdateOne {
|
||||
return NewAuthTokensClient(at.config).UpdateOne(at)
|
||||
return (&AuthTokensClient{config: at.config}).UpdateOne(at)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the AuthTokens entity that was returned from a transaction after it was closed,
|
||||
@@ -23,8 +23,6 @@ const (
|
||||
FieldExpiresAt = "expires_at"
|
||||
// EdgeUser holds the string denoting the user edge name in mutations.
|
||||
EdgeUser = "user"
|
||||
// EdgeRoles holds the string denoting the roles edge name in mutations.
|
||||
EdgeRoles = "roles"
|
||||
// Table holds the table name of the authtokens in the database.
|
||||
Table = "auth_tokens"
|
||||
// UserTable is the table that holds the user relation/edge.
|
||||
@@ -34,13 +32,6 @@ const (
|
||||
UserInverseTable = "users"
|
||||
// UserColumn is the table column denoting the user relation/edge.
|
||||
UserColumn = "user_auth_tokens"
|
||||
// RolesTable is the table that holds the roles relation/edge.
|
||||
RolesTable = "auth_roles"
|
||||
// RolesInverseTable is the table name for the AuthRoles entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "authroles" package.
|
||||
RolesInverseTable = "auth_roles"
|
||||
// RolesColumn is the table column denoting the roles relation/edge.
|
||||
RolesColumn = "auth_tokens_roles"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for authtokens fields.
|
||||
@@ -8,232 +8,362 @@ import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNEQ(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldIn(FieldID, ids...))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.In(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNotIn(FieldID, ids...))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.NotIn(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGT(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGTE(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLT(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLTE(FieldID, id))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
|
||||
func Token(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
|
||||
func ExpiresAt(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGT(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGTE(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLT(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLTE(FieldCreatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGT(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLT(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenEQ applies the EQ predicate on the "token" field.
|
||||
func TokenEQ(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenNEQ applies the NEQ predicate on the "token" field.
|
||||
func TokenNEQ(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNEQ(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenIn applies the In predicate on the "token" field.
|
||||
func TokenIn(vs ...[]byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldIn(FieldToken, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldToken), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenNotIn applies the NotIn predicate on the "token" field.
|
||||
func TokenNotIn(vs ...[]byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNotIn(FieldToken, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldToken), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenGT applies the GT predicate on the "token" field.
|
||||
func TokenGT(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGT(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenGTE applies the GTE predicate on the "token" field.
|
||||
func TokenGTE(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGTE(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenLT applies the LT predicate on the "token" field.
|
||||
func TokenLT(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLT(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenLTE applies the LTE predicate on the "token" field.
|
||||
func TokenLTE(v []byte) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLTE(FieldToken, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
|
||||
func ExpiresAtEQ(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldEQ(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
|
||||
func ExpiresAtNEQ(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNEQ(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtIn applies the In predicate on the "expires_at" field.
|
||||
func ExpiresAtIn(vs ...time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldIn(FieldExpiresAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldExpiresAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
|
||||
func ExpiresAtNotIn(vs ...time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldNotIn(FieldExpiresAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
|
||||
func ExpiresAtGT(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGT(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
|
||||
func ExpiresAtGTE(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldGTE(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
|
||||
func ExpiresAtLT(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLT(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
|
||||
func ExpiresAtLTE(v time.Time) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(sql.FieldLTE(FieldExpiresAt, v))
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// HasUser applies the HasEdge predicate on the "user" edge.
|
||||
@@ -241,6 +371,7 @@ func HasUser() predicate.AuthTokens {
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(UserTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -263,33 +394,6 @@ func HasUserWith(preds ...predicate.User) predicate.AuthTokens {
|
||||
})
|
||||
}
|
||||
|
||||
// HasRoles applies the HasEdge predicate on the "roles" edge.
|
||||
func HasRoles() predicate.AuthTokens {
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, RolesTable, RolesColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasRolesWith applies the HasEdge predicate on the "roles" edge with a given conditions (other predicates).
|
||||
func HasRolesWith(preds ...predicate.AuthRoles) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(RolesInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, RolesTable, RolesColumn),
|
||||
)
|
||||
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.AuthTokens) predicate.AuthTokens {
|
||||
return predicate.AuthTokens(func(s *sql.Selector) {
|
||||
@@ -11,9 +11,8 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authroles"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// AuthTokensCreate is the builder for creating a AuthTokens entity.
|
||||
@@ -104,25 +103,6 @@ func (atc *AuthTokensCreate) SetUser(u *User) *AuthTokensCreate {
|
||||
return atc.SetUserID(u.ID)
|
||||
}
|
||||
|
||||
// SetRolesID sets the "roles" edge to the AuthRoles entity by ID.
|
||||
func (atc *AuthTokensCreate) SetRolesID(id int) *AuthTokensCreate {
|
||||
atc.mutation.SetRolesID(id)
|
||||
return atc
|
||||
}
|
||||
|
||||
// SetNillableRolesID sets the "roles" edge to the AuthRoles entity by ID if the given value is not nil.
|
||||
func (atc *AuthTokensCreate) SetNillableRolesID(id *int) *AuthTokensCreate {
|
||||
if id != nil {
|
||||
atc = atc.SetRolesID(*id)
|
||||
}
|
||||
return atc
|
||||
}
|
||||
|
||||
// SetRoles sets the "roles" edge to the AuthRoles entity.
|
||||
func (atc *AuthTokensCreate) SetRoles(a *AuthRoles) *AuthTokensCreate {
|
||||
return atc.SetRolesID(a.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthTokensMutation object of the builder.
|
||||
func (atc *AuthTokensCreate) Mutation() *AuthTokensMutation {
|
||||
return atc.mutation
|
||||
@@ -130,8 +110,50 @@ func (atc *AuthTokensCreate) Mutation() *AuthTokensMutation {
|
||||
|
||||
// Save creates the AuthTokens in the database.
|
||||
func (atc *AuthTokensCreate) Save(ctx context.Context) (*AuthTokens, error) {
|
||||
var (
|
||||
err error
|
||||
node *AuthTokens
|
||||
)
|
||||
atc.defaults()
|
||||
return withHooks[*AuthTokens, AuthTokensMutation](ctx, atc.sqlSave, atc.mutation, atc.hooks)
|
||||
if len(atc.hooks) == 0 {
|
||||
if err = atc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = atc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AuthTokensMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = atc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atc.mutation = mutation
|
||||
if node, err = atc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(atc.hooks) - 1; i >= 0; i-- {
|
||||
if atc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = atc.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, atc.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*AuthTokens)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from AuthTokensMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
@@ -194,9 +216,6 @@ func (atc *AuthTokensCreate) check() error {
|
||||
}
|
||||
|
||||
func (atc *AuthTokensCreate) sqlSave(ctx context.Context) (*AuthTokens, error) {
|
||||
if err := atc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := atc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, atc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
@@ -211,8 +230,6 @@ func (atc *AuthTokensCreate) sqlSave(ctx context.Context) (*AuthTokens, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
atc.mutation.id = &_node.ID
|
||||
atc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
@@ -232,19 +249,35 @@ func (atc *AuthTokensCreate) createSpec() (*AuthTokens, *sqlgraph.CreateSpec) {
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := atc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(authtokens.FieldCreatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := atc.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(authtokens.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := atc.mutation.Token(); ok {
|
||||
_spec.SetField(authtokens.FieldToken, field.TypeBytes, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: authtokens.FieldToken,
|
||||
})
|
||||
_node.Token = value
|
||||
}
|
||||
if value, ok := atc.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(authtokens.FieldExpiresAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldExpiresAt,
|
||||
})
|
||||
_node.ExpiresAt = value
|
||||
}
|
||||
if nodes := atc.mutation.UserIDs(); len(nodes) > 0 {
|
||||
@@ -267,25 +300,6 @@ func (atc *AuthTokensCreate) createSpec() (*AuthTokens, *sqlgraph.CreateSpec) {
|
||||
_node.user_auth_tokens = &nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := atc.mutation.RolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: authtokens.RolesTable,
|
||||
Columns: []string{authtokens.RolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: authroles.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
@@ -4,12 +4,13 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// AuthTokensDelete is the builder for deleting a AuthTokens entity.
|
||||
@@ -27,7 +28,34 @@ func (atd *AuthTokensDelete) Where(ps ...predicate.AuthTokens) *AuthTokensDelete
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (atd *AuthTokensDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks[int, AuthTokensMutation](ctx, atd.sqlExec, atd.mutation, atd.hooks)
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
if len(atd.hooks) == 0 {
|
||||
affected, err = atd.sqlExec(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AuthTokensMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
atd.mutation = mutation
|
||||
affected, err = atd.sqlExec(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(atd.hooks) - 1; i >= 0; i-- {
|
||||
if atd.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = atd.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, atd.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
@@ -60,7 +88,6 @@ func (atd *AuthTokensDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
atd.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
@@ -69,12 +96,6 @@ type AuthTokensDeleteOne struct {
|
||||
atd *AuthTokensDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthTokensDelete builder.
|
||||
func (atdo *AuthTokensDeleteOne) Where(ps ...predicate.AuthTokens) *AuthTokensDeleteOne {
|
||||
atdo.atd.mutation.Where(ps...)
|
||||
return atdo
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (atdo *AuthTokensDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := atdo.atd.Exec(ctx)
|
||||
@@ -90,7 +111,5 @@ func (atdo *AuthTokensDeleteOne) Exec(ctx context.Context) error {
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (atdo *AuthTokensDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := atdo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
atdo.atd.ExecX(ctx)
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
@@ -12,21 +11,21 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authroles"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// AuthTokensQuery is the builder for querying AuthTokens entities.
|
||||
type AuthTokensQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
limit *int
|
||||
offset *int
|
||||
unique *bool
|
||||
order []OrderFunc
|
||||
inters []Interceptor
|
||||
fields []string
|
||||
predicates []predicate.AuthTokens
|
||||
withUser *UserQuery
|
||||
withRoles *AuthRolesQuery
|
||||
withFKs bool
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
@@ -39,26 +38,26 @@ func (atq *AuthTokensQuery) Where(ps ...predicate.AuthTokens) *AuthTokensQuery {
|
||||
return atq
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
// Limit adds a limit step to the query.
|
||||
func (atq *AuthTokensQuery) Limit(limit int) *AuthTokensQuery {
|
||||
atq.ctx.Limit = &limit
|
||||
atq.limit = &limit
|
||||
return atq
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
// Offset adds an offset step to the query.
|
||||
func (atq *AuthTokensQuery) Offset(offset int) *AuthTokensQuery {
|
||||
atq.ctx.Offset = &offset
|
||||
atq.offset = &offset
|
||||
return atq
|
||||
}
|
||||
|
||||
// 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 (atq *AuthTokensQuery) Unique(unique bool) *AuthTokensQuery {
|
||||
atq.ctx.Unique = &unique
|
||||
atq.unique = &unique
|
||||
return atq
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
// Order adds an order step to the query.
|
||||
func (atq *AuthTokensQuery) Order(o ...OrderFunc) *AuthTokensQuery {
|
||||
atq.order = append(atq.order, o...)
|
||||
return atq
|
||||
@@ -66,7 +65,7 @@ func (atq *AuthTokensQuery) Order(o ...OrderFunc) *AuthTokensQuery {
|
||||
|
||||
// QueryUser chains the current query on the "user" edge.
|
||||
func (atq *AuthTokensQuery) QueryUser() *UserQuery {
|
||||
query := (&UserClient{config: atq.config}).Query()
|
||||
query := &UserQuery{config: atq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := atq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -86,32 +85,10 @@ func (atq *AuthTokensQuery) QueryUser() *UserQuery {
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryRoles chains the current query on the "roles" edge.
|
||||
func (atq *AuthTokensQuery) QueryRoles() *AuthRolesQuery {
|
||||
query := (&AuthRolesClient{config: atq.config}).Query()
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := atq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selector := atq.sqlQuery(ctx)
|
||||
if err := selector.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(authtokens.Table, authtokens.FieldID, selector),
|
||||
sqlgraph.To(authroles.Table, authroles.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2O, false, authtokens.RolesTable, authtokens.RolesColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(atq.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first AuthTokens entity from the query.
|
||||
// Returns a *NotFoundError when no AuthTokens was found.
|
||||
func (atq *AuthTokensQuery) First(ctx context.Context) (*AuthTokens, error) {
|
||||
nodes, err := atq.Limit(1).All(setContextOp(ctx, atq.ctx, "First"))
|
||||
nodes, err := atq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -134,7 +111,7 @@ func (atq *AuthTokensQuery) FirstX(ctx context.Context) *AuthTokens {
|
||||
// Returns a *NotFoundError when no AuthTokens ID was found.
|
||||
func (atq *AuthTokensQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = atq.Limit(1).IDs(setContextOp(ctx, atq.ctx, "FirstID")); err != nil {
|
||||
if ids, err = atq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
@@ -157,7 +134,7 @@ func (atq *AuthTokensQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
// Returns a *NotSingularError when more than one AuthTokens entity is found.
|
||||
// Returns a *NotFoundError when no AuthTokens entities are found.
|
||||
func (atq *AuthTokensQuery) Only(ctx context.Context) (*AuthTokens, error) {
|
||||
nodes, err := atq.Limit(2).All(setContextOp(ctx, atq.ctx, "Only"))
|
||||
nodes, err := atq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -185,7 +162,7 @@ func (atq *AuthTokensQuery) OnlyX(ctx context.Context) *AuthTokens {
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (atq *AuthTokensQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = atq.Limit(2).IDs(setContextOp(ctx, atq.ctx, "OnlyID")); err != nil {
|
||||
if ids, err = atq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
@@ -210,12 +187,10 @@ func (atq *AuthTokensQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
|
||||
// All executes the query and returns a list of AuthTokensSlice.
|
||||
func (atq *AuthTokensQuery) All(ctx context.Context) ([]*AuthTokens, error) {
|
||||
ctx = setContextOp(ctx, atq.ctx, "All")
|
||||
if err := atq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*AuthTokens, *AuthTokensQuery]()
|
||||
return withInterceptors[[]*AuthTokens](ctx, atq, qr, atq.inters)
|
||||
return atq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
@@ -230,7 +205,6 @@ func (atq *AuthTokensQuery) AllX(ctx context.Context) []*AuthTokens {
|
||||
// IDs executes the query and returns a list of AuthTokens IDs.
|
||||
func (atq *AuthTokensQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
var ids []uuid.UUID
|
||||
ctx = setContextOp(ctx, atq.ctx, "IDs")
|
||||
if err := atq.Select(authtokens.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -248,11 +222,10 @@ func (atq *AuthTokensQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (atq *AuthTokensQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, atq.ctx, "Count")
|
||||
if err := atq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, atq, querierCount[*AuthTokensQuery](), atq.inters)
|
||||
return atq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
@@ -266,15 +239,10 @@ func (atq *AuthTokensQuery) CountX(ctx context.Context) int {
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (atq *AuthTokensQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, atq.ctx, "Exist")
|
||||
switch _, err := atq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
if err := atq.prepareQuery(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return atq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
@@ -294,22 +262,22 @@ func (atq *AuthTokensQuery) Clone() *AuthTokensQuery {
|
||||
}
|
||||
return &AuthTokensQuery{
|
||||
config: atq.config,
|
||||
ctx: atq.ctx.Clone(),
|
||||
limit: atq.limit,
|
||||
offset: atq.offset,
|
||||
order: append([]OrderFunc{}, atq.order...),
|
||||
inters: append([]Interceptor{}, atq.inters...),
|
||||
predicates: append([]predicate.AuthTokens{}, atq.predicates...),
|
||||
withUser: atq.withUser.Clone(),
|
||||
withRoles: atq.withRoles.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: atq.sql.Clone(),
|
||||
path: atq.path,
|
||||
sql: atq.sql.Clone(),
|
||||
path: atq.path,
|
||||
unique: atq.unique,
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (atq *AuthTokensQuery) WithUser(opts ...func(*UserQuery)) *AuthTokensQuery {
|
||||
query := (&UserClient{config: atq.config}).Query()
|
||||
query := &UserQuery{config: atq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -317,17 +285,6 @@ func (atq *AuthTokensQuery) WithUser(opts ...func(*UserQuery)) *AuthTokensQuery
|
||||
return atq
|
||||
}
|
||||
|
||||
// WithRoles tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "roles" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (atq *AuthTokensQuery) WithRoles(opts ...func(*AuthRolesQuery)) *AuthTokensQuery {
|
||||
query := (&AuthRolesClient{config: atq.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
atq.withRoles = query
|
||||
return atq
|
||||
}
|
||||
|
||||
// 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.
|
||||
//
|
||||
@@ -343,11 +300,16 @@ func (atq *AuthTokensQuery) WithRoles(opts ...func(*AuthRolesQuery)) *AuthTokens
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (atq *AuthTokensQuery) GroupBy(field string, fields ...string) *AuthTokensGroupBy {
|
||||
atq.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &AuthTokensGroupBy{build: atq}
|
||||
grbuild.flds = &atq.ctx.Fields
|
||||
grbuild := &AuthTokensGroupBy{config: atq.config}
|
||||
grbuild.fields = append([]string{field}, fields...)
|
||||
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
|
||||
if err := atq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return atq.sqlQuery(ctx), nil
|
||||
}
|
||||
grbuild.label = authtokens.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
@@ -364,30 +326,15 @@ func (atq *AuthTokensQuery) GroupBy(field string, fields ...string) *AuthTokensG
|
||||
// Select(authtokens.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (atq *AuthTokensQuery) Select(fields ...string) *AuthTokensSelect {
|
||||
atq.ctx.Fields = append(atq.ctx.Fields, fields...)
|
||||
sbuild := &AuthTokensSelect{AuthTokensQuery: atq}
|
||||
sbuild.label = authtokens.Label
|
||||
sbuild.flds, sbuild.scan = &atq.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a AuthTokensSelect configured with the given aggregations.
|
||||
func (atq *AuthTokensQuery) Aggregate(fns ...AggregateFunc) *AuthTokensSelect {
|
||||
return atq.Select().Aggregate(fns...)
|
||||
atq.fields = append(atq.fields, fields...)
|
||||
selbuild := &AuthTokensSelect{AuthTokensQuery: atq}
|
||||
selbuild.label = authtokens.Label
|
||||
selbuild.flds, selbuild.scan = &atq.fields, selbuild.Scan
|
||||
return selbuild
|
||||
}
|
||||
|
||||
func (atq *AuthTokensQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range atq.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, atq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range atq.ctx.Fields {
|
||||
for _, f := range atq.fields {
|
||||
if !authtokens.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
@@ -407,9 +354,8 @@ func (atq *AuthTokensQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*
|
||||
nodes = []*AuthTokens{}
|
||||
withFKs = atq.withFKs
|
||||
_spec = atq.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
loadedTypes = [1]bool{
|
||||
atq.withUser != nil,
|
||||
atq.withRoles != nil,
|
||||
}
|
||||
)
|
||||
if atq.withUser != nil {
|
||||
@@ -442,12 +388,6 @@ func (atq *AuthTokensQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := atq.withRoles; query != nil {
|
||||
if err := atq.loadRoles(ctx, query, nodes, nil,
|
||||
func(n *AuthTokens, e *AuthRoles) { n.Edges.Roles = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
@@ -464,9 +404,6 @@ func (atq *AuthTokensQuery) loadUser(ctx context.Context, query *UserQuery, node
|
||||
}
|
||||
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 {
|
||||
@@ -483,44 +420,27 @@ func (atq *AuthTokensQuery) loadUser(ctx context.Context, query *UserQuery, node
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (atq *AuthTokensQuery) loadRoles(ctx context.Context, query *AuthRolesQuery, nodes []*AuthTokens, init func(*AuthTokens), assign func(*AuthTokens, *AuthRoles)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID]*AuthTokens)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
}
|
||||
query.withFKs = true
|
||||
query.Where(predicate.AuthRoles(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(authtokens.RolesColumn, fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.auth_tokens_roles
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "auth_tokens_roles" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected foreign-key "auth_tokens_roles" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (atq *AuthTokensQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := atq.querySpec()
|
||||
_spec.Node.Columns = atq.ctx.Fields
|
||||
if len(atq.ctx.Fields) > 0 {
|
||||
_spec.Unique = atq.ctx.Unique != nil && *atq.ctx.Unique
|
||||
_spec.Node.Columns = atq.fields
|
||||
if len(atq.fields) > 0 {
|
||||
_spec.Unique = atq.unique != nil && *atq.unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, atq.driver, _spec)
|
||||
}
|
||||
|
||||
func (atq *AuthTokensQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
switch _, err := atq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (atq *AuthTokensQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := &sqlgraph.QuerySpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
@@ -534,10 +454,10 @@ func (atq *AuthTokensQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
From: atq.sql,
|
||||
Unique: true,
|
||||
}
|
||||
if unique := atq.ctx.Unique; unique != nil {
|
||||
if unique := atq.unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
}
|
||||
if fields := atq.ctx.Fields; len(fields) > 0 {
|
||||
if fields := atq.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, authtokens.FieldID)
|
||||
for i := range fields {
|
||||
@@ -553,10 +473,10 @@ func (atq *AuthTokensQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := atq.ctx.Limit; limit != nil {
|
||||
if limit := atq.limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := atq.ctx.Offset; offset != nil {
|
||||
if offset := atq.offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := atq.order; len(ps) > 0 {
|
||||
@@ -572,7 +492,7 @@ func (atq *AuthTokensQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
func (atq *AuthTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(atq.driver.Dialect())
|
||||
t1 := builder.Table(authtokens.Table)
|
||||
columns := atq.ctx.Fields
|
||||
columns := atq.fields
|
||||
if len(columns) == 0 {
|
||||
columns = authtokens.Columns
|
||||
}
|
||||
@@ -581,7 +501,7 @@ func (atq *AuthTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
selector = atq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if atq.ctx.Unique != nil && *atq.ctx.Unique {
|
||||
if atq.unique != nil && *atq.unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range atq.predicates {
|
||||
@@ -590,12 +510,12 @@ func (atq *AuthTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
for _, p := range atq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := atq.ctx.Offset; offset != nil {
|
||||
if offset := atq.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 := atq.ctx.Limit; limit != nil {
|
||||
if limit := atq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
@@ -603,8 +523,13 @@ func (atq *AuthTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
|
||||
// AuthTokensGroupBy is the group-by builder for AuthTokens entities.
|
||||
type AuthTokensGroupBy struct {
|
||||
config
|
||||
selector
|
||||
build *AuthTokensQuery
|
||||
fields []string
|
||||
fns []AggregateFunc
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
@@ -613,77 +538,74 @@ func (atgb *AuthTokensGroupBy) Aggregate(fns ...AggregateFunc) *AuthTokensGroupB
|
||||
return atgb
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
// Scan applies the group-by query and scans the result into the given value.
|
||||
func (atgb *AuthTokensGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, atgb.build.ctx, "GroupBy")
|
||||
if err := atgb.build.prepareQuery(ctx); err != nil {
|
||||
query, err := atgb.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*AuthTokensQuery, *AuthTokensGroupBy](ctx, atgb.build, atgb, atgb.build.inters, v)
|
||||
atgb.sql = query
|
||||
return atgb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (atgb *AuthTokensGroupBy) sqlScan(ctx context.Context, root *AuthTokensQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(atgb.fns))
|
||||
for _, fn := range atgb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*atgb.flds)+len(atgb.fns))
|
||||
for _, f := range *atgb.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
func (atgb *AuthTokensGroupBy) sqlScan(ctx context.Context, v any) error {
|
||||
for _, f := range atgb.fields {
|
||||
if !authtokens.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*atgb.flds...)...)
|
||||
selector := atgb.sqlQuery()
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := atgb.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
if err := atgb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (atgb *AuthTokensGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := atgb.sql.Select()
|
||||
aggregation := make([]string, 0, len(atgb.fns))
|
||||
for _, fn := range atgb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
// If no columns were selected in a custom aggregation function, the default
|
||||
// selection is the fields used for "group-by", and the aggregation functions.
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(atgb.fields)+len(atgb.fns))
|
||||
for _, f := range atgb.fields {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
return selector.GroupBy(selector.Columns(atgb.fields...)...)
|
||||
}
|
||||
|
||||
// AuthTokensSelect is the builder for selecting fields of AuthTokens entities.
|
||||
type AuthTokensSelect struct {
|
||||
*AuthTokensQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (ats *AuthTokensSelect) Aggregate(fns ...AggregateFunc) *AuthTokensSelect {
|
||||
ats.fns = append(ats.fns, fns...)
|
||||
return ats
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (ats *AuthTokensSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, ats.ctx, "Select")
|
||||
if err := ats.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*AuthTokensQuery, *AuthTokensSelect](ctx, ats.AuthTokensQuery, ats, ats.inters, v)
|
||||
ats.sql = ats.AuthTokensQuery.sqlQuery(ctx)
|
||||
return ats.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (ats *AuthTokensSelect) sqlScan(ctx context.Context, root *AuthTokensQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(ats.fns))
|
||||
for _, fn := range ats.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*ats.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
func (ats *AuthTokensSelect) sqlScan(ctx context.Context, v any) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
query, args := ats.sql.Query()
|
||||
if err := ats.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -12,10 +12,9 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authroles"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// AuthTokensUpdate is the builder for updating AuthTokens entities.
|
||||
@@ -76,25 +75,6 @@ func (atu *AuthTokensUpdate) SetUser(u *User) *AuthTokensUpdate {
|
||||
return atu.SetUserID(u.ID)
|
||||
}
|
||||
|
||||
// SetRolesID sets the "roles" edge to the AuthRoles entity by ID.
|
||||
func (atu *AuthTokensUpdate) SetRolesID(id int) *AuthTokensUpdate {
|
||||
atu.mutation.SetRolesID(id)
|
||||
return atu
|
||||
}
|
||||
|
||||
// SetNillableRolesID sets the "roles" edge to the AuthRoles entity by ID if the given value is not nil.
|
||||
func (atu *AuthTokensUpdate) SetNillableRolesID(id *int) *AuthTokensUpdate {
|
||||
if id != nil {
|
||||
atu = atu.SetRolesID(*id)
|
||||
}
|
||||
return atu
|
||||
}
|
||||
|
||||
// SetRoles sets the "roles" edge to the AuthRoles entity.
|
||||
func (atu *AuthTokensUpdate) SetRoles(a *AuthRoles) *AuthTokensUpdate {
|
||||
return atu.SetRolesID(a.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthTokensMutation object of the builder.
|
||||
func (atu *AuthTokensUpdate) Mutation() *AuthTokensMutation {
|
||||
return atu.mutation
|
||||
@@ -106,16 +86,37 @@ func (atu *AuthTokensUpdate) ClearUser() *AuthTokensUpdate {
|
||||
return atu
|
||||
}
|
||||
|
||||
// ClearRoles clears the "roles" edge to the AuthRoles entity.
|
||||
func (atu *AuthTokensUpdate) ClearRoles() *AuthTokensUpdate {
|
||||
atu.mutation.ClearRoles()
|
||||
return atu
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (atu *AuthTokensUpdate) Save(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
atu.defaults()
|
||||
return withHooks[int, AuthTokensMutation](ctx, atu.sqlSave, atu.mutation, atu.hooks)
|
||||
if len(atu.hooks) == 0 {
|
||||
affected, err = atu.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AuthTokensMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
atu.mutation = mutation
|
||||
affected, err = atu.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(atu.hooks) - 1; i >= 0; i-- {
|
||||
if atu.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = atu.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, atu.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -167,13 +168,25 @@ func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
}
|
||||
if value, ok := atu.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(authtokens.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := atu.mutation.Token(); ok {
|
||||
_spec.SetField(authtokens.FieldToken, field.TypeBytes, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: authtokens.FieldToken,
|
||||
})
|
||||
}
|
||||
if value, ok := atu.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(authtokens.FieldExpiresAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldExpiresAt,
|
||||
})
|
||||
}
|
||||
if atu.mutation.UserCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -210,41 +223,6 @@ func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if atu.mutation.RolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: authtokens.RolesTable,
|
||||
Columns: []string{authtokens.RolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: authroles.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := atu.mutation.RolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: authtokens.RolesTable,
|
||||
Columns: []string{authtokens.RolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: authroles.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if n, err = sqlgraph.UpdateNodes(ctx, atu.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{authtokens.Label}
|
||||
@@ -253,7 +231,6 @@ func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
atu.mutation.done = true
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@@ -310,25 +287,6 @@ func (atuo *AuthTokensUpdateOne) SetUser(u *User) *AuthTokensUpdateOne {
|
||||
return atuo.SetUserID(u.ID)
|
||||
}
|
||||
|
||||
// SetRolesID sets the "roles" edge to the AuthRoles entity by ID.
|
||||
func (atuo *AuthTokensUpdateOne) SetRolesID(id int) *AuthTokensUpdateOne {
|
||||
atuo.mutation.SetRolesID(id)
|
||||
return atuo
|
||||
}
|
||||
|
||||
// SetNillableRolesID sets the "roles" edge to the AuthRoles entity by ID if the given value is not nil.
|
||||
func (atuo *AuthTokensUpdateOne) SetNillableRolesID(id *int) *AuthTokensUpdateOne {
|
||||
if id != nil {
|
||||
atuo = atuo.SetRolesID(*id)
|
||||
}
|
||||
return atuo
|
||||
}
|
||||
|
||||
// SetRoles sets the "roles" edge to the AuthRoles entity.
|
||||
func (atuo *AuthTokensUpdateOne) SetRoles(a *AuthRoles) *AuthTokensUpdateOne {
|
||||
return atuo.SetRolesID(a.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthTokensMutation object of the builder.
|
||||
func (atuo *AuthTokensUpdateOne) Mutation() *AuthTokensMutation {
|
||||
return atuo.mutation
|
||||
@@ -340,12 +298,6 @@ func (atuo *AuthTokensUpdateOne) ClearUser() *AuthTokensUpdateOne {
|
||||
return atuo
|
||||
}
|
||||
|
||||
// ClearRoles clears the "roles" edge to the AuthRoles entity.
|
||||
func (atuo *AuthTokensUpdateOne) ClearRoles() *AuthTokensUpdateOne {
|
||||
atuo.mutation.ClearRoles()
|
||||
return atuo
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (atuo *AuthTokensUpdateOne) Select(field string, fields ...string) *AuthTokensUpdateOne {
|
||||
@@ -355,8 +307,41 @@ func (atuo *AuthTokensUpdateOne) Select(field string, fields ...string) *AuthTok
|
||||
|
||||
// Save executes the query and returns the updated AuthTokens entity.
|
||||
func (atuo *AuthTokensUpdateOne) Save(ctx context.Context) (*AuthTokens, error) {
|
||||
var (
|
||||
err error
|
||||
node *AuthTokens
|
||||
)
|
||||
atuo.defaults()
|
||||
return withHooks[*AuthTokens, AuthTokensMutation](ctx, atuo.sqlSave, atuo.mutation, atuo.hooks)
|
||||
if len(atuo.hooks) == 0 {
|
||||
node, err = atuo.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AuthTokensMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
atuo.mutation = mutation
|
||||
node, err = atuo.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(atuo.hooks) - 1; i >= 0; i-- {
|
||||
if atuo.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = atuo.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, atuo.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*AuthTokens)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from AuthTokensMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -425,13 +410,25 @@ func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens
|
||||
}
|
||||
}
|
||||
if value, ok := atuo.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(authtokens.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := atuo.mutation.Token(); ok {
|
||||
_spec.SetField(authtokens.FieldToken, field.TypeBytes, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: authtokens.FieldToken,
|
||||
})
|
||||
}
|
||||
if value, ok := atuo.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(authtokens.FieldExpiresAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: authtokens.FieldExpiresAt,
|
||||
})
|
||||
}
|
||||
if atuo.mutation.UserCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -468,41 +465,6 @@ func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if atuo.mutation.RolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: authtokens.RolesTable,
|
||||
Columns: []string{authtokens.RolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: authroles.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := atuo.mutation.RolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2O,
|
||||
Inverse: false,
|
||||
Table: authtokens.RolesTable,
|
||||
Columns: []string{authtokens.RolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Column: authroles.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &AuthTokens{config: atuo.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
@@ -514,6 +476,5 @@ func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
atuo.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,41 +20,22 @@ type config struct {
|
||||
log func(...any)
|
||||
// hooks to execute on mutations.
|
||||
hooks *hooks
|
||||
// interceptors to execute on queries.
|
||||
inters *inters
|
||||
}
|
||||
|
||||
// hooks and interceptors per client, for fast access.
|
||||
type (
|
||||
hooks struct {
|
||||
Attachment []ent.Hook
|
||||
AuthRoles []ent.Hook
|
||||
AuthTokens []ent.Hook
|
||||
Document []ent.Hook
|
||||
Group []ent.Hook
|
||||
GroupInvitationToken []ent.Hook
|
||||
Item []ent.Hook
|
||||
ItemField []ent.Hook
|
||||
Label []ent.Hook
|
||||
Location []ent.Hook
|
||||
MaintenanceEntry []ent.Hook
|
||||
User []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
Attachment []ent.Interceptor
|
||||
AuthRoles []ent.Interceptor
|
||||
AuthTokens []ent.Interceptor
|
||||
Document []ent.Interceptor
|
||||
Group []ent.Interceptor
|
||||
GroupInvitationToken []ent.Interceptor
|
||||
Item []ent.Interceptor
|
||||
ItemField []ent.Interceptor
|
||||
Label []ent.Interceptor
|
||||
Location []ent.Interceptor
|
||||
MaintenanceEntry []ent.Interceptor
|
||||
User []ent.Interceptor
|
||||
}
|
||||
)
|
||||
// hooks per client, for fast access.
|
||||
type hooks struct {
|
||||
Attachment []ent.Hook
|
||||
AuthTokens []ent.Hook
|
||||
Document []ent.Hook
|
||||
DocumentToken []ent.Hook
|
||||
Group []ent.Hook
|
||||
GroupInvitationToken []ent.Hook
|
||||
Item []ent.Hook
|
||||
ItemField []ent.Hook
|
||||
Label []ent.Hook
|
||||
Location []ent.Hook
|
||||
User []ent.Hook
|
||||
}
|
||||
|
||||
// Options applies the options on the config object.
|
||||
func (c *config) options(opts ...Option) {
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
)
|
||||
|
||||
// Document is the model entity for the Document schema.
|
||||
@@ -36,11 +36,13 @@ type Document struct {
|
||||
type DocumentEdges struct {
|
||||
// Group holds the value of the group edge.
|
||||
Group *Group `json:"group,omitempty"`
|
||||
// DocumentTokens holds the value of the document_tokens edge.
|
||||
DocumentTokens []*DocumentToken `json:"document_tokens,omitempty"`
|
||||
// Attachments holds the value of the attachments edge.
|
||||
Attachments []*Attachment `json:"attachments,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]bool
|
||||
loadedTypes [3]bool
|
||||
}
|
||||
|
||||
// GroupOrErr returns the Group value or an error if the edge
|
||||
@@ -56,10 +58,19 @@ func (e DocumentEdges) GroupOrErr() (*Group, error) {
|
||||
return nil, &NotLoadedError{edge: "group"}
|
||||
}
|
||||
|
||||
// DocumentTokensOrErr returns the DocumentTokens value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e DocumentEdges) DocumentTokensOrErr() ([]*DocumentToken, error) {
|
||||
if e.loadedTypes[1] {
|
||||
return e.DocumentTokens, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "document_tokens"}
|
||||
}
|
||||
|
||||
// AttachmentsOrErr returns the Attachments value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e DocumentEdges) AttachmentsOrErr() ([]*Attachment, error) {
|
||||
if e.loadedTypes[1] {
|
||||
if e.loadedTypes[2] {
|
||||
return e.Attachments, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "attachments"}
|
||||
@@ -137,19 +148,24 @@ func (d *Document) assignValues(columns []string, values []any) error {
|
||||
|
||||
// QueryGroup queries the "group" edge of the Document entity.
|
||||
func (d *Document) QueryGroup() *GroupQuery {
|
||||
return NewDocumentClient(d.config).QueryGroup(d)
|
||||
return (&DocumentClient{config: d.config}).QueryGroup(d)
|
||||
}
|
||||
|
||||
// QueryDocumentTokens queries the "document_tokens" edge of the Document entity.
|
||||
func (d *Document) QueryDocumentTokens() *DocumentTokenQuery {
|
||||
return (&DocumentClient{config: d.config}).QueryDocumentTokens(d)
|
||||
}
|
||||
|
||||
// QueryAttachments queries the "attachments" edge of the Document entity.
|
||||
func (d *Document) QueryAttachments() *AttachmentQuery {
|
||||
return NewDocumentClient(d.config).QueryAttachments(d)
|
||||
return (&DocumentClient{config: d.config}).QueryAttachments(d)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Document.
|
||||
// Note that you need to call Document.Unwrap() before calling this method if this Document
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (d *Document) Update() *DocumentUpdateOne {
|
||||
return NewDocumentClient(d.config).UpdateOne(d)
|
||||
return (&DocumentClient{config: d.config}).UpdateOne(d)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Document entity that was returned from a transaction after it was closed,
|
||||
@@ -23,6 +23,8 @@ const (
|
||||
FieldPath = "path"
|
||||
// EdgeGroup holds the string denoting the group edge name in mutations.
|
||||
EdgeGroup = "group"
|
||||
// EdgeDocumentTokens holds the string denoting the document_tokens edge name in mutations.
|
||||
EdgeDocumentTokens = "document_tokens"
|
||||
// EdgeAttachments holds the string denoting the attachments edge name in mutations.
|
||||
EdgeAttachments = "attachments"
|
||||
// Table holds the table name of the document in the database.
|
||||
@@ -34,6 +36,13 @@ const (
|
||||
GroupInverseTable = "groups"
|
||||
// GroupColumn is the table column denoting the group relation/edge.
|
||||
GroupColumn = "group_documents"
|
||||
// DocumentTokensTable is the table that holds the document_tokens relation/edge.
|
||||
DocumentTokensTable = "document_tokens"
|
||||
// DocumentTokensInverseTable is the table name for the DocumentToken entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "documenttoken" package.
|
||||
DocumentTokensInverseTable = "document_tokens"
|
||||
// DocumentTokensColumn is the table column denoting the document_tokens relation/edge.
|
||||
DocumentTokensColumn = "document_document_tokens"
|
||||
// AttachmentsTable is the table that holds the attachments relation/edge.
|
||||
AttachmentsTable = "attachments"
|
||||
// AttachmentsInverseTable is the table name for the Attachment entity.
|
||||
@@ -8,282 +8,432 @@ import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldID, ids...))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.In(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldID, ids...))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.NotIn(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldID, id))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
|
||||
func Title(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Path applies equality check predicate on the "path" field. It's identical to PathEQ.
|
||||
func Path(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldCreatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleEQ applies the EQ predicate on the "title" field.
|
||||
func TitleEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleNEQ applies the NEQ predicate on the "title" field.
|
||||
func TitleNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleIn applies the In predicate on the "title" field.
|
||||
func TitleIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldTitle, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldTitle), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleNotIn applies the NotIn predicate on the "title" field.
|
||||
func TitleNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldTitle, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldTitle), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleGT applies the GT predicate on the "title" field.
|
||||
func TitleGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleGTE applies the GTE predicate on the "title" field.
|
||||
func TitleGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleLT applies the LT predicate on the "title" field.
|
||||
func TitleLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleLTE applies the LTE predicate on the "title" field.
|
||||
func TitleLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleContains applies the Contains predicate on the "title" field.
|
||||
func TitleContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.Contains(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
|
||||
func TitleHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.HasPrefix(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
|
||||
func TitleHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.HasSuffix(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleEqualFold applies the EqualFold predicate on the "title" field.
|
||||
func TitleEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EqualFold(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TitleContainsFold applies the ContainsFold predicate on the "title" field.
|
||||
func TitleContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldTitle, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.ContainsFold(s.C(FieldTitle), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathEQ applies the EQ predicate on the "path" field.
|
||||
func PathEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathNEQ applies the NEQ predicate on the "path" field.
|
||||
func PathNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathIn applies the In predicate on the "path" field.
|
||||
func PathIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldPath, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldPath), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// PathNotIn applies the NotIn predicate on the "path" field.
|
||||
func PathNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldPath, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldPath), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// PathGT applies the GT predicate on the "path" field.
|
||||
func PathGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathGTE applies the GTE predicate on the "path" field.
|
||||
func PathGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathLT applies the LT predicate on the "path" field.
|
||||
func PathLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathLTE applies the LTE predicate on the "path" field.
|
||||
func PathLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathContains applies the Contains predicate on the "path" field.
|
||||
func PathContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.Contains(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathHasPrefix applies the HasPrefix predicate on the "path" field.
|
||||
func PathHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.HasPrefix(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathHasSuffix applies the HasSuffix predicate on the "path" field.
|
||||
func PathHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.HasSuffix(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathEqualFold applies the EqualFold predicate on the "path" field.
|
||||
func PathEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.EqualFold(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// PathContainsFold applies the ContainsFold predicate on the "path" field.
|
||||
func PathContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldPath, v))
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
s.Where(sql.ContainsFold(s.C(FieldPath), v))
|
||||
})
|
||||
}
|
||||
|
||||
// HasGroup applies the HasEdge predicate on the "group" edge.
|
||||
@@ -291,6 +441,7 @@ func HasGroup() predicate.Document {
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(GroupTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -313,11 +464,40 @@ func HasGroupWith(preds ...predicate.Group) predicate.Document {
|
||||
})
|
||||
}
|
||||
|
||||
// HasDocumentTokens applies the HasEdge predicate on the "document_tokens" edge.
|
||||
func HasDocumentTokens() predicate.Document {
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DocumentTokensTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, DocumentTokensTable, DocumentTokensColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasDocumentTokensWith applies the HasEdge predicate on the "document_tokens" edge with a given conditions (other predicates).
|
||||
func HasDocumentTokensWith(preds ...predicate.DocumentToken) predicate.Document {
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DocumentTokensInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, DocumentTokensTable, DocumentTokensColumn),
|
||||
)
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasAttachments applies the HasEdge predicate on the "attachments" edge.
|
||||
func HasAttachments() predicate.Document {
|
||||
return predicate.Document(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(AttachmentsTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, AttachmentsTable, AttachmentsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -11,9 +11,10 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
)
|
||||
|
||||
// DocumentCreate is the builder for creating a Document entity.
|
||||
@@ -88,6 +89,21 @@ func (dc *DocumentCreate) SetGroup(g *Group) *DocumentCreate {
|
||||
return dc.SetGroupID(g.ID)
|
||||
}
|
||||
|
||||
// AddDocumentTokenIDs adds the "document_tokens" edge to the DocumentToken entity by IDs.
|
||||
func (dc *DocumentCreate) AddDocumentTokenIDs(ids ...uuid.UUID) *DocumentCreate {
|
||||
dc.mutation.AddDocumentTokenIDs(ids...)
|
||||
return dc
|
||||
}
|
||||
|
||||
// AddDocumentTokens adds the "document_tokens" edges to the DocumentToken entity.
|
||||
func (dc *DocumentCreate) AddDocumentTokens(d ...*DocumentToken) *DocumentCreate {
|
||||
ids := make([]uuid.UUID, len(d))
|
||||
for i := range d {
|
||||
ids[i] = d[i].ID
|
||||
}
|
||||
return dc.AddDocumentTokenIDs(ids...)
|
||||
}
|
||||
|
||||
// AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs.
|
||||
func (dc *DocumentCreate) AddAttachmentIDs(ids ...uuid.UUID) *DocumentCreate {
|
||||
dc.mutation.AddAttachmentIDs(ids...)
|
||||
@@ -110,8 +126,50 @@ func (dc *DocumentCreate) Mutation() *DocumentMutation {
|
||||
|
||||
// Save creates the Document in the database.
|
||||
func (dc *DocumentCreate) Save(ctx context.Context) (*Document, error) {
|
||||
var (
|
||||
err error
|
||||
node *Document
|
||||
)
|
||||
dc.defaults()
|
||||
return withHooks[*Document, DocumentMutation](ctx, dc.sqlSave, dc.mutation, dc.hooks)
|
||||
if len(dc.hooks) == 0 {
|
||||
if err = dc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = dc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = dc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dc.mutation = mutation
|
||||
if node, err = dc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(dc.hooks) - 1; i >= 0; i-- {
|
||||
if dc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = dc.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, dc.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Document)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from DocumentMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
@@ -183,9 +241,6 @@ func (dc *DocumentCreate) check() error {
|
||||
}
|
||||
|
||||
func (dc *DocumentCreate) sqlSave(ctx context.Context) (*Document, error) {
|
||||
if err := dc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := dc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, dc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
@@ -200,8 +255,6 @@ func (dc *DocumentCreate) sqlSave(ctx context.Context) (*Document, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
dc.mutation.id = &_node.ID
|
||||
dc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
@@ -221,19 +274,35 @@ func (dc *DocumentCreate) createSpec() (*Document, *sqlgraph.CreateSpec) {
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := dc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(document.FieldCreatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: document.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := dc.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(document.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: document.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := dc.mutation.Title(); ok {
|
||||
_spec.SetField(document.FieldTitle, field.TypeString, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: document.FieldTitle,
|
||||
})
|
||||
_node.Title = value
|
||||
}
|
||||
if value, ok := dc.mutation.Path(); ok {
|
||||
_spec.SetField(document.FieldPath, field.TypeString, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: document.FieldPath,
|
||||
})
|
||||
_node.Path = value
|
||||
}
|
||||
if nodes := dc.mutation.GroupIDs(); len(nodes) > 0 {
|
||||
@@ -256,6 +325,25 @@ func (dc *DocumentCreate) createSpec() (*Document, *sqlgraph.CreateSpec) {
|
||||
_node.group_documents = &nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := dc.mutation.DocumentTokensIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := dc.mutation.AttachmentsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -4,12 +4,13 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// DocumentDelete is the builder for deleting a Document entity.
|
||||
@@ -27,7 +28,34 @@ func (dd *DocumentDelete) Where(ps ...predicate.Document) *DocumentDelete {
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (dd *DocumentDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks[int, DocumentMutation](ctx, dd.sqlExec, dd.mutation, dd.hooks)
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
if len(dd.hooks) == 0 {
|
||||
affected, err = dd.sqlExec(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
dd.mutation = mutation
|
||||
affected, err = dd.sqlExec(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(dd.hooks) - 1; i >= 0; i-- {
|
||||
if dd.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = dd.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, dd.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
@@ -60,7 +88,6 @@ func (dd *DocumentDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
dd.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
@@ -69,12 +96,6 @@ type DocumentDeleteOne struct {
|
||||
dd *DocumentDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the DocumentDelete builder.
|
||||
func (ddo *DocumentDeleteOne) Where(ps ...predicate.Document) *DocumentDeleteOne {
|
||||
ddo.dd.mutation.Where(ps...)
|
||||
return ddo
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (ddo *DocumentDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := ddo.dd.Exec(ctx)
|
||||
@@ -90,7 +111,5 @@ func (ddo *DocumentDeleteOne) Exec(ctx context.Context) error {
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ddo *DocumentDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := ddo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ddo.dd.ExecX(ctx)
|
||||
}
|
||||
@@ -12,22 +12,26 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// DocumentQuery is the builder for querying Document entities.
|
||||
type DocumentQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []OrderFunc
|
||||
inters []Interceptor
|
||||
predicates []predicate.Document
|
||||
withGroup *GroupQuery
|
||||
withAttachments *AttachmentQuery
|
||||
withFKs bool
|
||||
limit *int
|
||||
offset *int
|
||||
unique *bool
|
||||
order []OrderFunc
|
||||
fields []string
|
||||
predicates []predicate.Document
|
||||
withGroup *GroupQuery
|
||||
withDocumentTokens *DocumentTokenQuery
|
||||
withAttachments *AttachmentQuery
|
||||
withFKs bool
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
@@ -39,26 +43,26 @@ func (dq *DocumentQuery) Where(ps ...predicate.Document) *DocumentQuery {
|
||||
return dq
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
// Limit adds a limit step to the query.
|
||||
func (dq *DocumentQuery) Limit(limit int) *DocumentQuery {
|
||||
dq.ctx.Limit = &limit
|
||||
dq.limit = &limit
|
||||
return dq
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
// Offset adds an offset step to the query.
|
||||
func (dq *DocumentQuery) Offset(offset int) *DocumentQuery {
|
||||
dq.ctx.Offset = &offset
|
||||
dq.offset = &offset
|
||||
return dq
|
||||
}
|
||||
|
||||
// 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 (dq *DocumentQuery) Unique(unique bool) *DocumentQuery {
|
||||
dq.ctx.Unique = &unique
|
||||
dq.unique = &unique
|
||||
return dq
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
// Order adds an order step to the query.
|
||||
func (dq *DocumentQuery) Order(o ...OrderFunc) *DocumentQuery {
|
||||
dq.order = append(dq.order, o...)
|
||||
return dq
|
||||
@@ -66,7 +70,7 @@ func (dq *DocumentQuery) Order(o ...OrderFunc) *DocumentQuery {
|
||||
|
||||
// QueryGroup chains the current query on the "group" edge.
|
||||
func (dq *DocumentQuery) QueryGroup() *GroupQuery {
|
||||
query := (&GroupClient{config: dq.config}).Query()
|
||||
query := &GroupQuery{config: dq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -86,9 +90,31 @@ func (dq *DocumentQuery) QueryGroup() *GroupQuery {
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryDocumentTokens chains the current query on the "document_tokens" edge.
|
||||
func (dq *DocumentQuery) QueryDocumentTokens() *DocumentTokenQuery {
|
||||
query := &DocumentTokenQuery{config: dq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selector := dq.sqlQuery(ctx)
|
||||
if err := selector.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(document.Table, document.FieldID, selector),
|
||||
sqlgraph.To(documenttoken.Table, documenttoken.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, document.DocumentTokensTable, document.DocumentTokensColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(dq.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryAttachments chains the current query on the "attachments" edge.
|
||||
func (dq *DocumentQuery) QueryAttachments() *AttachmentQuery {
|
||||
query := (&AttachmentClient{config: dq.config}).Query()
|
||||
query := &AttachmentQuery{config: dq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -111,7 +137,7 @@ func (dq *DocumentQuery) QueryAttachments() *AttachmentQuery {
|
||||
// First returns the first Document entity from the query.
|
||||
// Returns a *NotFoundError when no Document was found.
|
||||
func (dq *DocumentQuery) First(ctx context.Context) (*Document, error) {
|
||||
nodes, err := dq.Limit(1).All(setContextOp(ctx, dq.ctx, "First"))
|
||||
nodes, err := dq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -134,7 +160,7 @@ func (dq *DocumentQuery) FirstX(ctx context.Context) *Document {
|
||||
// Returns a *NotFoundError when no Document ID was found.
|
||||
func (dq *DocumentQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = dq.Limit(1).IDs(setContextOp(ctx, dq.ctx, "FirstID")); err != nil {
|
||||
if ids, err = dq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
@@ -157,7 +183,7 @@ func (dq *DocumentQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
// Returns a *NotSingularError when more than one Document entity is found.
|
||||
// Returns a *NotFoundError when no Document entities are found.
|
||||
func (dq *DocumentQuery) Only(ctx context.Context) (*Document, error) {
|
||||
nodes, err := dq.Limit(2).All(setContextOp(ctx, dq.ctx, "Only"))
|
||||
nodes, err := dq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -185,7 +211,7 @@ func (dq *DocumentQuery) OnlyX(ctx context.Context) *Document {
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (dq *DocumentQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = dq.Limit(2).IDs(setContextOp(ctx, dq.ctx, "OnlyID")); err != nil {
|
||||
if ids, err = dq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
@@ -210,12 +236,10 @@ func (dq *DocumentQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
|
||||
// All executes the query and returns a list of Documents.
|
||||
func (dq *DocumentQuery) All(ctx context.Context) ([]*Document, error) {
|
||||
ctx = setContextOp(ctx, dq.ctx, "All")
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Document, *DocumentQuery]()
|
||||
return withInterceptors[[]*Document](ctx, dq, qr, dq.inters)
|
||||
return dq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
@@ -230,7 +254,6 @@ func (dq *DocumentQuery) AllX(ctx context.Context) []*Document {
|
||||
// IDs executes the query and returns a list of Document IDs.
|
||||
func (dq *DocumentQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
var ids []uuid.UUID
|
||||
ctx = setContextOp(ctx, dq.ctx, "IDs")
|
||||
if err := dq.Select(document.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -248,11 +271,10 @@ func (dq *DocumentQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (dq *DocumentQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, dq.ctx, "Count")
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, dq, querierCount[*DocumentQuery](), dq.inters)
|
||||
return dq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
@@ -266,15 +288,10 @@ func (dq *DocumentQuery) CountX(ctx context.Context) int {
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (dq *DocumentQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, dq.ctx, "Exist")
|
||||
switch _, err := dq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return dq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
@@ -293,23 +310,25 @@ func (dq *DocumentQuery) Clone() *DocumentQuery {
|
||||
return nil
|
||||
}
|
||||
return &DocumentQuery{
|
||||
config: dq.config,
|
||||
ctx: dq.ctx.Clone(),
|
||||
order: append([]OrderFunc{}, dq.order...),
|
||||
inters: append([]Interceptor{}, dq.inters...),
|
||||
predicates: append([]predicate.Document{}, dq.predicates...),
|
||||
withGroup: dq.withGroup.Clone(),
|
||||
withAttachments: dq.withAttachments.Clone(),
|
||||
config: dq.config,
|
||||
limit: dq.limit,
|
||||
offset: dq.offset,
|
||||
order: append([]OrderFunc{}, dq.order...),
|
||||
predicates: append([]predicate.Document{}, dq.predicates...),
|
||||
withGroup: dq.withGroup.Clone(),
|
||||
withDocumentTokens: dq.withDocumentTokens.Clone(),
|
||||
withAttachments: dq.withAttachments.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: dq.sql.Clone(),
|
||||
path: dq.path,
|
||||
sql: dq.sql.Clone(),
|
||||
path: dq.path,
|
||||
unique: dq.unique,
|
||||
}
|
||||
}
|
||||
|
||||
// WithGroup tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (dq *DocumentQuery) WithGroup(opts ...func(*GroupQuery)) *DocumentQuery {
|
||||
query := (&GroupClient{config: dq.config}).Query()
|
||||
query := &GroupQuery{config: dq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -317,10 +336,21 @@ func (dq *DocumentQuery) WithGroup(opts ...func(*GroupQuery)) *DocumentQuery {
|
||||
return dq
|
||||
}
|
||||
|
||||
// WithDocumentTokens tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "document_tokens" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (dq *DocumentQuery) WithDocumentTokens(opts ...func(*DocumentTokenQuery)) *DocumentQuery {
|
||||
query := &DocumentTokenQuery{config: dq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
dq.withDocumentTokens = query
|
||||
return dq
|
||||
}
|
||||
|
||||
// WithAttachments tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "attachments" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (dq *DocumentQuery) WithAttachments(opts ...func(*AttachmentQuery)) *DocumentQuery {
|
||||
query := (&AttachmentClient{config: dq.config}).Query()
|
||||
query := &AttachmentQuery{config: dq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -343,11 +373,16 @@ func (dq *DocumentQuery) WithAttachments(opts ...func(*AttachmentQuery)) *Docume
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (dq *DocumentQuery) GroupBy(field string, fields ...string) *DocumentGroupBy {
|
||||
dq.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &DocumentGroupBy{build: dq}
|
||||
grbuild.flds = &dq.ctx.Fields
|
||||
grbuild := &DocumentGroupBy{config: dq.config}
|
||||
grbuild.fields = append([]string{field}, fields...)
|
||||
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
|
||||
if err := dq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dq.sqlQuery(ctx), nil
|
||||
}
|
||||
grbuild.label = document.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
@@ -364,30 +399,15 @@ func (dq *DocumentQuery) GroupBy(field string, fields ...string) *DocumentGroupB
|
||||
// Select(document.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (dq *DocumentQuery) Select(fields ...string) *DocumentSelect {
|
||||
dq.ctx.Fields = append(dq.ctx.Fields, fields...)
|
||||
sbuild := &DocumentSelect{DocumentQuery: dq}
|
||||
sbuild.label = document.Label
|
||||
sbuild.flds, sbuild.scan = &dq.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a DocumentSelect configured with the given aggregations.
|
||||
func (dq *DocumentQuery) Aggregate(fns ...AggregateFunc) *DocumentSelect {
|
||||
return dq.Select().Aggregate(fns...)
|
||||
dq.fields = append(dq.fields, fields...)
|
||||
selbuild := &DocumentSelect{DocumentQuery: dq}
|
||||
selbuild.label = document.Label
|
||||
selbuild.flds, selbuild.scan = &dq.fields, selbuild.Scan
|
||||
return selbuild
|
||||
}
|
||||
|
||||
func (dq *DocumentQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range dq.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, dq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range dq.ctx.Fields {
|
||||
for _, f := range dq.fields {
|
||||
if !document.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
@@ -407,8 +427,9 @@ func (dq *DocumentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Doc
|
||||
nodes = []*Document{}
|
||||
withFKs = dq.withFKs
|
||||
_spec = dq.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
loadedTypes = [3]bool{
|
||||
dq.withGroup != nil,
|
||||
dq.withDocumentTokens != nil,
|
||||
dq.withAttachments != nil,
|
||||
}
|
||||
)
|
||||
@@ -442,6 +463,13 @@ func (dq *DocumentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Doc
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := dq.withDocumentTokens; query != nil {
|
||||
if err := dq.loadDocumentTokens(ctx, query, nodes,
|
||||
func(n *Document) { n.Edges.DocumentTokens = []*DocumentToken{} },
|
||||
func(n *Document, e *DocumentToken) { n.Edges.DocumentTokens = append(n.Edges.DocumentTokens, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := dq.withAttachments; query != nil {
|
||||
if err := dq.loadAttachments(ctx, query, nodes,
|
||||
func(n *Document) { n.Edges.Attachments = []*Attachment{} },
|
||||
@@ -465,9 +493,6 @@ func (dq *DocumentQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(group.IDIn(ids...))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
@@ -484,6 +509,37 @@ func (dq *DocumentQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (dq *DocumentQuery) loadDocumentTokens(ctx context.Context, query *DocumentTokenQuery, nodes []*Document, init func(*Document), assign func(*Document, *DocumentToken)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID]*Document)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
if init != nil {
|
||||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
query.withFKs = true
|
||||
query.Where(predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(document.DocumentTokensColumn, fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.document_document_tokens
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "document_document_tokens" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected foreign-key "document_document_tokens" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (dq *DocumentQuery) loadAttachments(ctx context.Context, query *AttachmentQuery, nodes []*Document, init func(*Document), assign func(*Document, *Attachment)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID]*Document)
|
||||
@@ -518,13 +574,24 @@ func (dq *DocumentQuery) loadAttachments(ctx context.Context, query *AttachmentQ
|
||||
|
||||
func (dq *DocumentQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := dq.querySpec()
|
||||
_spec.Node.Columns = dq.ctx.Fields
|
||||
if len(dq.ctx.Fields) > 0 {
|
||||
_spec.Unique = dq.ctx.Unique != nil && *dq.ctx.Unique
|
||||
_spec.Node.Columns = dq.fields
|
||||
if len(dq.fields) > 0 {
|
||||
_spec.Unique = dq.unique != nil && *dq.unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, dq.driver, _spec)
|
||||
}
|
||||
|
||||
func (dq *DocumentQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
switch _, err := dq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (dq *DocumentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := &sqlgraph.QuerySpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
@@ -538,10 +605,10 @@ func (dq *DocumentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
From: dq.sql,
|
||||
Unique: true,
|
||||
}
|
||||
if unique := dq.ctx.Unique; unique != nil {
|
||||
if unique := dq.unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
}
|
||||
if fields := dq.ctx.Fields; len(fields) > 0 {
|
||||
if fields := dq.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, document.FieldID)
|
||||
for i := range fields {
|
||||
@@ -557,10 +624,10 @@ func (dq *DocumentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := dq.ctx.Limit; limit != nil {
|
||||
if limit := dq.limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := dq.ctx.Offset; offset != nil {
|
||||
if offset := dq.offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := dq.order; len(ps) > 0 {
|
||||
@@ -576,7 +643,7 @@ func (dq *DocumentQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
func (dq *DocumentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(dq.driver.Dialect())
|
||||
t1 := builder.Table(document.Table)
|
||||
columns := dq.ctx.Fields
|
||||
columns := dq.fields
|
||||
if len(columns) == 0 {
|
||||
columns = document.Columns
|
||||
}
|
||||
@@ -585,7 +652,7 @@ func (dq *DocumentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
selector = dq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if dq.ctx.Unique != nil && *dq.ctx.Unique {
|
||||
if dq.unique != nil && *dq.unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range dq.predicates {
|
||||
@@ -594,12 +661,12 @@ func (dq *DocumentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
for _, p := range dq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := dq.ctx.Offset; offset != nil {
|
||||
if offset := dq.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 := dq.ctx.Limit; limit != nil {
|
||||
if limit := dq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
@@ -607,8 +674,13 @@ func (dq *DocumentQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
|
||||
// DocumentGroupBy is the group-by builder for Document entities.
|
||||
type DocumentGroupBy struct {
|
||||
config
|
||||
selector
|
||||
build *DocumentQuery
|
||||
fields []string
|
||||
fns []AggregateFunc
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
@@ -617,77 +689,74 @@ func (dgb *DocumentGroupBy) Aggregate(fns ...AggregateFunc) *DocumentGroupBy {
|
||||
return dgb
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
// Scan applies the group-by query and scans the result into the given value.
|
||||
func (dgb *DocumentGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, dgb.build.ctx, "GroupBy")
|
||||
if err := dgb.build.prepareQuery(ctx); err != nil {
|
||||
query, err := dgb.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*DocumentQuery, *DocumentGroupBy](ctx, dgb.build, dgb, dgb.build.inters, v)
|
||||
dgb.sql = query
|
||||
return dgb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (dgb *DocumentGroupBy) sqlScan(ctx context.Context, root *DocumentQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(dgb.fns))
|
||||
for _, fn := range dgb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*dgb.flds)+len(dgb.fns))
|
||||
for _, f := range *dgb.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
func (dgb *DocumentGroupBy) sqlScan(ctx context.Context, v any) error {
|
||||
for _, f := range dgb.fields {
|
||||
if !document.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*dgb.flds...)...)
|
||||
selector := dgb.sqlQuery()
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := dgb.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
if err := dgb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (dgb *DocumentGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := dgb.sql.Select()
|
||||
aggregation := make([]string, 0, len(dgb.fns))
|
||||
for _, fn := range dgb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
// If no columns were selected in a custom aggregation function, the default
|
||||
// selection is the fields used for "group-by", and the aggregation functions.
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(dgb.fields)+len(dgb.fns))
|
||||
for _, f := range dgb.fields {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
return selector.GroupBy(selector.Columns(dgb.fields...)...)
|
||||
}
|
||||
|
||||
// DocumentSelect is the builder for selecting fields of Document entities.
|
||||
type DocumentSelect struct {
|
||||
*DocumentQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (ds *DocumentSelect) Aggregate(fns ...AggregateFunc) *DocumentSelect {
|
||||
ds.fns = append(ds.fns, fns...)
|
||||
return ds
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (ds *DocumentSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, ds.ctx, "Select")
|
||||
if err := ds.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*DocumentQuery, *DocumentSelect](ctx, ds.DocumentQuery, ds, ds.inters, v)
|
||||
ds.sql = ds.DocumentQuery.sqlQuery(ctx)
|
||||
return ds.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (ds *DocumentSelect) sqlScan(ctx context.Context, root *DocumentQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(ds.fns))
|
||||
for _, fn := range ds.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*ds.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
func (ds *DocumentSelect) sqlScan(ctx context.Context, v any) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
query, args := ds.sql.Query()
|
||||
if err := ds.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -12,10 +12,11 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// DocumentUpdate is the builder for updating Document entities.
|
||||
@@ -60,6 +61,21 @@ func (du *DocumentUpdate) SetGroup(g *Group) *DocumentUpdate {
|
||||
return du.SetGroupID(g.ID)
|
||||
}
|
||||
|
||||
// AddDocumentTokenIDs adds the "document_tokens" edge to the DocumentToken entity by IDs.
|
||||
func (du *DocumentUpdate) AddDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdate {
|
||||
du.mutation.AddDocumentTokenIDs(ids...)
|
||||
return du
|
||||
}
|
||||
|
||||
// AddDocumentTokens adds the "document_tokens" edges to the DocumentToken entity.
|
||||
func (du *DocumentUpdate) AddDocumentTokens(d ...*DocumentToken) *DocumentUpdate {
|
||||
ids := make([]uuid.UUID, len(d))
|
||||
for i := range d {
|
||||
ids[i] = d[i].ID
|
||||
}
|
||||
return du.AddDocumentTokenIDs(ids...)
|
||||
}
|
||||
|
||||
// AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs.
|
||||
func (du *DocumentUpdate) AddAttachmentIDs(ids ...uuid.UUID) *DocumentUpdate {
|
||||
du.mutation.AddAttachmentIDs(ids...)
|
||||
@@ -86,6 +102,27 @@ func (du *DocumentUpdate) ClearGroup() *DocumentUpdate {
|
||||
return du
|
||||
}
|
||||
|
||||
// ClearDocumentTokens clears all "document_tokens" edges to the DocumentToken entity.
|
||||
func (du *DocumentUpdate) ClearDocumentTokens() *DocumentUpdate {
|
||||
du.mutation.ClearDocumentTokens()
|
||||
return du
|
||||
}
|
||||
|
||||
// RemoveDocumentTokenIDs removes the "document_tokens" edge to DocumentToken entities by IDs.
|
||||
func (du *DocumentUpdate) RemoveDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdate {
|
||||
du.mutation.RemoveDocumentTokenIDs(ids...)
|
||||
return du
|
||||
}
|
||||
|
||||
// RemoveDocumentTokens removes "document_tokens" edges to DocumentToken entities.
|
||||
func (du *DocumentUpdate) RemoveDocumentTokens(d ...*DocumentToken) *DocumentUpdate {
|
||||
ids := make([]uuid.UUID, len(d))
|
||||
for i := range d {
|
||||
ids[i] = d[i].ID
|
||||
}
|
||||
return du.RemoveDocumentTokenIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearAttachments clears all "attachments" edges to the Attachment entity.
|
||||
func (du *DocumentUpdate) ClearAttachments() *DocumentUpdate {
|
||||
du.mutation.ClearAttachments()
|
||||
@@ -109,8 +146,41 @@ func (du *DocumentUpdate) RemoveAttachments(a ...*Attachment) *DocumentUpdate {
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (du *DocumentUpdate) Save(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
du.defaults()
|
||||
return withHooks[int, DocumentMutation](ctx, du.sqlSave, du.mutation, du.hooks)
|
||||
if len(du.hooks) == 0 {
|
||||
if err = du.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err = du.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = du.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
du.mutation = mutation
|
||||
affected, err = du.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(du.hooks) - 1; i >= 0; i-- {
|
||||
if du.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = du.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, du.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -162,9 +232,6 @@ func (du *DocumentUpdate) check() error {
|
||||
}
|
||||
|
||||
func (du *DocumentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if err := du.check(); err != nil {
|
||||
return n, err
|
||||
}
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: document.Table,
|
||||
@@ -183,13 +250,25 @@ func (du *DocumentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
}
|
||||
if value, ok := du.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(document.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: document.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := du.mutation.Title(); ok {
|
||||
_spec.SetField(document.FieldTitle, field.TypeString, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: document.FieldTitle,
|
||||
})
|
||||
}
|
||||
if value, ok := du.mutation.Path(); ok {
|
||||
_spec.SetField(document.FieldPath, field.TypeString, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: document.FieldPath,
|
||||
})
|
||||
}
|
||||
if du.mutation.GroupCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -226,6 +305,60 @@ func (du *DocumentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if du.mutation.DocumentTokensCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := du.mutation.RemovedDocumentTokensIDs(); len(nodes) > 0 && !du.mutation.DocumentTokensCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := du.mutation.DocumentTokensIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if du.mutation.AttachmentsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -288,7 +421,6 @@ func (du *DocumentUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
du.mutation.done = true
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@@ -329,6 +461,21 @@ func (duo *DocumentUpdateOne) SetGroup(g *Group) *DocumentUpdateOne {
|
||||
return duo.SetGroupID(g.ID)
|
||||
}
|
||||
|
||||
// AddDocumentTokenIDs adds the "document_tokens" edge to the DocumentToken entity by IDs.
|
||||
func (duo *DocumentUpdateOne) AddDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdateOne {
|
||||
duo.mutation.AddDocumentTokenIDs(ids...)
|
||||
return duo
|
||||
}
|
||||
|
||||
// AddDocumentTokens adds the "document_tokens" edges to the DocumentToken entity.
|
||||
func (duo *DocumentUpdateOne) AddDocumentTokens(d ...*DocumentToken) *DocumentUpdateOne {
|
||||
ids := make([]uuid.UUID, len(d))
|
||||
for i := range d {
|
||||
ids[i] = d[i].ID
|
||||
}
|
||||
return duo.AddDocumentTokenIDs(ids...)
|
||||
}
|
||||
|
||||
// AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs.
|
||||
func (duo *DocumentUpdateOne) AddAttachmentIDs(ids ...uuid.UUID) *DocumentUpdateOne {
|
||||
duo.mutation.AddAttachmentIDs(ids...)
|
||||
@@ -355,6 +502,27 @@ func (duo *DocumentUpdateOne) ClearGroup() *DocumentUpdateOne {
|
||||
return duo
|
||||
}
|
||||
|
||||
// ClearDocumentTokens clears all "document_tokens" edges to the DocumentToken entity.
|
||||
func (duo *DocumentUpdateOne) ClearDocumentTokens() *DocumentUpdateOne {
|
||||
duo.mutation.ClearDocumentTokens()
|
||||
return duo
|
||||
}
|
||||
|
||||
// RemoveDocumentTokenIDs removes the "document_tokens" edge to DocumentToken entities by IDs.
|
||||
func (duo *DocumentUpdateOne) RemoveDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdateOne {
|
||||
duo.mutation.RemoveDocumentTokenIDs(ids...)
|
||||
return duo
|
||||
}
|
||||
|
||||
// RemoveDocumentTokens removes "document_tokens" edges to DocumentToken entities.
|
||||
func (duo *DocumentUpdateOne) RemoveDocumentTokens(d ...*DocumentToken) *DocumentUpdateOne {
|
||||
ids := make([]uuid.UUID, len(d))
|
||||
for i := range d {
|
||||
ids[i] = d[i].ID
|
||||
}
|
||||
return duo.RemoveDocumentTokenIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearAttachments clears all "attachments" edges to the Attachment entity.
|
||||
func (duo *DocumentUpdateOne) ClearAttachments() *DocumentUpdateOne {
|
||||
duo.mutation.ClearAttachments()
|
||||
@@ -385,8 +553,47 @@ func (duo *DocumentUpdateOne) Select(field string, fields ...string) *DocumentUp
|
||||
|
||||
// Save executes the query and returns the updated Document entity.
|
||||
func (duo *DocumentUpdateOne) Save(ctx context.Context) (*Document, error) {
|
||||
var (
|
||||
err error
|
||||
node *Document
|
||||
)
|
||||
duo.defaults()
|
||||
return withHooks[*Document, DocumentMutation](ctx, duo.sqlSave, duo.mutation, duo.hooks)
|
||||
if len(duo.hooks) == 0 {
|
||||
if err = duo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = duo.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = duo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
duo.mutation = mutation
|
||||
node, err = duo.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(duo.hooks) - 1; i >= 0; i-- {
|
||||
if duo.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = duo.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, duo.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Document)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from DocumentMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -438,9 +645,6 @@ func (duo *DocumentUpdateOne) check() error {
|
||||
}
|
||||
|
||||
func (duo *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err error) {
|
||||
if err := duo.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: document.Table,
|
||||
@@ -476,13 +680,25 @@ func (duo *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err
|
||||
}
|
||||
}
|
||||
if value, ok := duo.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(document.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: document.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := duo.mutation.Title(); ok {
|
||||
_spec.SetField(document.FieldTitle, field.TypeString, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: document.FieldTitle,
|
||||
})
|
||||
}
|
||||
if value, ok := duo.mutation.Path(); ok {
|
||||
_spec.SetField(document.FieldPath, field.TypeString, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: document.FieldPath,
|
||||
})
|
||||
}
|
||||
if duo.mutation.GroupCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -519,6 +735,60 @@ func (duo *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if duo.mutation.DocumentTokensCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := duo.mutation.RemovedDocumentTokensIDs(); len(nodes) > 0 && !duo.mutation.DocumentTokensCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := duo.mutation.DocumentTokensIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: document.DocumentTokensTable,
|
||||
Columns: []string{document.DocumentTokensColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if duo.mutation.AttachmentsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -584,6 +854,5 @@ func (duo *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
duo.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
190
backend/ent/documenttoken.go
Normal file
190
backend/ent/documenttoken.go
Normal file
@@ -0,0 +1,190 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
)
|
||||
|
||||
// DocumentToken is the model entity for the DocumentToken schema.
|
||||
type DocumentToken struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID uuid.UUID `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"`
|
||||
// Token holds the value of the "token" field.
|
||||
Token []byte `json:"token,omitempty"`
|
||||
// Uses holds the value of the "uses" field.
|
||||
Uses int `json:"uses,omitempty"`
|
||||
// ExpiresAt holds the value of the "expires_at" field.
|
||||
ExpiresAt time.Time `json:"expires_at,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the DocumentTokenQuery when eager-loading is set.
|
||||
Edges DocumentTokenEdges `json:"edges"`
|
||||
document_document_tokens *uuid.UUID
|
||||
}
|
||||
|
||||
// DocumentTokenEdges holds the relations/edges for other nodes in the graph.
|
||||
type DocumentTokenEdges struct {
|
||||
// Document holds the value of the document edge.
|
||||
Document *Document `json:"document,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// DocumentOrErr returns the Document value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e DocumentTokenEdges) DocumentOrErr() (*Document, error) {
|
||||
if e.loadedTypes[0] {
|
||||
if e.Document == nil {
|
||||
// Edge was loaded but was not found.
|
||||
return nil, &NotFoundError{label: document.Label}
|
||||
}
|
||||
return e.Document, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "document"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*DocumentToken) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case documenttoken.FieldToken:
|
||||
values[i] = new([]byte)
|
||||
case documenttoken.FieldUses:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case documenttoken.FieldCreatedAt, documenttoken.FieldUpdatedAt, documenttoken.FieldExpiresAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
case documenttoken.FieldID:
|
||||
values[i] = new(uuid.UUID)
|
||||
case documenttoken.ForeignKeys[0]: // document_document_tokens
|
||||
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected column %q for type DocumentToken", columns[i])
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the DocumentToken fields.
|
||||
func (dt *DocumentToken) 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 documenttoken.FieldID:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value != nil {
|
||||
dt.ID = *value
|
||||
}
|
||||
case documenttoken.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 {
|
||||
dt.CreatedAt = value.Time
|
||||
}
|
||||
case documenttoken.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 {
|
||||
dt.UpdatedAt = value.Time
|
||||
}
|
||||
case documenttoken.FieldToken:
|
||||
if value, ok := values[i].(*[]byte); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field token", values[i])
|
||||
} else if value != nil {
|
||||
dt.Token = *value
|
||||
}
|
||||
case documenttoken.FieldUses:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field uses", values[i])
|
||||
} else if value.Valid {
|
||||
dt.Uses = int(value.Int64)
|
||||
}
|
||||
case documenttoken.FieldExpiresAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
|
||||
} else if value.Valid {
|
||||
dt.ExpiresAt = value.Time
|
||||
}
|
||||
case documenttoken.ForeignKeys[0]:
|
||||
if value, ok := values[i].(*sql.NullScanner); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field document_document_tokens", values[i])
|
||||
} else if value.Valid {
|
||||
dt.document_document_tokens = new(uuid.UUID)
|
||||
*dt.document_document_tokens = *value.S.(*uuid.UUID)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// QueryDocument queries the "document" edge of the DocumentToken entity.
|
||||
func (dt *DocumentToken) QueryDocument() *DocumentQuery {
|
||||
return (&DocumentTokenClient{config: dt.config}).QueryDocument(dt)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this DocumentToken.
|
||||
// Note that you need to call DocumentToken.Unwrap() before calling this method if this DocumentToken
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (dt *DocumentToken) Update() *DocumentTokenUpdateOne {
|
||||
return (&DocumentTokenClient{config: dt.config}).UpdateOne(dt)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the DocumentToken entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (dt *DocumentToken) Unwrap() *DocumentToken {
|
||||
_tx, ok := dt.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: DocumentToken is not a transactional entity")
|
||||
}
|
||||
dt.config.driver = _tx.drv
|
||||
return dt
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (dt *DocumentToken) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("DocumentToken(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", dt.ID))
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(dt.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("updated_at=")
|
||||
builder.WriteString(dt.UpdatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("token=")
|
||||
builder.WriteString(fmt.Sprintf("%v", dt.Token))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("uses=")
|
||||
builder.WriteString(fmt.Sprintf("%v", dt.Uses))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("expires_at=")
|
||||
builder.WriteString(dt.ExpiresAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// DocumentTokens is a parsable slice of DocumentToken.
|
||||
type DocumentTokens []*DocumentToken
|
||||
|
||||
func (dt DocumentTokens) config(cfg config) {
|
||||
for _i := range dt {
|
||||
dt[_i].config = cfg
|
||||
}
|
||||
}
|
||||
85
backend/ent/documenttoken/documenttoken.go
Normal file
85
backend/ent/documenttoken/documenttoken.go
Normal file
@@ -0,0 +1,85 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package documenttoken
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the documenttoken type in the database.
|
||||
Label = "document_token"
|
||||
// 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"
|
||||
// FieldToken holds the string denoting the token field in the database.
|
||||
FieldToken = "token"
|
||||
// FieldUses holds the string denoting the uses field in the database.
|
||||
FieldUses = "uses"
|
||||
// FieldExpiresAt holds the string denoting the expires_at field in the database.
|
||||
FieldExpiresAt = "expires_at"
|
||||
// EdgeDocument holds the string denoting the document edge name in mutations.
|
||||
EdgeDocument = "document"
|
||||
// Table holds the table name of the documenttoken in the database.
|
||||
Table = "document_tokens"
|
||||
// DocumentTable is the table that holds the document relation/edge.
|
||||
DocumentTable = "document_tokens"
|
||||
// DocumentInverseTable is the table name for the Document entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "document" package.
|
||||
DocumentInverseTable = "documents"
|
||||
// DocumentColumn is the table column denoting the document relation/edge.
|
||||
DocumentColumn = "document_document_tokens"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for documenttoken fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
FieldToken,
|
||||
FieldUses,
|
||||
FieldExpiresAt,
|
||||
}
|
||||
|
||||
// ForeignKeys holds the SQL foreign-keys that are owned by the "document_tokens"
|
||||
// table and are not defined as standalone fields in the schema.
|
||||
var ForeignKeys = []string{
|
||||
"document_document_tokens",
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for i := range ForeignKeys {
|
||||
if column == ForeignKeys[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
// 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
|
||||
// TokenValidator is a validator for the "token" field. It is called by the builders before save.
|
||||
TokenValidator func([]byte) error
|
||||
// DefaultUses holds the default value on creation for the "uses" field.
|
||||
DefaultUses int
|
||||
// DefaultExpiresAt holds the default value on creation for the "expires_at" field.
|
||||
DefaultExpiresAt func() time.Time
|
||||
// DefaultID holds the default value on creation for the "id" field.
|
||||
DefaultID func() uuid.UUID
|
||||
)
|
||||
498
backend/ent/documenttoken/where.go
Normal file
498
backend/ent/documenttoken/where.go
Normal file
@@ -0,0 +1,498 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package documenttoken
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.In(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.NotIn(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
|
||||
func Token(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Uses applies equality check predicate on the "uses" field. It's identical to UsesEQ.
|
||||
func Uses(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
|
||||
func ExpiresAt(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenEQ applies the EQ predicate on the "token" field.
|
||||
func TokenEQ(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenNEQ applies the NEQ predicate on the "token" field.
|
||||
func TokenNEQ(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenIn applies the In predicate on the "token" field.
|
||||
func TokenIn(vs ...[]byte) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldToken), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenNotIn applies the NotIn predicate on the "token" field.
|
||||
func TokenNotIn(vs ...[]byte) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldToken), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenGT applies the GT predicate on the "token" field.
|
||||
func TokenGT(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenGTE applies the GTE predicate on the "token" field.
|
||||
func TokenGTE(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenLT applies the LT predicate on the "token" field.
|
||||
func TokenLT(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenLTE applies the LTE predicate on the "token" field.
|
||||
func TokenLTE(v []byte) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesEQ applies the EQ predicate on the "uses" field.
|
||||
func UsesEQ(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesNEQ applies the NEQ predicate on the "uses" field.
|
||||
func UsesNEQ(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesIn applies the In predicate on the "uses" field.
|
||||
func UsesIn(vs ...int) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUses), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesNotIn applies the NotIn predicate on the "uses" field.
|
||||
func UsesNotIn(vs ...int) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUses), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesGT applies the GT predicate on the "uses" field.
|
||||
func UsesGT(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesGTE applies the GTE predicate on the "uses" field.
|
||||
func UsesGTE(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesLT applies the LT predicate on the "uses" field.
|
||||
func UsesLT(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesLTE applies the LTE predicate on the "uses" field.
|
||||
func UsesLTE(v int) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
|
||||
func ExpiresAtEQ(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
|
||||
func ExpiresAtNEQ(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtIn applies the In predicate on the "expires_at" field.
|
||||
func ExpiresAtIn(vs ...time.Time) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldExpiresAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
|
||||
func ExpiresAtNotIn(vs ...time.Time) predicate.DocumentToken {
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
|
||||
func ExpiresAtGT(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
|
||||
func ExpiresAtGTE(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
|
||||
func ExpiresAtLT(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
|
||||
func ExpiresAtLTE(v time.Time) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// HasDocument applies the HasEdge predicate on the "document" edge.
|
||||
func HasDocument() predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DocumentTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasDocumentWith applies the HasEdge predicate on the "document" edge with a given conditions (other predicates).
|
||||
func HasDocumentWith(preds ...predicate.Document) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DocumentInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
|
||||
)
|
||||
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.DocumentToken) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s1 := s.Clone().SetP(nil)
|
||||
for _, p := range predicates {
|
||||
p(s1)
|
||||
}
|
||||
s.Where(s1.P())
|
||||
})
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.DocumentToken) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
s1 := s.Clone().SetP(nil)
|
||||
for i, p := range predicates {
|
||||
if i > 0 {
|
||||
s1.Or()
|
||||
}
|
||||
p(s1)
|
||||
}
|
||||
s.Where(s1.P())
|
||||
})
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.DocumentToken) predicate.DocumentToken {
|
||||
return predicate.DocumentToken(func(s *sql.Selector) {
|
||||
p(s.Not())
|
||||
})
|
||||
}
|
||||
418
backend/ent/documenttoken_create.go
Normal file
418
backend/ent/documenttoken_create.go
Normal file
@@ -0,0 +1,418 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
)
|
||||
|
||||
// DocumentTokenCreate is the builder for creating a DocumentToken entity.
|
||||
type DocumentTokenCreate struct {
|
||||
config
|
||||
mutation *DocumentTokenMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (dtc *DocumentTokenCreate) SetCreatedAt(t time.Time) *DocumentTokenCreate {
|
||||
dtc.mutation.SetCreatedAt(t)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (dtc *DocumentTokenCreate) SetNillableCreatedAt(t *time.Time) *DocumentTokenCreate {
|
||||
if t != nil {
|
||||
dtc.SetCreatedAt(*t)
|
||||
}
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (dtc *DocumentTokenCreate) SetUpdatedAt(t time.Time) *DocumentTokenCreate {
|
||||
dtc.mutation.SetUpdatedAt(t)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (dtc *DocumentTokenCreate) SetNillableUpdatedAt(t *time.Time) *DocumentTokenCreate {
|
||||
if t != nil {
|
||||
dtc.SetUpdatedAt(*t)
|
||||
}
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (dtc *DocumentTokenCreate) SetToken(b []byte) *DocumentTokenCreate {
|
||||
dtc.mutation.SetToken(b)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetUses sets the "uses" field.
|
||||
func (dtc *DocumentTokenCreate) SetUses(i int) *DocumentTokenCreate {
|
||||
dtc.mutation.SetUses(i)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetNillableUses sets the "uses" field if the given value is not nil.
|
||||
func (dtc *DocumentTokenCreate) SetNillableUses(i *int) *DocumentTokenCreate {
|
||||
if i != nil {
|
||||
dtc.SetUses(*i)
|
||||
}
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (dtc *DocumentTokenCreate) SetExpiresAt(t time.Time) *DocumentTokenCreate {
|
||||
dtc.mutation.SetExpiresAt(t)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (dtc *DocumentTokenCreate) SetNillableExpiresAt(t *time.Time) *DocumentTokenCreate {
|
||||
if t != nil {
|
||||
dtc.SetExpiresAt(*t)
|
||||
}
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (dtc *DocumentTokenCreate) SetID(u uuid.UUID) *DocumentTokenCreate {
|
||||
dtc.mutation.SetID(u)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetNillableID sets the "id" field if the given value is not nil.
|
||||
func (dtc *DocumentTokenCreate) SetNillableID(u *uuid.UUID) *DocumentTokenCreate {
|
||||
if u != nil {
|
||||
dtc.SetID(*u)
|
||||
}
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetDocumentID sets the "document" edge to the Document entity by ID.
|
||||
func (dtc *DocumentTokenCreate) SetDocumentID(id uuid.UUID) *DocumentTokenCreate {
|
||||
dtc.mutation.SetDocumentID(id)
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetNillableDocumentID sets the "document" edge to the Document entity by ID if the given value is not nil.
|
||||
func (dtc *DocumentTokenCreate) SetNillableDocumentID(id *uuid.UUID) *DocumentTokenCreate {
|
||||
if id != nil {
|
||||
dtc = dtc.SetDocumentID(*id)
|
||||
}
|
||||
return dtc
|
||||
}
|
||||
|
||||
// SetDocument sets the "document" edge to the Document entity.
|
||||
func (dtc *DocumentTokenCreate) SetDocument(d *Document) *DocumentTokenCreate {
|
||||
return dtc.SetDocumentID(d.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the DocumentTokenMutation object of the builder.
|
||||
func (dtc *DocumentTokenCreate) Mutation() *DocumentTokenMutation {
|
||||
return dtc.mutation
|
||||
}
|
||||
|
||||
// Save creates the DocumentToken in the database.
|
||||
func (dtc *DocumentTokenCreate) Save(ctx context.Context) (*DocumentToken, error) {
|
||||
var (
|
||||
err error
|
||||
node *DocumentToken
|
||||
)
|
||||
dtc.defaults()
|
||||
if len(dtc.hooks) == 0 {
|
||||
if err = dtc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = dtc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = dtc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dtc.mutation = mutation
|
||||
if node, err = dtc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(dtc.hooks) - 1; i >= 0; i-- {
|
||||
if dtc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = dtc.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, dtc.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*DocumentToken)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from DocumentTokenMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (dtc *DocumentTokenCreate) SaveX(ctx context.Context) *DocumentToken {
|
||||
v, err := dtc.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (dtc *DocumentTokenCreate) Exec(ctx context.Context) error {
|
||||
_, err := dtc.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (dtc *DocumentTokenCreate) ExecX(ctx context.Context) {
|
||||
if err := dtc.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (dtc *DocumentTokenCreate) defaults() {
|
||||
if _, ok := dtc.mutation.CreatedAt(); !ok {
|
||||
v := documenttoken.DefaultCreatedAt()
|
||||
dtc.mutation.SetCreatedAt(v)
|
||||
}
|
||||
if _, ok := dtc.mutation.UpdatedAt(); !ok {
|
||||
v := documenttoken.DefaultUpdatedAt()
|
||||
dtc.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
if _, ok := dtc.mutation.Uses(); !ok {
|
||||
v := documenttoken.DefaultUses
|
||||
dtc.mutation.SetUses(v)
|
||||
}
|
||||
if _, ok := dtc.mutation.ExpiresAt(); !ok {
|
||||
v := documenttoken.DefaultExpiresAt()
|
||||
dtc.mutation.SetExpiresAt(v)
|
||||
}
|
||||
if _, ok := dtc.mutation.ID(); !ok {
|
||||
v := documenttoken.DefaultID()
|
||||
dtc.mutation.SetID(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (dtc *DocumentTokenCreate) check() error {
|
||||
if _, ok := dtc.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "DocumentToken.created_at"`)}
|
||||
}
|
||||
if _, ok := dtc.mutation.UpdatedAt(); !ok {
|
||||
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "DocumentToken.updated_at"`)}
|
||||
}
|
||||
if _, ok := dtc.mutation.Token(); !ok {
|
||||
return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "DocumentToken.token"`)}
|
||||
}
|
||||
if v, ok := dtc.mutation.Token(); ok {
|
||||
if err := documenttoken.TokenValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "DocumentToken.token": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := dtc.mutation.Uses(); !ok {
|
||||
return &ValidationError{Name: "uses", err: errors.New(`ent: missing required field "DocumentToken.uses"`)}
|
||||
}
|
||||
if _, ok := dtc.mutation.ExpiresAt(); !ok {
|
||||
return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "DocumentToken.expires_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dtc *DocumentTokenCreate) sqlSave(ctx context.Context) (*DocumentToken, error) {
|
||||
_node, _spec := dtc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, dtc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
|
||||
_node.ID = *id
|
||||
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (dtc *DocumentTokenCreate) createSpec() (*DocumentToken, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &DocumentToken{config: dtc.config}
|
||||
_spec = &sqlgraph.CreateSpec{
|
||||
Table: documenttoken.Table,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
}
|
||||
)
|
||||
if id, ok := dtc.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := dtc.mutation.CreatedAt(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := dtc.mutation.UpdatedAt(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := dtc.mutation.Token(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldToken,
|
||||
})
|
||||
_node.Token = value
|
||||
}
|
||||
if value, ok := dtc.mutation.Uses(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUses,
|
||||
})
|
||||
_node.Uses = value
|
||||
}
|
||||
if value, ok := dtc.mutation.ExpiresAt(); ok {
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldExpiresAt,
|
||||
})
|
||||
_node.ExpiresAt = value
|
||||
}
|
||||
if nodes := dtc.mutation.DocumentIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: documenttoken.DocumentTable,
|
||||
Columns: []string{documenttoken.DocumentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: document.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.document_document_tokens = &nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// DocumentTokenCreateBulk is the builder for creating many DocumentToken entities in bulk.
|
||||
type DocumentTokenCreateBulk struct {
|
||||
config
|
||||
builders []*DocumentTokenCreate
|
||||
}
|
||||
|
||||
// Save creates the DocumentToken entities in the database.
|
||||
func (dtcb *DocumentTokenCreateBulk) Save(ctx context.Context) ([]*DocumentToken, error) {
|
||||
specs := make([]*sqlgraph.CreateSpec, len(dtcb.builders))
|
||||
nodes := make([]*DocumentToken, len(dtcb.builders))
|
||||
mutators := make([]Mutator, len(dtcb.builders))
|
||||
for i := range dtcb.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := dtcb.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
var err error
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, dtcb.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, dtcb.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, dtcb.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (dtcb *DocumentTokenCreateBulk) SaveX(ctx context.Context) []*DocumentToken {
|
||||
v, err := dtcb.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (dtcb *DocumentTokenCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := dtcb.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (dtcb *DocumentTokenCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := dtcb.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
115
backend/ent/documenttoken_delete.go
Normal file
115
backend/ent/documenttoken_delete.go
Normal file
@@ -0,0 +1,115 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// DocumentTokenDelete is the builder for deleting a DocumentToken entity.
|
||||
type DocumentTokenDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *DocumentTokenMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the DocumentTokenDelete builder.
|
||||
func (dtd *DocumentTokenDelete) Where(ps ...predicate.DocumentToken) *DocumentTokenDelete {
|
||||
dtd.mutation.Where(ps...)
|
||||
return dtd
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (dtd *DocumentTokenDelete) Exec(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
if len(dtd.hooks) == 0 {
|
||||
affected, err = dtd.sqlExec(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
dtd.mutation = mutation
|
||||
affected, err = dtd.sqlExec(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(dtd.hooks) - 1; i >= 0; i-- {
|
||||
if dtd.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = dtd.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, dtd.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (dtd *DocumentTokenDelete) ExecX(ctx context.Context) int {
|
||||
n, err := dtd.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (dtd *DocumentTokenDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := &sqlgraph.DeleteSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: documenttoken.Table,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
if ps := dtd.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, dtd.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// DocumentTokenDeleteOne is the builder for deleting a single DocumentToken entity.
|
||||
type DocumentTokenDeleteOne struct {
|
||||
dtd *DocumentTokenDelete
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (dtdo *DocumentTokenDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := dtdo.dtd.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{documenttoken.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (dtdo *DocumentTokenDeleteOne) ExecX(ctx context.Context) {
|
||||
dtdo.dtd.ExecX(ctx)
|
||||
}
|
||||
614
backend/ent/documenttoken_query.go
Normal file
614
backend/ent/documenttoken_query.go
Normal file
@@ -0,0 +1,614 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// DocumentTokenQuery is the builder for querying DocumentToken entities.
|
||||
type DocumentTokenQuery struct {
|
||||
config
|
||||
limit *int
|
||||
offset *int
|
||||
unique *bool
|
||||
order []OrderFunc
|
||||
fields []string
|
||||
predicates []predicate.DocumentToken
|
||||
withDocument *DocumentQuery
|
||||
withFKs bool
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the DocumentTokenQuery builder.
|
||||
func (dtq *DocumentTokenQuery) Where(ps ...predicate.DocumentToken) *DocumentTokenQuery {
|
||||
dtq.predicates = append(dtq.predicates, ps...)
|
||||
return dtq
|
||||
}
|
||||
|
||||
// Limit adds a limit step to the query.
|
||||
func (dtq *DocumentTokenQuery) Limit(limit int) *DocumentTokenQuery {
|
||||
dtq.limit = &limit
|
||||
return dtq
|
||||
}
|
||||
|
||||
// Offset adds an offset step to the query.
|
||||
func (dtq *DocumentTokenQuery) Offset(offset int) *DocumentTokenQuery {
|
||||
dtq.offset = &offset
|
||||
return dtq
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (dtq *DocumentTokenQuery) Unique(unique bool) *DocumentTokenQuery {
|
||||
dtq.unique = &unique
|
||||
return dtq
|
||||
}
|
||||
|
||||
// Order adds an order step to the query.
|
||||
func (dtq *DocumentTokenQuery) Order(o ...OrderFunc) *DocumentTokenQuery {
|
||||
dtq.order = append(dtq.order, o...)
|
||||
return dtq
|
||||
}
|
||||
|
||||
// QueryDocument chains the current query on the "document" edge.
|
||||
func (dtq *DocumentTokenQuery) QueryDocument() *DocumentQuery {
|
||||
query := &DocumentQuery{config: dtq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := dtq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selector := dtq.sqlQuery(ctx)
|
||||
if err := selector.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(documenttoken.Table, documenttoken.FieldID, selector),
|
||||
sqlgraph.To(document.Table, document.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, documenttoken.DocumentTable, documenttoken.DocumentColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(dtq.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first DocumentToken entity from the query.
|
||||
// Returns a *NotFoundError when no DocumentToken was found.
|
||||
func (dtq *DocumentTokenQuery) First(ctx context.Context) (*DocumentToken, error) {
|
||||
nodes, err := dtq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{documenttoken.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) FirstX(ctx context.Context) *DocumentToken {
|
||||
node, err := dtq.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first DocumentToken ID from the query.
|
||||
// Returns a *NotFoundError when no DocumentToken ID was found.
|
||||
func (dtq *DocumentTokenQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = dtq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{documenttoken.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := dtq.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single DocumentToken entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one DocumentToken entity is found.
|
||||
// Returns a *NotFoundError when no DocumentToken entities are found.
|
||||
func (dtq *DocumentTokenQuery) Only(ctx context.Context) (*DocumentToken, error) {
|
||||
nodes, err := dtq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{documenttoken.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{documenttoken.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) OnlyX(ctx context.Context) *DocumentToken {
|
||||
node, err := dtq.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only DocumentToken ID in the query.
|
||||
// Returns a *NotSingularError when more than one DocumentToken ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (dtq *DocumentTokenQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = dtq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{documenttoken.Label}
|
||||
default:
|
||||
err = &NotSingularError{documenttoken.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := dtq.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of DocumentTokens.
|
||||
func (dtq *DocumentTokenQuery) All(ctx context.Context) ([]*DocumentToken, error) {
|
||||
if err := dtq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dtq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) AllX(ctx context.Context) []*DocumentToken {
|
||||
nodes, err := dtq.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of DocumentToken IDs.
|
||||
func (dtq *DocumentTokenQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
var ids []uuid.UUID
|
||||
if err := dtq.Select(documenttoken.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
ids, err := dtq.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (dtq *DocumentTokenQuery) Count(ctx context.Context) (int, error) {
|
||||
if err := dtq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return dtq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) CountX(ctx context.Context) int {
|
||||
count, err := dtq.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (dtq *DocumentTokenQuery) Exist(ctx context.Context) (bool, error) {
|
||||
if err := dtq.prepareQuery(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return dtq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (dtq *DocumentTokenQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := dtq.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the DocumentTokenQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (dtq *DocumentTokenQuery) Clone() *DocumentTokenQuery {
|
||||
if dtq == nil {
|
||||
return nil
|
||||
}
|
||||
return &DocumentTokenQuery{
|
||||
config: dtq.config,
|
||||
limit: dtq.limit,
|
||||
offset: dtq.offset,
|
||||
order: append([]OrderFunc{}, dtq.order...),
|
||||
predicates: append([]predicate.DocumentToken{}, dtq.predicates...),
|
||||
withDocument: dtq.withDocument.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: dtq.sql.Clone(),
|
||||
path: dtq.path,
|
||||
unique: dtq.unique,
|
||||
}
|
||||
}
|
||||
|
||||
// WithDocument tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "document" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (dtq *DocumentTokenQuery) WithDocument(opts ...func(*DocumentQuery)) *DocumentTokenQuery {
|
||||
query := &DocumentQuery{config: dtq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
dtq.withDocument = query
|
||||
return dtq
|
||||
}
|
||||
|
||||
// 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.DocumentToken.Query().
|
||||
// GroupBy(documenttoken.FieldCreatedAt).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (dtq *DocumentTokenQuery) GroupBy(field string, fields ...string) *DocumentTokenGroupBy {
|
||||
grbuild := &DocumentTokenGroupBy{config: dtq.config}
|
||||
grbuild.fields = append([]string{field}, fields...)
|
||||
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
|
||||
if err := dtq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dtq.sqlQuery(ctx), nil
|
||||
}
|
||||
grbuild.label = documenttoken.Label
|
||||
grbuild.flds, grbuild.scan = &grbuild.fields, 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.DocumentToken.Query().
|
||||
// Select(documenttoken.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (dtq *DocumentTokenQuery) Select(fields ...string) *DocumentTokenSelect {
|
||||
dtq.fields = append(dtq.fields, fields...)
|
||||
selbuild := &DocumentTokenSelect{DocumentTokenQuery: dtq}
|
||||
selbuild.label = documenttoken.Label
|
||||
selbuild.flds, selbuild.scan = &dtq.fields, selbuild.Scan
|
||||
return selbuild
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, f := range dtq.fields {
|
||||
if !documenttoken.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if dtq.path != nil {
|
||||
prev, err := dtq.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dtq.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DocumentToken, error) {
|
||||
var (
|
||||
nodes = []*DocumentToken{}
|
||||
withFKs = dtq.withFKs
|
||||
_spec = dtq.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
dtq.withDocument != nil,
|
||||
}
|
||||
)
|
||||
if dtq.withDocument != nil {
|
||||
withFKs = true
|
||||
}
|
||||
if withFKs {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, documenttoken.ForeignKeys...)
|
||||
}
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*DocumentToken).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &DocumentToken{config: dtq.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, dtq.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
if query := dtq.withDocument; query != nil {
|
||||
if err := dtq.loadDocument(ctx, query, nodes, nil,
|
||||
func(n *DocumentToken, e *Document) { n.Edges.Document = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) loadDocument(ctx context.Context, query *DocumentQuery, nodes []*DocumentToken, init func(*DocumentToken), assign func(*DocumentToken, *Document)) error {
|
||||
ids := make([]uuid.UUID, 0, len(nodes))
|
||||
nodeids := make(map[uuid.UUID][]*DocumentToken)
|
||||
for i := range nodes {
|
||||
if nodes[i].document_document_tokens == nil {
|
||||
continue
|
||||
}
|
||||
fk := *nodes[i].document_document_tokens
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
query.Where(document.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 "document_document_tokens" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := dtq.querySpec()
|
||||
_spec.Node.Columns = dtq.fields
|
||||
if len(dtq.fields) > 0 {
|
||||
_spec.Unique = dtq.unique != nil && *dtq.unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, dtq.driver, _spec)
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
switch _, err := dtq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := &sqlgraph.QuerySpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: documenttoken.Table,
|
||||
Columns: documenttoken.Columns,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
From: dtq.sql,
|
||||
Unique: true,
|
||||
}
|
||||
if unique := dtq.unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
}
|
||||
if fields := dtq.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, documenttoken.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != documenttoken.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := dtq.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := dtq.limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := dtq.offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := dtq.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (dtq *DocumentTokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(dtq.driver.Dialect())
|
||||
t1 := builder.Table(documenttoken.Table)
|
||||
columns := dtq.fields
|
||||
if len(columns) == 0 {
|
||||
columns = documenttoken.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if dtq.sql != nil {
|
||||
selector = dtq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if dtq.unique != nil && *dtq.unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range dtq.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range dtq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := dtq.offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := dtq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// DocumentTokenGroupBy is the group-by builder for DocumentToken entities.
|
||||
type DocumentTokenGroupBy struct {
|
||||
config
|
||||
selector
|
||||
fields []string
|
||||
fns []AggregateFunc
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (dtgb *DocumentTokenGroupBy) Aggregate(fns ...AggregateFunc) *DocumentTokenGroupBy {
|
||||
dtgb.fns = append(dtgb.fns, fns...)
|
||||
return dtgb
|
||||
}
|
||||
|
||||
// Scan applies the group-by query and scans the result into the given value.
|
||||
func (dtgb *DocumentTokenGroupBy) Scan(ctx context.Context, v any) error {
|
||||
query, err := dtgb.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dtgb.sql = query
|
||||
return dtgb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (dtgb *DocumentTokenGroupBy) sqlScan(ctx context.Context, v any) error {
|
||||
for _, f := range dtgb.fields {
|
||||
if !documenttoken.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
|
||||
}
|
||||
}
|
||||
selector := dtgb.sqlQuery()
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := dtgb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (dtgb *DocumentTokenGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := dtgb.sql.Select()
|
||||
aggregation := make([]string, 0, len(dtgb.fns))
|
||||
for _, fn := range dtgb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
// If no columns were selected in a custom aggregation function, the default
|
||||
// selection is the fields used for "group-by", and the aggregation functions.
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(dtgb.fields)+len(dtgb.fns))
|
||||
for _, f := range dtgb.fields {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
return selector.GroupBy(selector.Columns(dtgb.fields...)...)
|
||||
}
|
||||
|
||||
// DocumentTokenSelect is the builder for selecting fields of DocumentToken entities.
|
||||
type DocumentTokenSelect struct {
|
||||
*DocumentTokenQuery
|
||||
selector
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (dts *DocumentTokenSelect) Scan(ctx context.Context, v any) error {
|
||||
if err := dts.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
dts.sql = dts.DocumentTokenQuery.sqlQuery(ctx)
|
||||
return dts.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (dts *DocumentTokenSelect) sqlScan(ctx context.Context, v any) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := dts.sql.Query()
|
||||
if err := dts.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
582
backend/ent/documenttoken_update.go
Normal file
582
backend/ent/documenttoken_update.go
Normal file
@@ -0,0 +1,582 @@
|
||||
// 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/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// DocumentTokenUpdate is the builder for updating DocumentToken entities.
|
||||
type DocumentTokenUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *DocumentTokenMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the DocumentTokenUpdate builder.
|
||||
func (dtu *DocumentTokenUpdate) Where(ps ...predicate.DocumentToken) *DocumentTokenUpdate {
|
||||
dtu.mutation.Where(ps...)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (dtu *DocumentTokenUpdate) SetUpdatedAt(t time.Time) *DocumentTokenUpdate {
|
||||
dtu.mutation.SetUpdatedAt(t)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (dtu *DocumentTokenUpdate) SetToken(b []byte) *DocumentTokenUpdate {
|
||||
dtu.mutation.SetToken(b)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetUses sets the "uses" field.
|
||||
func (dtu *DocumentTokenUpdate) SetUses(i int) *DocumentTokenUpdate {
|
||||
dtu.mutation.ResetUses()
|
||||
dtu.mutation.SetUses(i)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetNillableUses sets the "uses" field if the given value is not nil.
|
||||
func (dtu *DocumentTokenUpdate) SetNillableUses(i *int) *DocumentTokenUpdate {
|
||||
if i != nil {
|
||||
dtu.SetUses(*i)
|
||||
}
|
||||
return dtu
|
||||
}
|
||||
|
||||
// AddUses adds i to the "uses" field.
|
||||
func (dtu *DocumentTokenUpdate) AddUses(i int) *DocumentTokenUpdate {
|
||||
dtu.mutation.AddUses(i)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (dtu *DocumentTokenUpdate) SetExpiresAt(t time.Time) *DocumentTokenUpdate {
|
||||
dtu.mutation.SetExpiresAt(t)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (dtu *DocumentTokenUpdate) SetNillableExpiresAt(t *time.Time) *DocumentTokenUpdate {
|
||||
if t != nil {
|
||||
dtu.SetExpiresAt(*t)
|
||||
}
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetDocumentID sets the "document" edge to the Document entity by ID.
|
||||
func (dtu *DocumentTokenUpdate) SetDocumentID(id uuid.UUID) *DocumentTokenUpdate {
|
||||
dtu.mutation.SetDocumentID(id)
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetNillableDocumentID sets the "document" edge to the Document entity by ID if the given value is not nil.
|
||||
func (dtu *DocumentTokenUpdate) SetNillableDocumentID(id *uuid.UUID) *DocumentTokenUpdate {
|
||||
if id != nil {
|
||||
dtu = dtu.SetDocumentID(*id)
|
||||
}
|
||||
return dtu
|
||||
}
|
||||
|
||||
// SetDocument sets the "document" edge to the Document entity.
|
||||
func (dtu *DocumentTokenUpdate) SetDocument(d *Document) *DocumentTokenUpdate {
|
||||
return dtu.SetDocumentID(d.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the DocumentTokenMutation object of the builder.
|
||||
func (dtu *DocumentTokenUpdate) Mutation() *DocumentTokenMutation {
|
||||
return dtu.mutation
|
||||
}
|
||||
|
||||
// ClearDocument clears the "document" edge to the Document entity.
|
||||
func (dtu *DocumentTokenUpdate) ClearDocument() *DocumentTokenUpdate {
|
||||
dtu.mutation.ClearDocument()
|
||||
return dtu
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (dtu *DocumentTokenUpdate) Save(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
dtu.defaults()
|
||||
if len(dtu.hooks) == 0 {
|
||||
if err = dtu.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err = dtu.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = dtu.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
dtu.mutation = mutation
|
||||
affected, err = dtu.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(dtu.hooks) - 1; i >= 0; i-- {
|
||||
if dtu.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = dtu.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, dtu.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (dtu *DocumentTokenUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := dtu.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (dtu *DocumentTokenUpdate) Exec(ctx context.Context) error {
|
||||
_, err := dtu.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (dtu *DocumentTokenUpdate) ExecX(ctx context.Context) {
|
||||
if err := dtu.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (dtu *DocumentTokenUpdate) defaults() {
|
||||
if _, ok := dtu.mutation.UpdatedAt(); !ok {
|
||||
v := documenttoken.UpdateDefaultUpdatedAt()
|
||||
dtu.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (dtu *DocumentTokenUpdate) check() error {
|
||||
if v, ok := dtu.mutation.Token(); ok {
|
||||
if err := documenttoken.TokenValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "DocumentToken.token": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dtu *DocumentTokenUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: documenttoken.Table,
|
||||
Columns: documenttoken.Columns,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
if ps := dtu.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := dtu.mutation.UpdatedAt(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := dtu.mutation.Token(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldToken,
|
||||
})
|
||||
}
|
||||
if value, ok := dtu.mutation.Uses(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUses,
|
||||
})
|
||||
}
|
||||
if value, ok := dtu.mutation.AddedUses(); ok {
|
||||
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUses,
|
||||
})
|
||||
}
|
||||
if value, ok := dtu.mutation.ExpiresAt(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldExpiresAt,
|
||||
})
|
||||
}
|
||||
if dtu.mutation.DocumentCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: documenttoken.DocumentTable,
|
||||
Columns: []string{documenttoken.DocumentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: document.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := dtu.mutation.DocumentIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: documenttoken.DocumentTable,
|
||||
Columns: []string{documenttoken.DocumentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: document.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if n, err = sqlgraph.UpdateNodes(ctx, dtu.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{documenttoken.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// DocumentTokenUpdateOne is the builder for updating a single DocumentToken entity.
|
||||
type DocumentTokenUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *DocumentTokenMutation
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetUpdatedAt(t time.Time) *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.SetUpdatedAt(t)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetToken sets the "token" field.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetToken(b []byte) *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.SetToken(b)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetUses sets the "uses" field.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetUses(i int) *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.ResetUses()
|
||||
dtuo.mutation.SetUses(i)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetNillableUses sets the "uses" field if the given value is not nil.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetNillableUses(i *int) *DocumentTokenUpdateOne {
|
||||
if i != nil {
|
||||
dtuo.SetUses(*i)
|
||||
}
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// AddUses adds i to the "uses" field.
|
||||
func (dtuo *DocumentTokenUpdateOne) AddUses(i int) *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.AddUses(i)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetExpiresAt(t time.Time) *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.SetExpiresAt(t)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetNillableExpiresAt(t *time.Time) *DocumentTokenUpdateOne {
|
||||
if t != nil {
|
||||
dtuo.SetExpiresAt(*t)
|
||||
}
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetDocumentID sets the "document" edge to the Document entity by ID.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetDocumentID(id uuid.UUID) *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.SetDocumentID(id)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetNillableDocumentID sets the "document" edge to the Document entity by ID if the given value is not nil.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetNillableDocumentID(id *uuid.UUID) *DocumentTokenUpdateOne {
|
||||
if id != nil {
|
||||
dtuo = dtuo.SetDocumentID(*id)
|
||||
}
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// SetDocument sets the "document" edge to the Document entity.
|
||||
func (dtuo *DocumentTokenUpdateOne) SetDocument(d *Document) *DocumentTokenUpdateOne {
|
||||
return dtuo.SetDocumentID(d.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the DocumentTokenMutation object of the builder.
|
||||
func (dtuo *DocumentTokenUpdateOne) Mutation() *DocumentTokenMutation {
|
||||
return dtuo.mutation
|
||||
}
|
||||
|
||||
// ClearDocument clears the "document" edge to the Document entity.
|
||||
func (dtuo *DocumentTokenUpdateOne) ClearDocument() *DocumentTokenUpdateOne {
|
||||
dtuo.mutation.ClearDocument()
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (dtuo *DocumentTokenUpdateOne) Select(field string, fields ...string) *DocumentTokenUpdateOne {
|
||||
dtuo.fields = append([]string{field}, fields...)
|
||||
return dtuo
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated DocumentToken entity.
|
||||
func (dtuo *DocumentTokenUpdateOne) Save(ctx context.Context) (*DocumentToken, error) {
|
||||
var (
|
||||
err error
|
||||
node *DocumentToken
|
||||
)
|
||||
dtuo.defaults()
|
||||
if len(dtuo.hooks) == 0 {
|
||||
if err = dtuo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = dtuo.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = dtuo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dtuo.mutation = mutation
|
||||
node, err = dtuo.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(dtuo.hooks) - 1; i >= 0; i-- {
|
||||
if dtuo.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = dtuo.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, dtuo.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*DocumentToken)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from DocumentTokenMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (dtuo *DocumentTokenUpdateOne) SaveX(ctx context.Context) *DocumentToken {
|
||||
node, err := dtuo.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (dtuo *DocumentTokenUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := dtuo.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (dtuo *DocumentTokenUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := dtuo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (dtuo *DocumentTokenUpdateOne) defaults() {
|
||||
if _, ok := dtuo.mutation.UpdatedAt(); !ok {
|
||||
v := documenttoken.UpdateDefaultUpdatedAt()
|
||||
dtuo.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (dtuo *DocumentTokenUpdateOne) check() error {
|
||||
if v, ok := dtuo.mutation.Token(); ok {
|
||||
if err := documenttoken.TokenValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "DocumentToken.token": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dtuo *DocumentTokenUpdateOne) sqlSave(ctx context.Context) (_node *DocumentToken, err error) {
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: documenttoken.Table,
|
||||
Columns: documenttoken.Columns,
|
||||
ID: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: documenttoken.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
id, ok := dtuo.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "DocumentToken.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := dtuo.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, documenttoken.FieldID)
|
||||
for _, f := range fields {
|
||||
if !documenttoken.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != documenttoken.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := dtuo.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := dtuo.mutation.UpdatedAt(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := dtuo.mutation.Token(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldToken,
|
||||
})
|
||||
}
|
||||
if value, ok := dtuo.mutation.Uses(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUses,
|
||||
})
|
||||
}
|
||||
if value, ok := dtuo.mutation.AddedUses(); ok {
|
||||
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldUses,
|
||||
})
|
||||
}
|
||||
if value, ok := dtuo.mutation.ExpiresAt(); ok {
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: documenttoken.FieldExpiresAt,
|
||||
})
|
||||
}
|
||||
if dtuo.mutation.DocumentCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: documenttoken.DocumentTable,
|
||||
Columns: []string{documenttoken.DocumentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: document.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := dtuo.mutation.DocumentIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: documenttoken.DocumentTable,
|
||||
Columns: []string{documenttoken.DocumentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: &sqlgraph.FieldSpec{
|
||||
Type: field.TypeUUID,
|
||||
Column: document.FieldID,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &DocumentToken{config: dtuo.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, dtuo.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{documenttoken.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return _node, nil
|
||||
}
|
||||
@@ -6,42 +6,33 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authroles"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/itemfield"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/attachment"
|
||||
"github.com/hay-kot/homebox/backend/ent/authtokens"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/itemfield"
|
||||
"github.com/hay-kot/homebox/backend/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// ent aliases to avoid import conflicts in user's code.
|
||||
type (
|
||||
Op = ent.Op
|
||||
Hook = ent.Hook
|
||||
Value = ent.Value
|
||||
Query = ent.Query
|
||||
QueryContext = ent.QueryContext
|
||||
Querier = ent.Querier
|
||||
QuerierFunc = ent.QuerierFunc
|
||||
Interceptor = ent.Interceptor
|
||||
InterceptFunc = ent.InterceptFunc
|
||||
Traverser = ent.Traverser
|
||||
TraverseFunc = ent.TraverseFunc
|
||||
Policy = ent.Policy
|
||||
Mutator = ent.Mutator
|
||||
Mutation = ent.Mutation
|
||||
MutateFunc = ent.MutateFunc
|
||||
Op = ent.Op
|
||||
Hook = ent.Hook
|
||||
Value = ent.Value
|
||||
Query = ent.Query
|
||||
Policy = ent.Policy
|
||||
Mutator = ent.Mutator
|
||||
Mutation = ent.Mutation
|
||||
MutateFunc = ent.MutateFunc
|
||||
)
|
||||
|
||||
// OrderFunc applies an ordering on the sql selector.
|
||||
@@ -51,16 +42,15 @@ type OrderFunc func(*sql.Selector)
|
||||
func columnChecker(table string) func(string) error {
|
||||
checks := map[string]func(string) bool{
|
||||
attachment.Table: attachment.ValidColumn,
|
||||
authroles.Table: authroles.ValidColumn,
|
||||
authtokens.Table: authtokens.ValidColumn,
|
||||
document.Table: document.ValidColumn,
|
||||
documenttoken.Table: documenttoken.ValidColumn,
|
||||
group.Table: group.ValidColumn,
|
||||
groupinvitationtoken.Table: groupinvitationtoken.ValidColumn,
|
||||
item.Table: item.ValidColumn,
|
||||
itemfield.Table: itemfield.ValidColumn,
|
||||
label.Table: label.ValidColumn,
|
||||
location.Table: location.ValidColumn,
|
||||
maintenanceentry.Table: maintenanceentry.ValidColumn,
|
||||
user.Table: user.ValidColumn,
|
||||
}
|
||||
check, ok := checks[table]
|
||||
@@ -293,7 +283,6 @@ func IsConstraintError(err error) bool {
|
||||
type selector struct {
|
||||
label string
|
||||
flds *[]string
|
||||
fns []AggregateFunc
|
||||
scan func(context.Context, any) error
|
||||
}
|
||||
|
||||
@@ -492,121 +481,5 @@ func (s *selector) BoolX(ctx context.Context) bool {
|
||||
return v
|
||||
}
|
||||
|
||||
// withHooks invokes the builder operation with the given hooks, if any.
|
||||
func withHooks[V Value, M any, PM interface {
|
||||
*M
|
||||
Mutation
|
||||
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
|
||||
if len(hooks) == 0 {
|
||||
return exec(ctx)
|
||||
}
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutationT, ok := m.(PM)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
// Set the mutation to the builder.
|
||||
*mutation = *mutationT
|
||||
return exec(ctx)
|
||||
})
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
if hooks[i] == nil {
|
||||
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, mutation)
|
||||
if err != nil {
|
||||
return value, err
|
||||
}
|
||||
nv, ok := v.(V)
|
||||
if !ok {
|
||||
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
|
||||
}
|
||||
return nv, nil
|
||||
}
|
||||
|
||||
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
|
||||
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
|
||||
if ent.QueryFromContext(ctx) == nil {
|
||||
qc.Op = op
|
||||
ctx = ent.NewQueryContext(ctx, qc)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func querierAll[V Value, Q interface {
|
||||
sqlAll(context.Context, ...queryHook) (V, error)
|
||||
}]() Querier {
|
||||
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
return query.sqlAll(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func querierCount[Q interface {
|
||||
sqlCount(context.Context) (int, error)
|
||||
}]() Querier {
|
||||
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
return query.sqlCount(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
|
||||
for i := len(inters) - 1; i >= 0; i-- {
|
||||
qr = inters[i].Intercept(qr)
|
||||
}
|
||||
rv, err := qr.Query(ctx, q)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
vt, ok := rv.(V)
|
||||
if !ok {
|
||||
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
|
||||
}
|
||||
return vt, nil
|
||||
}
|
||||
|
||||
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
|
||||
sqlScan(context.Context, Q1, any) error
|
||||
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
|
||||
rv := reflect.ValueOf(v)
|
||||
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q1)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
|
||||
return rv.Elem().Interface(), nil
|
||||
}
|
||||
return v, nil
|
||||
})
|
||||
for i := len(inters) - 1; i >= 0; i-- {
|
||||
qr = inters[i].Intercept(qr)
|
||||
}
|
||||
vv, err := qr.Query(ctx, rootQuery)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch rv2 := reflect.ValueOf(vv); {
|
||||
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
|
||||
case rv.Type() == rv2.Type():
|
||||
rv.Elem().Set(rv2.Elem())
|
||||
case rv.Elem().Type() == rv2.Type():
|
||||
rv.Elem().Set(rv2)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// queryHook describes an internal hook for the different sqlAll methods.
|
||||
type queryHook func(context.Context, *sqlgraph.QuerySpec)
|
||||
@@ -5,12 +5,12 @@ package enttest
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent"
|
||||
"github.com/hay-kot/homebox/backend/ent"
|
||||
// required by schema hooks.
|
||||
_ "github.com/hay-kot/homebox/backend/internal/data/ent/runtime"
|
||||
_ "github.com/hay-kot/homebox/backend/ent/runtime"
|
||||
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/migrate"
|
||||
"github.com/hay-kot/homebox/backend/ent/migrate"
|
||||
)
|
||||
|
||||
type (
|
||||
3
backend/ent/generate.go
Normal file
3
backend/ent/generate.go
Normal file
@@ -0,0 +1,3 @@
|
||||
package ent
|
||||
|
||||
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/versioned-migration ./schema
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
)
|
||||
|
||||
// Group is the model entity for the Group schema.
|
||||
@@ -166,39 +166,39 @@ func (gr *Group) assignValues(columns []string, values []any) error {
|
||||
|
||||
// QueryUsers queries the "users" edge of the Group entity.
|
||||
func (gr *Group) QueryUsers() *UserQuery {
|
||||
return NewGroupClient(gr.config).QueryUsers(gr)
|
||||
return (&GroupClient{config: gr.config}).QueryUsers(gr)
|
||||
}
|
||||
|
||||
// QueryLocations queries the "locations" edge of the Group entity.
|
||||
func (gr *Group) QueryLocations() *LocationQuery {
|
||||
return NewGroupClient(gr.config).QueryLocations(gr)
|
||||
return (&GroupClient{config: gr.config}).QueryLocations(gr)
|
||||
}
|
||||
|
||||
// QueryItems queries the "items" edge of the Group entity.
|
||||
func (gr *Group) QueryItems() *ItemQuery {
|
||||
return NewGroupClient(gr.config).QueryItems(gr)
|
||||
return (&GroupClient{config: gr.config}).QueryItems(gr)
|
||||
}
|
||||
|
||||
// QueryLabels queries the "labels" edge of the Group entity.
|
||||
func (gr *Group) QueryLabels() *LabelQuery {
|
||||
return NewGroupClient(gr.config).QueryLabels(gr)
|
||||
return (&GroupClient{config: gr.config}).QueryLabels(gr)
|
||||
}
|
||||
|
||||
// QueryDocuments queries the "documents" edge of the Group entity.
|
||||
func (gr *Group) QueryDocuments() *DocumentQuery {
|
||||
return NewGroupClient(gr.config).QueryDocuments(gr)
|
||||
return (&GroupClient{config: gr.config}).QueryDocuments(gr)
|
||||
}
|
||||
|
||||
// QueryInvitationTokens queries the "invitation_tokens" edge of the Group entity.
|
||||
func (gr *Group) QueryInvitationTokens() *GroupInvitationTokenQuery {
|
||||
return NewGroupClient(gr.config).QueryInvitationTokens(gr)
|
||||
return (&GroupClient{config: gr.config}).QueryInvitationTokens(gr)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Group.
|
||||
// Note that you need to call Group.Unwrap() before calling this method if this Group
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (gr *Group) Update() *GroupUpdateOne {
|
||||
return NewGroupClient(gr.config).UpdateOne(gr)
|
||||
return (&GroupClient{config: gr.config}).UpdateOne(gr)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Group entity that was returned from a transaction after it was closed,
|
||||
@@ -121,17 +121,6 @@ const DefaultCurrency = CurrencyUsd
|
||||
// Currency values.
|
||||
const (
|
||||
CurrencyUsd Currency = "usd"
|
||||
CurrencyEur Currency = "eur"
|
||||
CurrencyGbp Currency = "gbp"
|
||||
CurrencyJpy Currency = "jpy"
|
||||
CurrencyZar Currency = "zar"
|
||||
CurrencyAud Currency = "aud"
|
||||
CurrencyNok Currency = "nok"
|
||||
CurrencySek Currency = "sek"
|
||||
CurrencyDkk Currency = "dkk"
|
||||
CurrencyInr Currency = "inr"
|
||||
CurrencyRmb Currency = "rmb"
|
||||
CurrencyBgn Currency = "bgn"
|
||||
)
|
||||
|
||||
func (c Currency) String() string {
|
||||
@@ -141,7 +130,7 @@ func (c Currency) String() string {
|
||||
// CurrencyValidator is a validator for the "currency" field enum values. It is called by the builders before save.
|
||||
func CurrencyValidator(c Currency) error {
|
||||
switch c {
|
||||
case CurrencyUsd, CurrencyEur, CurrencyGbp, CurrencyJpy, CurrencyZar, CurrencyAud, CurrencyNok, CurrencySek, CurrencyDkk, CurrencyInr, CurrencyRmb, CurrencyBgn:
|
||||
case CurrencyUsd:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("group: invalid enum value for currency field: %q", c)
|
||||
@@ -8,232 +8,362 @@ import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldID, ids...))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.In(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.NotIn(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldGT(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldGTE(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldLT(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.Group {
|
||||
return predicate.Group(sql.FieldLTE(FieldID, id))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
|
||||
func Name(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldGT(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldGTE(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldLT(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldLTE(FieldCreatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldGT(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldLT(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.Group {
|
||||
return predicate.Group(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameEQ applies the EQ predicate on the "name" field.
|
||||
func NameEQ(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameNEQ applies the NEQ predicate on the "name" field.
|
||||
func NameNEQ(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameIn applies the In predicate on the "name" field.
|
||||
func NameIn(vs ...string) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldName, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldName), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// NameNotIn applies the NotIn predicate on the "name" field.
|
||||
func NameNotIn(vs ...string) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldName), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// NameGT applies the GT predicate on the "name" field.
|
||||
func NameGT(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldGT(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameGTE applies the GTE predicate on the "name" field.
|
||||
func NameGTE(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldGTE(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameLT applies the LT predicate on the "name" field.
|
||||
func NameLT(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldLT(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameLTE applies the LTE predicate on the "name" field.
|
||||
func NameLTE(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldLTE(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameContains applies the Contains predicate on the "name" field.
|
||||
func NameContains(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldContains(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.Contains(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
|
||||
func NameHasPrefix(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.HasPrefix(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
|
||||
func NameHasSuffix(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.HasSuffix(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldEqualFold(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EqualFold(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// NameContainsFold applies the ContainsFold predicate on the "name" field.
|
||||
func NameContainsFold(v string) predicate.Group {
|
||||
return predicate.Group(sql.FieldContainsFold(FieldName, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.ContainsFold(s.C(FieldName), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CurrencyEQ applies the EQ predicate on the "currency" field.
|
||||
func CurrencyEQ(v Currency) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldCurrency, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCurrency), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CurrencyNEQ applies the NEQ predicate on the "currency" field.
|
||||
func CurrencyNEQ(v Currency) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldCurrency, v))
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCurrency), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CurrencyIn applies the In predicate on the "currency" field.
|
||||
func CurrencyIn(vs ...Currency) predicate.Group {
|
||||
return predicate.Group(sql.FieldIn(FieldCurrency, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCurrency), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CurrencyNotIn applies the NotIn predicate on the "currency" field.
|
||||
func CurrencyNotIn(vs ...Currency) predicate.Group {
|
||||
return predicate.Group(sql.FieldNotIn(FieldCurrency, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCurrency), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// HasUsers applies the HasEdge predicate on the "users" edge.
|
||||
@@ -241,6 +371,7 @@ func HasUsers() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(UsersTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -268,6 +399,7 @@ func HasLocations() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(LocationsTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, LocationsTable, LocationsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -295,6 +427,7 @@ func HasItems() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(ItemsTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -322,6 +455,7 @@ func HasLabels() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(LabelsTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, LabelsTable, LabelsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -349,6 +483,7 @@ func HasDocuments() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(DocumentsTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, DocumentsTable, DocumentsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -376,6 +511,7 @@ func HasInvitationTokens() predicate.Group {
|
||||
return predicate.Group(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(InvitationTokensTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, InvitationTokensTable, InvitationTokensColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -11,13 +11,13 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// GroupCreate is the builder for creating a Group entity.
|
||||
@@ -186,8 +186,50 @@ func (gc *GroupCreate) Mutation() *GroupMutation {
|
||||
|
||||
// Save creates the Group in the database.
|
||||
func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) {
|
||||
var (
|
||||
err error
|
||||
node *Group
|
||||
)
|
||||
gc.defaults()
|
||||
return withHooks[*Group, GroupMutation](ctx, gc.sqlSave, gc.mutation, gc.hooks)
|
||||
if len(gc.hooks) == 0 {
|
||||
if err = gc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = gc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*GroupMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = gc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gc.mutation = mutation
|
||||
if node, err = gc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(gc.hooks) - 1; i >= 0; i-- {
|
||||
if gc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = gc.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, gc.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Group)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from GroupMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
@@ -260,9 +302,6 @@ func (gc *GroupCreate) check() error {
|
||||
}
|
||||
|
||||
func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
|
||||
if err := gc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := gc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
@@ -277,8 +316,6 @@ func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
gc.mutation.id = &_node.ID
|
||||
gc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
@@ -298,19 +335,35 @@ func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := gc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(group.FieldCreatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: group.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := gc.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(group.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: group.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := gc.mutation.Name(); ok {
|
||||
_spec.SetField(group.FieldName, field.TypeString, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: group.FieldName,
|
||||
})
|
||||
_node.Name = value
|
||||
}
|
||||
if value, ok := gc.mutation.Currency(); ok {
|
||||
_spec.SetField(group.FieldCurrency, field.TypeEnum, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeEnum,
|
||||
Value: value,
|
||||
Column: group.FieldCurrency,
|
||||
})
|
||||
_node.Currency = value
|
||||
}
|
||||
if nodes := gc.mutation.UsersIDs(); len(nodes) > 0 {
|
||||
@@ -4,12 +4,13 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// GroupDelete is the builder for deleting a Group entity.
|
||||
@@ -27,7 +28,34 @@ func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (gd *GroupDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks[int, GroupMutation](ctx, gd.sqlExec, gd.mutation, gd.hooks)
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
if len(gd.hooks) == 0 {
|
||||
affected, err = gd.sqlExec(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*GroupMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
gd.mutation = mutation
|
||||
affected, err = gd.sqlExec(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(gd.hooks) - 1; i >= 0; i-- {
|
||||
if gd.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = gd.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, gd.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
@@ -60,7 +88,6 @@ func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
gd.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
@@ -69,12 +96,6 @@ type GroupDeleteOne struct {
|
||||
gd *GroupDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the GroupDelete builder.
|
||||
func (gdo *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne {
|
||||
gdo.gd.mutation.Where(ps...)
|
||||
return gdo
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (gdo *GroupDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := gdo.gd.Exec(ctx)
|
||||
@@ -90,7 +111,5 @@ func (gdo *GroupDeleteOne) Exec(ctx context.Context) error {
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (gdo *GroupDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := gdo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
gdo.gd.ExecX(ctx)
|
||||
}
|
||||
@@ -12,22 +12,24 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// GroupQuery is the builder for querying Group entities.
|
||||
type GroupQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
limit *int
|
||||
offset *int
|
||||
unique *bool
|
||||
order []OrderFunc
|
||||
inters []Interceptor
|
||||
fields []string
|
||||
predicates []predicate.Group
|
||||
withUsers *UserQuery
|
||||
withLocations *LocationQuery
|
||||
@@ -46,26 +48,26 @@ func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
|
||||
return gq
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
// Limit adds a limit step to the query.
|
||||
func (gq *GroupQuery) Limit(limit int) *GroupQuery {
|
||||
gq.ctx.Limit = &limit
|
||||
gq.limit = &limit
|
||||
return gq
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
// Offset adds an offset step to the query.
|
||||
func (gq *GroupQuery) Offset(offset int) *GroupQuery {
|
||||
gq.ctx.Offset = &offset
|
||||
gq.offset = &offset
|
||||
return gq
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (gq *GroupQuery) Unique(unique bool) *GroupQuery {
|
||||
gq.ctx.Unique = &unique
|
||||
gq.unique = &unique
|
||||
return gq
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
// Order adds an order step to the query.
|
||||
func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery {
|
||||
gq.order = append(gq.order, o...)
|
||||
return gq
|
||||
@@ -73,7 +75,7 @@ func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery {
|
||||
|
||||
// QueryUsers chains the current query on the "users" edge.
|
||||
func (gq *GroupQuery) QueryUsers() *UserQuery {
|
||||
query := (&UserClient{config: gq.config}).Query()
|
||||
query := &UserQuery{config: gq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -95,7 +97,7 @@ func (gq *GroupQuery) QueryUsers() *UserQuery {
|
||||
|
||||
// QueryLocations chains the current query on the "locations" edge.
|
||||
func (gq *GroupQuery) QueryLocations() *LocationQuery {
|
||||
query := (&LocationClient{config: gq.config}).Query()
|
||||
query := &LocationQuery{config: gq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -117,7 +119,7 @@ func (gq *GroupQuery) QueryLocations() *LocationQuery {
|
||||
|
||||
// QueryItems chains the current query on the "items" edge.
|
||||
func (gq *GroupQuery) QueryItems() *ItemQuery {
|
||||
query := (&ItemClient{config: gq.config}).Query()
|
||||
query := &ItemQuery{config: gq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -139,7 +141,7 @@ func (gq *GroupQuery) QueryItems() *ItemQuery {
|
||||
|
||||
// QueryLabels chains the current query on the "labels" edge.
|
||||
func (gq *GroupQuery) QueryLabels() *LabelQuery {
|
||||
query := (&LabelClient{config: gq.config}).Query()
|
||||
query := &LabelQuery{config: gq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -161,7 +163,7 @@ func (gq *GroupQuery) QueryLabels() *LabelQuery {
|
||||
|
||||
// QueryDocuments chains the current query on the "documents" edge.
|
||||
func (gq *GroupQuery) QueryDocuments() *DocumentQuery {
|
||||
query := (&DocumentClient{config: gq.config}).Query()
|
||||
query := &DocumentQuery{config: gq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -183,7 +185,7 @@ func (gq *GroupQuery) QueryDocuments() *DocumentQuery {
|
||||
|
||||
// QueryInvitationTokens chains the current query on the "invitation_tokens" edge.
|
||||
func (gq *GroupQuery) QueryInvitationTokens() *GroupInvitationTokenQuery {
|
||||
query := (&GroupInvitationTokenClient{config: gq.config}).Query()
|
||||
query := &GroupInvitationTokenQuery{config: gq.config}
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -206,7 +208,7 @@ func (gq *GroupQuery) QueryInvitationTokens() *GroupInvitationTokenQuery {
|
||||
// First returns the first Group entity from the query.
|
||||
// Returns a *NotFoundError when no Group was found.
|
||||
func (gq *GroupQuery) First(ctx context.Context) (*Group, error) {
|
||||
nodes, err := gq.Limit(1).All(setContextOp(ctx, gq.ctx, "First"))
|
||||
nodes, err := gq.Limit(1).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -229,7 +231,7 @@ func (gq *GroupQuery) FirstX(ctx context.Context) *Group {
|
||||
// Returns a *NotFoundError when no Group ID was found.
|
||||
func (gq *GroupQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = gq.Limit(1).IDs(setContextOp(ctx, gq.ctx, "FirstID")); err != nil {
|
||||
if ids, err = gq.Limit(1).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
@@ -252,7 +254,7 @@ func (gq *GroupQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
// Returns a *NotSingularError when more than one Group entity is found.
|
||||
// Returns a *NotFoundError when no Group entities are found.
|
||||
func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) {
|
||||
nodes, err := gq.Limit(2).All(setContextOp(ctx, gq.ctx, "Only"))
|
||||
nodes, err := gq.Limit(2).All(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -280,7 +282,7 @@ func (gq *GroupQuery) OnlyX(ctx context.Context) *Group {
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (gq *GroupQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = gq.Limit(2).IDs(setContextOp(ctx, gq.ctx, "OnlyID")); err != nil {
|
||||
if ids, err = gq.Limit(2).IDs(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
@@ -305,12 +307,10 @@ func (gq *GroupQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
|
||||
// All executes the query and returns a list of Groups.
|
||||
func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) {
|
||||
ctx = setContextOp(ctx, gq.ctx, "All")
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Group, *GroupQuery]()
|
||||
return withInterceptors[[]*Group](ctx, gq, qr, gq.inters)
|
||||
return gq.sqlAll(ctx)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
@@ -325,7 +325,6 @@ func (gq *GroupQuery) AllX(ctx context.Context) []*Group {
|
||||
// IDs executes the query and returns a list of Group IDs.
|
||||
func (gq *GroupQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
var ids []uuid.UUID
|
||||
ctx = setContextOp(ctx, gq.ctx, "IDs")
|
||||
if err := gq.Select(group.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -343,11 +342,10 @@ func (gq *GroupQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (gq *GroupQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, gq.ctx, "Count")
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, gq, querierCount[*GroupQuery](), gq.inters)
|
||||
return gq.sqlCount(ctx)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
@@ -361,15 +359,10 @@ func (gq *GroupQuery) CountX(ctx context.Context) int {
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, gq.ctx, "Exist")
|
||||
switch _, err := gq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return gq.sqlExist(ctx)
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
@@ -389,9 +382,9 @@ func (gq *GroupQuery) Clone() *GroupQuery {
|
||||
}
|
||||
return &GroupQuery{
|
||||
config: gq.config,
|
||||
ctx: gq.ctx.Clone(),
|
||||
limit: gq.limit,
|
||||
offset: gq.offset,
|
||||
order: append([]OrderFunc{}, gq.order...),
|
||||
inters: append([]Interceptor{}, gq.inters...),
|
||||
predicates: append([]predicate.Group{}, gq.predicates...),
|
||||
withUsers: gq.withUsers.Clone(),
|
||||
withLocations: gq.withLocations.Clone(),
|
||||
@@ -400,15 +393,16 @@ func (gq *GroupQuery) Clone() *GroupQuery {
|
||||
withDocuments: gq.withDocuments.Clone(),
|
||||
withInvitationTokens: gq.withInvitationTokens.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: gq.sql.Clone(),
|
||||
path: gq.path,
|
||||
sql: gq.sql.Clone(),
|
||||
path: gq.path,
|
||||
unique: gq.unique,
|
||||
}
|
||||
}
|
||||
|
||||
// WithUsers tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
|
||||
query := (&UserClient{config: gq.config}).Query()
|
||||
query := &UserQuery{config: gq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -419,7 +413,7 @@ func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
|
||||
// WithLocations tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "locations" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (gq *GroupQuery) WithLocations(opts ...func(*LocationQuery)) *GroupQuery {
|
||||
query := (&LocationClient{config: gq.config}).Query()
|
||||
query := &LocationQuery{config: gq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -430,7 +424,7 @@ func (gq *GroupQuery) WithLocations(opts ...func(*LocationQuery)) *GroupQuery {
|
||||
// WithItems tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (gq *GroupQuery) WithItems(opts ...func(*ItemQuery)) *GroupQuery {
|
||||
query := (&ItemClient{config: gq.config}).Query()
|
||||
query := &ItemQuery{config: gq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -441,7 +435,7 @@ func (gq *GroupQuery) WithItems(opts ...func(*ItemQuery)) *GroupQuery {
|
||||
// WithLabels tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "labels" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (gq *GroupQuery) WithLabels(opts ...func(*LabelQuery)) *GroupQuery {
|
||||
query := (&LabelClient{config: gq.config}).Query()
|
||||
query := &LabelQuery{config: gq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -452,7 +446,7 @@ func (gq *GroupQuery) WithLabels(opts ...func(*LabelQuery)) *GroupQuery {
|
||||
// WithDocuments tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "documents" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (gq *GroupQuery) WithDocuments(opts ...func(*DocumentQuery)) *GroupQuery {
|
||||
query := (&DocumentClient{config: gq.config}).Query()
|
||||
query := &DocumentQuery{config: gq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -463,7 +457,7 @@ func (gq *GroupQuery) WithDocuments(opts ...func(*DocumentQuery)) *GroupQuery {
|
||||
// WithInvitationTokens tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "invitation_tokens" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (gq *GroupQuery) WithInvitationTokens(opts ...func(*GroupInvitationTokenQuery)) *GroupQuery {
|
||||
query := (&GroupInvitationTokenClient{config: gq.config}).Query()
|
||||
query := &GroupInvitationTokenQuery{config: gq.config}
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
@@ -486,11 +480,16 @@ func (gq *GroupQuery) WithInvitationTokens(opts ...func(*GroupInvitationTokenQue
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
|
||||
gq.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &GroupGroupBy{build: gq}
|
||||
grbuild.flds = &gq.ctx.Fields
|
||||
grbuild := &GroupGroupBy{config: gq.config}
|
||||
grbuild.fields = append([]string{field}, fields...)
|
||||
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
|
||||
if err := gq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gq.sqlQuery(ctx), nil
|
||||
}
|
||||
grbuild.label = group.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
@@ -507,30 +506,15 @@ func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
|
||||
// Select(group.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (gq *GroupQuery) Select(fields ...string) *GroupSelect {
|
||||
gq.ctx.Fields = append(gq.ctx.Fields, fields...)
|
||||
sbuild := &GroupSelect{GroupQuery: gq}
|
||||
sbuild.label = group.Label
|
||||
sbuild.flds, sbuild.scan = &gq.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a GroupSelect configured with the given aggregations.
|
||||
func (gq *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect {
|
||||
return gq.Select().Aggregate(fns...)
|
||||
gq.fields = append(gq.fields, fields...)
|
||||
selbuild := &GroupSelect{GroupQuery: gq}
|
||||
selbuild.label = group.Label
|
||||
selbuild.flds, selbuild.scan = &gq.fields, selbuild.Scan
|
||||
return selbuild
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range gq.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, gq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range gq.ctx.Fields {
|
||||
for _, f := range gq.fields {
|
||||
if !group.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
@@ -812,13 +796,24 @@ func (gq *GroupQuery) loadInvitationTokens(ctx context.Context, query *GroupInvi
|
||||
|
||||
func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := gq.querySpec()
|
||||
_spec.Node.Columns = gq.ctx.Fields
|
||||
if len(gq.ctx.Fields) > 0 {
|
||||
_spec.Unique = gq.ctx.Unique != nil && *gq.ctx.Unique
|
||||
_spec.Node.Columns = gq.fields
|
||||
if len(gq.fields) > 0 {
|
||||
_spec.Unique = gq.unique != nil && *gq.unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, gq.driver, _spec)
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) sqlExist(ctx context.Context) (bool, error) {
|
||||
switch _, err := gq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := &sqlgraph.QuerySpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
@@ -832,10 +827,10 @@ func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
From: gq.sql,
|
||||
Unique: true,
|
||||
}
|
||||
if unique := gq.ctx.Unique; unique != nil {
|
||||
if unique := gq.unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
}
|
||||
if fields := gq.ctx.Fields; len(fields) > 0 {
|
||||
if fields := gq.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
|
||||
for i := range fields {
|
||||
@@ -851,10 +846,10 @@ func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := gq.ctx.Limit; limit != nil {
|
||||
if limit := gq.limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := gq.ctx.Offset; offset != nil {
|
||||
if offset := gq.offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := gq.order; len(ps) > 0 {
|
||||
@@ -870,7 +865,7 @@ func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(gq.driver.Dialect())
|
||||
t1 := builder.Table(group.Table)
|
||||
columns := gq.ctx.Fields
|
||||
columns := gq.fields
|
||||
if len(columns) == 0 {
|
||||
columns = group.Columns
|
||||
}
|
||||
@@ -879,7 +874,7 @@ func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
selector = gq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if gq.ctx.Unique != nil && *gq.ctx.Unique {
|
||||
if gq.unique != nil && *gq.unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range gq.predicates {
|
||||
@@ -888,12 +883,12 @@ func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
for _, p := range gq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := gq.ctx.Offset; offset != nil {
|
||||
if offset := gq.offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := gq.ctx.Limit; limit != nil {
|
||||
if limit := gq.limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
@@ -901,8 +896,13 @@ func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
|
||||
// GroupGroupBy is the group-by builder for Group entities.
|
||||
type GroupGroupBy struct {
|
||||
config
|
||||
selector
|
||||
build *GroupQuery
|
||||
fields []string
|
||||
fns []AggregateFunc
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
@@ -911,77 +911,74 @@ func (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
|
||||
return ggb
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
// Scan applies the group-by query and scans the result into the given value.
|
||||
func (ggb *GroupGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, ggb.build.ctx, "GroupBy")
|
||||
if err := ggb.build.prepareQuery(ctx); err != nil {
|
||||
query, err := ggb.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*GroupQuery, *GroupGroupBy](ctx, ggb.build, ggb, ggb.build.inters, v)
|
||||
ggb.sql = query
|
||||
return ggb.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (ggb *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(ggb.fns))
|
||||
for _, fn := range ggb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*ggb.flds)+len(ggb.fns))
|
||||
for _, f := range *ggb.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
func (ggb *GroupGroupBy) sqlScan(ctx context.Context, v any) error {
|
||||
for _, f := range ggb.fields {
|
||||
if !group.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*ggb.flds...)...)
|
||||
selector := ggb.sqlQuery()
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := ggb.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
if err := ggb.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
func (ggb *GroupGroupBy) sqlQuery() *sql.Selector {
|
||||
selector := ggb.sql.Select()
|
||||
aggregation := make([]string, 0, len(ggb.fns))
|
||||
for _, fn := range ggb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
// If no columns were selected in a custom aggregation function, the default
|
||||
// selection is the fields used for "group-by", and the aggregation functions.
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(ggb.fields)+len(ggb.fns))
|
||||
for _, f := range ggb.fields {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
return selector.GroupBy(selector.Columns(ggb.fields...)...)
|
||||
}
|
||||
|
||||
// GroupSelect is the builder for selecting fields of Group entities.
|
||||
type GroupSelect struct {
|
||||
*GroupQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (gs *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect {
|
||||
gs.fns = append(gs.fns, fns...)
|
||||
return gs
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (gs *GroupSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, gs.ctx, "Select")
|
||||
if err := gs.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*GroupQuery, *GroupSelect](ctx, gs.GroupQuery, gs, gs.inters, v)
|
||||
gs.sql = gs.GroupQuery.sqlQuery(ctx)
|
||||
return gs.sqlScan(ctx, v)
|
||||
}
|
||||
|
||||
func (gs *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(gs.fns))
|
||||
for _, fn := range gs.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*gs.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
func (gs *GroupSelect) sqlScan(ctx context.Context, v any) error {
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
query, args := gs.sql.Query()
|
||||
if err := gs.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -12,14 +12,14 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
|
||||
"github.com/hay-kot/homebox/backend/ent/document"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/item"
|
||||
"github.com/hay-kot/homebox/backend/ent/label"
|
||||
"github.com/hay-kot/homebox/backend/ent/location"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/user"
|
||||
)
|
||||
|
||||
// GroupUpdate is the builder for updating Group entities.
|
||||
@@ -284,8 +284,41 @@ func (gu *GroupUpdate) RemoveInvitationTokens(g ...*GroupInvitationToken) *Group
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (gu *GroupUpdate) Save(ctx context.Context) (int, error) {
|
||||
var (
|
||||
err error
|
||||
affected int
|
||||
)
|
||||
gu.defaults()
|
||||
return withHooks[int, GroupMutation](ctx, gu.sqlSave, gu.mutation, gu.hooks)
|
||||
if len(gu.hooks) == 0 {
|
||||
if err = gu.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, err = gu.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*GroupMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = gu.check(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
gu.mutation = mutation
|
||||
affected, err = gu.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return affected, err
|
||||
})
|
||||
for i := len(gu.hooks) - 1; i >= 0; i-- {
|
||||
if gu.hooks[i] == nil {
|
||||
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = gu.hooks[i](mut)
|
||||
}
|
||||
if _, err := mut.Mutate(ctx, gu.mutation); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -334,9 +367,6 @@ func (gu *GroupUpdate) check() error {
|
||||
}
|
||||
|
||||
func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if err := gu.check(); err != nil {
|
||||
return n, err
|
||||
}
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: group.Table,
|
||||
@@ -355,13 +385,25 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
}
|
||||
if value, ok := gu.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(group.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: group.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := gu.mutation.Name(); ok {
|
||||
_spec.SetField(group.FieldName, field.TypeString, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: group.FieldName,
|
||||
})
|
||||
}
|
||||
if value, ok := gu.mutation.Currency(); ok {
|
||||
_spec.SetField(group.FieldCurrency, field.TypeEnum, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeEnum,
|
||||
Value: value,
|
||||
Column: group.FieldCurrency,
|
||||
})
|
||||
}
|
||||
if gu.mutation.UsersCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -695,7 +737,6 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
gu.mutation.done = true
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@@ -963,8 +1004,47 @@ func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOn
|
||||
|
||||
// Save executes the query and returns the updated Group entity.
|
||||
func (guo *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
|
||||
var (
|
||||
err error
|
||||
node *Group
|
||||
)
|
||||
guo.defaults()
|
||||
return withHooks[*Group, GroupMutation](ctx, guo.sqlSave, guo.mutation, guo.hooks)
|
||||
if len(guo.hooks) == 0 {
|
||||
if err = guo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = guo.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*GroupMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = guo.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
guo.mutation = mutation
|
||||
node, err = guo.sqlSave(ctx)
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(guo.hooks) - 1; i >= 0; i-- {
|
||||
if guo.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = guo.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, guo.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Group)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from GroupMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
@@ -1013,9 +1093,6 @@ func (guo *GroupUpdateOne) check() error {
|
||||
}
|
||||
|
||||
func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) {
|
||||
if err := guo.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := &sqlgraph.UpdateSpec{
|
||||
Node: &sqlgraph.NodeSpec{
|
||||
Table: group.Table,
|
||||
@@ -1051,13 +1128,25 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error
|
||||
}
|
||||
}
|
||||
if value, ok := guo.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(group.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: group.FieldUpdatedAt,
|
||||
})
|
||||
}
|
||||
if value, ok := guo.mutation.Name(); ok {
|
||||
_spec.SetField(group.FieldName, field.TypeString, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeString,
|
||||
Value: value,
|
||||
Column: group.FieldName,
|
||||
})
|
||||
}
|
||||
if value, ok := guo.mutation.Currency(); ok {
|
||||
_spec.SetField(group.FieldCurrency, field.TypeEnum, value)
|
||||
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeEnum,
|
||||
Value: value,
|
||||
Column: group.FieldCurrency,
|
||||
})
|
||||
}
|
||||
if guo.mutation.UsersCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
@@ -1394,6 +1483,5 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
guo.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
|
||||
)
|
||||
|
||||
// GroupInvitationToken is the model entity for the GroupInvitationToken schema.
|
||||
@@ -136,14 +136,14 @@ func (git *GroupInvitationToken) assignValues(columns []string, values []any) er
|
||||
|
||||
// QueryGroup queries the "group" edge of the GroupInvitationToken entity.
|
||||
func (git *GroupInvitationToken) QueryGroup() *GroupQuery {
|
||||
return NewGroupInvitationTokenClient(git.config).QueryGroup(git)
|
||||
return (&GroupInvitationTokenClient{config: git.config}).QueryGroup(git)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this GroupInvitationToken.
|
||||
// Note that you need to call GroupInvitationToken.Unwrap() before calling this method if this GroupInvitationToken
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (git *GroupInvitationToken) Update() *GroupInvitationTokenUpdateOne {
|
||||
return NewGroupInvitationTokenClient(git.config).UpdateOne(git)
|
||||
return (&GroupInvitationTokenClient{config: git.config}).UpdateOne(git)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the GroupInvitationToken entity that was returned from a transaction after it was closed,
|
||||
@@ -8,277 +8,433 @@ import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
|
||||
"github.com/hay-kot/homebox/backend/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNEQ(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldIn(FieldID, ids...))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.In(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNotIn(FieldID, ids...))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
v := make([]any, len(ids))
|
||||
for i := range v {
|
||||
v[i] = ids[i]
|
||||
}
|
||||
s.Where(sql.NotIn(s.C(FieldID), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGT(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGTE(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLT(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLTE(FieldID, id))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldID), id))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
|
||||
func Token(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
|
||||
func ExpiresAt(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// Uses applies equality check predicate on the "uses" field. It's identical to UsesEQ.
|
||||
func Uses(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGT(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGTE(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLT(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLTE(FieldCreatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGT(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLT(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenEQ applies the EQ predicate on the "token" field.
|
||||
func TokenEQ(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenNEQ applies the NEQ predicate on the "token" field.
|
||||
func TokenNEQ(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNEQ(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenIn applies the In predicate on the "token" field.
|
||||
func TokenIn(vs ...[]byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldIn(FieldToken, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldToken), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenNotIn applies the NotIn predicate on the "token" field.
|
||||
func TokenNotIn(vs ...[]byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNotIn(FieldToken, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldToken), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenGT applies the GT predicate on the "token" field.
|
||||
func TokenGT(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGT(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenGTE applies the GTE predicate on the "token" field.
|
||||
func TokenGTE(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGTE(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenLT applies the LT predicate on the "token" field.
|
||||
func TokenLT(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLT(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// TokenLTE applies the LTE predicate on the "token" field.
|
||||
func TokenLTE(v []byte) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLTE(FieldToken, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldToken), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
|
||||
func ExpiresAtEQ(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
|
||||
func ExpiresAtNEQ(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNEQ(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtIn applies the In predicate on the "expires_at" field.
|
||||
func ExpiresAtIn(vs ...time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldIn(FieldExpiresAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldExpiresAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
|
||||
func ExpiresAtNotIn(vs ...time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNotIn(FieldExpiresAt, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
|
||||
func ExpiresAtGT(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGT(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
|
||||
func ExpiresAtGTE(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGTE(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
|
||||
func ExpiresAtLT(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLT(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
|
||||
func ExpiresAtLTE(v time.Time) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLTE(FieldExpiresAt, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesEQ applies the EQ predicate on the "uses" field.
|
||||
func UsesEQ(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldEQ(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.EQ(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesNEQ applies the NEQ predicate on the "uses" field.
|
||||
func UsesNEQ(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNEQ(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NEQ(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesIn applies the In predicate on the "uses" field.
|
||||
func UsesIn(vs ...int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldIn(FieldUses, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.In(s.C(FieldUses), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesNotIn applies the NotIn predicate on the "uses" field.
|
||||
func UsesNotIn(vs ...int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldNotIn(FieldUses, vs...))
|
||||
v := make([]any, len(vs))
|
||||
for i := range v {
|
||||
v[i] = vs[i]
|
||||
}
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.NotIn(s.C(FieldUses), v...))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesGT applies the GT predicate on the "uses" field.
|
||||
func UsesGT(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGT(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GT(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesGTE applies the GTE predicate on the "uses" field.
|
||||
func UsesGTE(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldGTE(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.GTE(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesLT applies the LT predicate on the "uses" field.
|
||||
func UsesLT(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLT(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LT(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// UsesLTE applies the LTE predicate on the "uses" field.
|
||||
func UsesLTE(v int) predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(sql.FieldLTE(FieldUses, v))
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
s.Where(sql.LTE(s.C(FieldUses), v))
|
||||
})
|
||||
}
|
||||
|
||||
// HasGroup applies the HasEdge predicate on the "group" edge.
|
||||
@@ -286,6 +442,7 @@ func HasGroup() predicate.GroupInvitationToken {
|
||||
return predicate.GroupInvitationToken(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(GroupTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
|
||||
"github.com/hay-kot/homebox/backend/ent/group"
|
||||
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
|
||||
)
|
||||
|
||||
// GroupInvitationTokenCreate is the builder for creating a GroupInvitationToken entity.
|
||||
@@ -124,8 +124,50 @@ func (gitc *GroupInvitationTokenCreate) Mutation() *GroupInvitationTokenMutation
|
||||
|
||||
// Save creates the GroupInvitationToken in the database.
|
||||
func (gitc *GroupInvitationTokenCreate) Save(ctx context.Context) (*GroupInvitationToken, error) {
|
||||
var (
|
||||
err error
|
||||
node *GroupInvitationToken
|
||||
)
|
||||
gitc.defaults()
|
||||
return withHooks[*GroupInvitationToken, GroupInvitationTokenMutation](ctx, gitc.sqlSave, gitc.mutation, gitc.hooks)
|
||||
if len(gitc.hooks) == 0 {
|
||||
if err = gitc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = gitc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*GroupInvitationTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = gitc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gitc.mutation = mutation
|
||||
if node, err = gitc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(gitc.hooks) - 1; i >= 0; i-- {
|
||||
if gitc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = gitc.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, gitc.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*GroupInvitationToken)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from GroupInvitationTokenMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
@@ -195,9 +237,6 @@ func (gitc *GroupInvitationTokenCreate) check() error {
|
||||
}
|
||||
|
||||
func (gitc *GroupInvitationTokenCreate) sqlSave(ctx context.Context) (*GroupInvitationToken, error) {
|
||||
if err := gitc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := gitc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, gitc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
@@ -212,8 +251,6 @@ func (gitc *GroupInvitationTokenCreate) sqlSave(ctx context.Context) (*GroupInvi
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
gitc.mutation.id = &_node.ID
|
||||
gitc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
@@ -233,23 +270,43 @@ func (gitc *GroupInvitationTokenCreate) createSpec() (*GroupInvitationToken, *sq
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := gitc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(groupinvitationtoken.FieldCreatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: groupinvitationtoken.FieldCreatedAt,
|
||||
})
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := gitc.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(groupinvitationtoken.FieldUpdatedAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: groupinvitationtoken.FieldUpdatedAt,
|
||||
})
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := gitc.mutation.Token(); ok {
|
||||
_spec.SetField(groupinvitationtoken.FieldToken, field.TypeBytes, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeBytes,
|
||||
Value: value,
|
||||
Column: groupinvitationtoken.FieldToken,
|
||||
})
|
||||
_node.Token = value
|
||||
}
|
||||
if value, ok := gitc.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(groupinvitationtoken.FieldExpiresAt, field.TypeTime, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeTime,
|
||||
Value: value,
|
||||
Column: groupinvitationtoken.FieldExpiresAt,
|
||||
})
|
||||
_node.ExpiresAt = value
|
||||
}
|
||||
if value, ok := gitc.mutation.Uses(); ok {
|
||||
_spec.SetField(groupinvitationtoken.FieldUses, field.TypeInt, value)
|
||||
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
|
||||
Type: field.TypeInt,
|
||||
Value: value,
|
||||
Column: groupinvitationtoken.FieldUses,
|
||||
})
|
||||
_node.Uses = value
|
||||
}
|
||||
if nodes := gitc.mutation.GroupIDs(); len(nodes) > 0 {
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user