* add handlers for signin,singup,logout... * introduce ent ORM and add user schema * add live mode, devel mode to selectively turn on features via config/flags * add templates, handle embedding moar smarter: * live mode uses live folder structure, else embedded templates are used * start using tailwindcss to style stuff * add development goodies for hot-reloading (browser-sync - bs.js) * pimp-up config.dhall with actual custom config Type (enables remote schema and local values only as needed) * add justfile (alternative to makefile for process automation)
This commit is contained in:
parent
fee253b79e
commit
f129606b8f
32
.drone.yml
32
.drone.yml
@ -55,9 +55,21 @@ steps:
|
||||
commands:
|
||||
- go vet ./...
|
||||
|
||||
- name: go build
|
||||
- name: npm i
|
||||
image: docker.io/immawanderer/archlinux-go:linux-amd64
|
||||
depends_on: [go fmt, go vet]
|
||||
volumes:
|
||||
- name: gopath
|
||||
path: /go
|
||||
commands:
|
||||
- mkdir -pv static
|
||||
- pacman -Sy && pacman -S --noconfirm --needed npm
|
||||
- npm i
|
||||
- npx tailwindcss -i ./assets/input.css -o ./static/pcmt.css --minify
|
||||
|
||||
- name: go build
|
||||
image: docker.io/immawanderer/archlinux-go:linux-amd64
|
||||
depends_on: [go fmt, go vet, npm i]
|
||||
volumes:
|
||||
- name: gopath
|
||||
path: /go
|
||||
@ -66,7 +78,7 @@ steps:
|
||||
|
||||
- name: go test
|
||||
image: docker.io/immawanderer/archlinux-go:linux-amd64
|
||||
depends_on: [go fmt, go vet]
|
||||
depends_on: [go fmt, go vet, npm i]
|
||||
volumes:
|
||||
- name: gopath
|
||||
path: /go
|
||||
@ -135,9 +147,21 @@ steps:
|
||||
commands:
|
||||
- go vet ./...
|
||||
|
||||
- name: go build
|
||||
- name: npm i
|
||||
image: docker.io/library/golang:1.20.3-alpine3.17
|
||||
depends_on: [go fmt, go vet]
|
||||
volumes:
|
||||
- name: gopath
|
||||
path: /go
|
||||
commands:
|
||||
- mkdir -pv static
|
||||
- apk update -q && apk add -q --no-cache npm
|
||||
- npm i
|
||||
- npx tailwindcss -i ./assets/input.css -o ./static/pcmt.css --minify
|
||||
|
||||
- name: go build
|
||||
image: docker.io/library/golang:1.20.3-alpine3.17
|
||||
depends_on: [go fmt, go vet, npm i]
|
||||
volumes:
|
||||
- name: gopath
|
||||
path: /go
|
||||
@ -146,7 +170,7 @@ steps:
|
||||
|
||||
- name: go test
|
||||
image: docker.io/library/golang:1.20.3-alpine3.17
|
||||
depends_on: [go fmt, go vet]
|
||||
depends_on: [go fmt, go vet, npm i]
|
||||
volumes:
|
||||
- name: gopath
|
||||
path: /go
|
||||
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,6 +1,11 @@
|
||||
# main binary
|
||||
pcmt
|
||||
|
||||
# static assets folder
|
||||
/static/
|
||||
|
||||
/node_modules/
|
||||
|
||||
# ---> Go
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
|
63
app/app.go
63
app/app.go
@ -1,30 +1,58 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/config"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
e *echo.Echo
|
||||
logger *log.Logger
|
||||
initialised bool
|
||||
e *echo.Echo
|
||||
logger *log.Logger
|
||||
initialised bool
|
||||
embeds Embeds
|
||||
config *config.Config
|
||||
version string
|
||||
develMode bool
|
||||
jwtkey string
|
||||
encryptionKey string
|
||||
dbConnect string
|
||||
db *ent.Client
|
||||
}
|
||||
|
||||
type Embeds struct {
|
||||
templates embed.FS
|
||||
assets embed.FS
|
||||
}
|
||||
|
||||
// Init allows setting App's important fields - once.
|
||||
func (a *App) Init() error {
|
||||
func (a *App) Init(version string, conf *config.Config, dbclient *ent.Client) error {
|
||||
if !a.initialised {
|
||||
e := echo.New()
|
||||
|
||||
a.e = e
|
||||
a.logger = log.New(os.Stderr, " *** pcmt:", log.Ldate|log.Ltime|log.Lshortfile)
|
||||
a.logger = log.New(os.Stderr, "*** pcmt:", log.Ldate|log.Ltime|log.Lshortfile)
|
||||
|
||||
a.Logger().Printf("app version: %s", version)
|
||||
a.version = version
|
||||
|
||||
a.Logger().Printf("setting app config to %#v", conf)
|
||||
a.config = conf
|
||||
a.Logger().Printf("app config set to %#v", a.config)
|
||||
|
||||
a.Logger().Print("saving client conn to db")
|
||||
a.db = dbclient
|
||||
|
||||
a.initialised = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("ErrAppAlreadyInitialised")
|
||||
}
|
||||
|
||||
@ -37,3 +65,28 @@ func (a *App) E() *echo.Echo {
|
||||
func (a *App) Logger() *log.Logger {
|
||||
return a.logger
|
||||
}
|
||||
|
||||
// SetEmbeds saves the embedded files to application state.
|
||||
func (a *App) SetEmbeds(templates, assets embed.FS) {
|
||||
a.embeds.templates = templates
|
||||
a.embeds.assets = assets
|
||||
}
|
||||
|
||||
// SetDevel puts the app in devel mode, which loads browser-sync script in
|
||||
// templates and expects browser-sync running.
|
||||
func (a *App) SetDevel() {
|
||||
if !a.Config().DevelMode {
|
||||
a.Logger().Print("overriding configuration value of DevelMode based on a flag")
|
||||
a.Config().DevelMode = true
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
a.Logger().Print("setting DevelMode based on a flag")
|
||||
a.develMode = true
|
||||
}
|
||||
|
||||
// func (a *App) SetVersion(version string) {
|
||||
// a.Logger().Printf("setting app version to %s", version)
|
||||
// a.version = version
|
||||
// }
|
||||
|
52
app/assets.go
Normal file
52
app/assets.go
Normal file
@ -0,0 +1,52 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func (a *App) getAssets(live bool) http.FileSystem {
|
||||
if live {
|
||||
log.Print("assets - live mode")
|
||||
return http.FS(os.DirFS("static"))
|
||||
}
|
||||
|
||||
log.Print("assets - embed mode")
|
||||
|
||||
fsys, err := fs.Sub(a.embeds.assets, "static")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return http.FS(fsys)
|
||||
}
|
||||
|
||||
// func (a *App) getTemplates(live bool) http.FileSystem {
|
||||
func (a *App) getTemplates(live bool) fs.FS {
|
||||
if live {
|
||||
log.Print("tmpls - live mode")
|
||||
// return http.FS(os.DirFS("../templates"))
|
||||
entries, err := os.ReadDir("templates")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
fmt.Println(e.Name())
|
||||
}
|
||||
|
||||
return os.DirFS("templates")
|
||||
}
|
||||
|
||||
log.Print("tmpls - embed mode")
|
||||
|
||||
fsys, err := fs.Sub(a.embeds.templates, "templates")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// return http.FS(fsys)
|
||||
return fsys
|
||||
}
|
41
app/config.go
Normal file
41
app/config.go
Normal file
@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/config"
|
||||
)
|
||||
|
||||
// // SetConfig takes one argument - the config - and sets it if the config has
|
||||
// // not been set.
|
||||
// func (a *App) SetConfig(c *config.Config) {
|
||||
// if a.config == nil {
|
||||
// a.config = c
|
||||
// } else {
|
||||
// a.logger.Println("config already set, not setting it again")
|
||||
// }
|
||||
// }
|
||||
|
||||
// Config returns config.
|
||||
func (a *App) Config() *config.Config {
|
||||
return a.config
|
||||
}
|
||||
|
||||
// PrintConfiguration outputs relevant settings of the application to console.
|
||||
func (a *App) PrintConfiguration() {
|
||||
a.Logger().Print("app configuration options")
|
||||
|
||||
if a.Config() != nil {
|
||||
if a.Config().LiveMode {
|
||||
a.Logger().Print("live mode enabled")
|
||||
}
|
||||
|
||||
if a.Config().DevelMode {
|
||||
a.Logger().Print("devel mode enabled - make sure that browser-sync is running")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.New("somehow we got here with config unset - contact the developer"))
|
||||
}
|
@ -9,14 +9,33 @@ import (
|
||||
|
||||
func (a *App) SetupRoutes() {
|
||||
e := a.E()
|
||||
conf := a.Config()
|
||||
liveMode := conf.LiveMode
|
||||
// liveMode := a.Config().LiveMode
|
||||
assets := http.FileServer(a.getAssets(liveMode))
|
||||
tmpls := a.getTemplates(liveMode)
|
||||
// tmplHandler := http.FileServer(a.getTemplates(live))
|
||||
|
||||
e.GET("/", func(c echo.Context) error {
|
||||
return c.NoContent(http.StatusOK)
|
||||
})
|
||||
e.HEAD("/", func(c echo.Context) error {
|
||||
return c.NoContent(http.StatusOK)
|
||||
})
|
||||
// run this before declaring any handler funcs.
|
||||
// handlers.SetConfig(conf)
|
||||
// handlers.SetAppVer(a.version)
|
||||
// handlers.InitTemplates(tmpls)
|
||||
handlers.InitHandlers(a.version, conf, tmpls)
|
||||
|
||||
// e.GET("/", echo.WrapHandler(assetHandler))
|
||||
e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", assets)))
|
||||
// e.GET("/", handlers.Index(indexTmpl))
|
||||
// e.GET("/", handlers.Index(conf, tmpls))
|
||||
// e.GET("/", handlers.Index(conf))
|
||||
e.GET("/", handlers.Index())
|
||||
e.GET("/signin", handlers.Signin())
|
||||
e.POST("/signin", handlers.SigninPost(a.db))
|
||||
e.GET("/signup", handlers.Signup())
|
||||
e.POST("/signup", handlers.SignupPost(a.db))
|
||||
e.GET("/home", handlers.Home())
|
||||
e.GET("/logout", handlers.Logout())
|
||||
e.POST("/logout", handlers.Logout())
|
||||
|
||||
// administrative endpoints.
|
||||
e.GET("/admin", handlers.Admin())
|
||||
e.GET("/admin/*", handlers.Admin())
|
||||
}
|
||||
|
@ -1,16 +1,52 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
)
|
||||
|
||||
func (a *App) StartupSettings() {
|
||||
func (a *App) SetEchoSettings() {
|
||||
e := a.E()
|
||||
|
||||
e.HideBanner = true
|
||||
|
||||
e.Use(middleware.Logger())
|
||||
// e.Use(middleware.LoggerWithConfig(
|
||||
// middleware.LoggerConfig{
|
||||
// Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` +
|
||||
// `"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` +
|
||||
// `"status":${status},"error":"${error}","latency":${latency},"latency_human":"${latency_human}"` +
|
||||
// `,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n",
|
||||
// CustomTimeFormat: "2006-01-02 15:04:05.00000",
|
||||
// },
|
||||
// ))
|
||||
// logger := zerolog.New(os.Stdout)
|
||||
// e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
||||
// LogURI: true,
|
||||
// LogStatus: true,
|
||||
// LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
|
||||
// logger.Info().
|
||||
// Str("URI", v.URI).
|
||||
// Int("status", v.Status).
|
||||
// Msg("request")
|
||||
//
|
||||
// return nil
|
||||
// },
|
||||
// }))
|
||||
|
||||
e.Use(middleware.Recover())
|
||||
e.Use(middleware.CSRF())
|
||||
|
||||
// e.Use(middleware.CSRF())
|
||||
e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
|
||||
TokenLookup: "cookie:_csrf",
|
||||
CookiePath: "/",
|
||||
// CookieDomain: "example.com",
|
||||
// CookieSecure: true,
|
||||
CookieHTTPOnly: true,
|
||||
CookieSameSite: http.SameSiteStrictMode,
|
||||
}),
|
||||
)
|
||||
|
||||
e.Use(middleware.Secure())
|
||||
}
|
||||
|
4
assets/img/lock.svg
Normal file
4
assets/img/lock.svg
Normal file
@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-3 text-gray-300 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 339 B |
4
assets/img/mail.svg
Normal file
4
assets/img/mail.svg
Normal file
@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mx-3 text-gray-300 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 339 B |
3
assets/input.css
Normal file
3
assets/input.css
Normal file
@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
113
bs.js
Normal file
113
bs.js
Normal file
@ -0,0 +1,113 @@
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Browser-sync config file
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| For up-to-date information about the options:
|
||||
| http://www.browsersync.io/docs/options/
|
||||
|
|
||||
| There are more options than you see here, these are just the ones that are
|
||||
| set internally. See the website for more info.
|
||||
|
|
||||
|
|
||||
*/
|
||||
module.exports = {
|
||||
"ui": {
|
||||
"port": 3003
|
||||
},
|
||||
/* "files": true, */
|
||||
"files": ["templates/*.tmpl", "dist/*.css"],
|
||||
"watchEvents": [
|
||||
"change"
|
||||
],
|
||||
"watch": false,
|
||||
"ignore": [],
|
||||
"single": false,
|
||||
"watchOptions": {
|
||||
"ignoreInitial": true
|
||||
},
|
||||
"server": false,
|
||||
"proxy": "localhost:3000",
|
||||
"port": 3002,
|
||||
"middleware": false,
|
||||
"serveStatic": [],
|
||||
"ghostMode": {
|
||||
"clicks": true,
|
||||
"scroll": true,
|
||||
"location": true,
|
||||
"forms": {
|
||||
"submit": true,
|
||||
"inputs": true,
|
||||
"toggles": true
|
||||
}
|
||||
},
|
||||
"logLevel": "info",
|
||||
"logPrefix": "Browsersync",
|
||||
"logConnections": false,
|
||||
"logFileChanges": true,
|
||||
"logSnippet": true,
|
||||
"rewriteRules": [],
|
||||
"open": "local",
|
||||
/* this is the true command, i.e. no browser */
|
||||
"browser": "true",
|
||||
"online": false,
|
||||
"cors": false,
|
||||
"xip": false,
|
||||
"hostnameSuffix": false,
|
||||
"reloadOnRestart": false,
|
||||
"notify": false,
|
||||
"scrollProportionally": true,
|
||||
"scrollThrottle": 0,
|
||||
"scrollRestoreTechnique": "window.name",
|
||||
"scrollElements": [],
|
||||
"scrollElementMapping": [],
|
||||
"reloadDelay": 90,
|
||||
"reloadDebounce": 500,
|
||||
"reloadThrottle": 0,
|
||||
/* "plugins": [], */
|
||||
plugins: ["bs-html-injector?files[]=*.tmpl"],
|
||||
"injectChanges": true,
|
||||
"startPath": null,
|
||||
"minify": true,
|
||||
/* "host": "localhost:3000", */
|
||||
"host": null,
|
||||
"localOnly": true,
|
||||
"codeSync": true,
|
||||
"timestamps": true,
|
||||
"clientEvents": [
|
||||
"scroll",
|
||||
"scroll:element",
|
||||
"input:text",
|
||||
"input:toggles",
|
||||
"form:submit",
|
||||
"form:reset",
|
||||
"click"
|
||||
],
|
||||
"socket": {
|
||||
"socketIoOptions": {
|
||||
"log": false
|
||||
},
|
||||
"socketIoClientConfig": {
|
||||
"reconnectionAttempts": 50
|
||||
},
|
||||
"path": "/browser-sync/socket.io",
|
||||
"clientPath": "/browser-sync",
|
||||
"namespace": "/browser-sync",
|
||||
"clients": {
|
||||
"heartbeatTimeout": 5000
|
||||
}
|
||||
},
|
||||
"tagNames": {
|
||||
"less": "link",
|
||||
"scss": "link",
|
||||
"css": "link",
|
||||
"jpg": "img",
|
||||
"jpeg": "img",
|
||||
"png": "img",
|
||||
"svg": "img",
|
||||
"gif": "img",
|
||||
"js": "script"
|
||||
},
|
||||
"injectNotification": false
|
||||
};
|
92
config.dhall
92
config.dhall
@ -1 +1,91 @@
|
||||
{ Port = 3001, AppName = "whatever" }
|
||||
-- convenience funcs for validation.
|
||||
let Prelude =
|
||||
https://prelude.dhall-lang.org/v20.2.0/package.dhall
|
||||
sha256:a6036bc38d883450598d1de7c98ead113196fe2db02e9733855668b18096f07b
|
||||
|
||||
let NuConfig =
|
||||
-- | define a configuration schema.
|
||||
{ Type =
|
||||
{ Port : Natural
|
||||
, AppName : Text
|
||||
, LiveMode : Bool
|
||||
, DevelMode : Bool
|
||||
, LoginCookieName : Optional Text
|
||||
}
|
||||
, default =
|
||||
{ Port = 3000
|
||||
, AppName = "pcmt"
|
||||
, LiveMode = False
|
||||
, DevelMode = False
|
||||
, LoginCookieName = None Text
|
||||
}
|
||||
}
|
||||
|
||||
let NuConfig/validate
|
||||
: NuConfig.Type -> Type
|
||||
=
|
||||
-- | define validation.
|
||||
\(c : NuConfig.Type) ->
|
||||
let expected = { validPort = True }
|
||||
|
||||
let actual =
|
||||
{ validPort =
|
||||
-- | make sure port number belongs to the <1;65565> range.
|
||||
Prelude.Natural.lessThanEqual 1 c.Port
|
||||
&& Prelude.Natural.lessThanEqual c.Port 65565
|
||||
}
|
||||
|
||||
in expected === actual
|
||||
|
||||
let nuconf = NuConfig::{ LiveMode = True, DevelMode = True }
|
||||
|
||||
let _ =
|
||||
-- | validate the configuration.
|
||||
assert : NuConfig/validate nuconf
|
||||
|
||||
let Config =
|
||||
-- | define configuration schema.
|
||||
{ Port : Natural
|
||||
, AppName : Text
|
||||
, LiveMode : Bool
|
||||
, DevelMode : Bool
|
||||
, LoginCookieName : Optional Text
|
||||
}
|
||||
|
||||
let defconf
|
||||
-- | a full default configuration.
|
||||
-- | TODO: have this reside on the Internet and import it similar to how
|
||||
-- | the Dhall Prelude is imported.
|
||||
: Config
|
||||
= { Port = 3000
|
||||
, AppName = "pcmt"
|
||||
, LiveMode = False
|
||||
, DevelMode = False
|
||||
, LoginCookieName = None Text
|
||||
}
|
||||
|
||||
let conf
|
||||
: Config
|
||||
= defconf // { LiveMode = True, DevelMode = False }
|
||||
|
||||
let Config/validate
|
||||
: Config -> Type
|
||||
=
|
||||
-- | define validation.
|
||||
\(config : Config) ->
|
||||
let expected = { validPort = True }
|
||||
|
||||
let actual =
|
||||
{ validPort =
|
||||
-- | make sure port number belongs to the <1;65565> range.
|
||||
Prelude.Natural.lessThanEqual 1 config.Port
|
||||
&& Prelude.Natural.lessThanEqual config.Port 65565
|
||||
}
|
||||
|
||||
in expected === actual
|
||||
|
||||
let _ =
|
||||
-- | validate the configuration.
|
||||
assert : Config/validate conf
|
||||
|
||||
in nuconf
|
||||
|
@ -1,12 +1,16 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/philandstuff/dhall-golang/v6"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port int
|
||||
AppName string
|
||||
Port int
|
||||
AppName string
|
||||
LiveMode bool
|
||||
DevelMode bool
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (*Config, error) {
|
||||
@ -17,5 +21,7 @@ func LoadConfig(path string) (*Config, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Printf("parsed config: %+v", &config)
|
||||
|
||||
return &config, nil
|
||||
}
|
||||
|
11
embed.go
Normal file
11
embed.go
Normal file
@ -0,0 +1,11 @@
|
||||
package main
|
||||
|
||||
import "embed"
|
||||
|
||||
var (
|
||||
//go:embed templates
|
||||
templates embed.FS
|
||||
|
||||
//go:embed assets
|
||||
assets embed.FS
|
||||
)
|
317
ent/client.go
Normal file
317
ent/client.go
Normal file
@ -0,0 +1,317 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/migrate"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
)
|
||||
|
||||
// Client is the client that holds all ent builders.
|
||||
type Client struct {
|
||||
config
|
||||
// Schema is the client for creating, migrating and dropping schema.
|
||||
Schema *migrate.Schema
|
||||
// User is the client for interacting with the User builders.
|
||||
User *UserClient
|
||||
}
|
||||
|
||||
// NewClient creates a new client configured with the given options.
|
||||
func NewClient(opts ...Option) *Client {
|
||||
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
|
||||
cfg.options(opts...)
|
||||
client := &Client{config: cfg}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
func (c *Client) init() {
|
||||
c.Schema = migrate.NewSchema(c.driver)
|
||||
c.User = NewUserClient(c.config)
|
||||
}
|
||||
|
||||
type (
|
||||
// config is the configuration for the client and its builder.
|
||||
config struct {
|
||||
// driver used for executing database requests.
|
||||
driver dialect.Driver
|
||||
// debug enable a debug logging.
|
||||
debug bool
|
||||
// log used for logging on debug mode.
|
||||
log func(...any)
|
||||
// hooks to execute on mutations.
|
||||
hooks *hooks
|
||||
// interceptors to execute on queries.
|
||||
inters *inters
|
||||
}
|
||||
// Option function to configure the client.
|
||||
Option func(*config)
|
||||
)
|
||||
|
||||
// options applies the options on the config object.
|
||||
func (c *config) options(opts ...Option) {
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
if c.debug {
|
||||
c.driver = dialect.Debug(c.driver, c.log)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug enables debug logging on the ent.Driver.
|
||||
func Debug() Option {
|
||||
return func(c *config) {
|
||||
c.debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// Log sets the logging function for debug mode.
|
||||
func Log(fn func(...any)) Option {
|
||||
return func(c *config) {
|
||||
c.log = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Driver configures the client driver.
|
||||
func Driver(driver dialect.Driver) Option {
|
||||
return func(c *config) {
|
||||
c.driver = driver
|
||||
}
|
||||
}
|
||||
|
||||
// Open opens a database/sql.DB specified by the driver name and
|
||||
// the data source name, and returns a new client attached to it.
|
||||
// Optional parameters can be added for configuring the client.
|
||||
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
|
||||
switch driverName {
|
||||
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
|
||||
drv, err := sql.Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewClient(append(options, Driver(drv))...), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported driver: %q", driverName)
|
||||
}
|
||||
}
|
||||
|
||||
// Tx returns a new transactional client. The provided context
|
||||
// is used until the transaction is committed or rolled back.
|
||||
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, errors.New("ent: cannot start a transaction within a transaction")
|
||||
}
|
||||
tx, err := newTx(ctx, c.driver)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = tx
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
User: NewUserClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BeginTx returns a transactional client with specified options.
|
||||
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, errors.New("ent: cannot start a transaction within a transaction")
|
||||
}
|
||||
tx, err := c.driver.(interface {
|
||||
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
|
||||
}).BeginTx(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = &txDriver{tx: tx, drv: c.driver}
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
User: NewUserClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
|
||||
//
|
||||
// client.Debug().
|
||||
// User.
|
||||
// Query().
|
||||
// Count(ctx)
|
||||
func (c *Client) Debug() *Client {
|
||||
if c.debug {
|
||||
return c
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = dialect.Debug(c.driver, c.log)
|
||||
client := &Client{config: cfg}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
// Close closes the database connection and prevents new queries from starting.
|
||||
func (c *Client) Close() error {
|
||||
return c.driver.Close()
|
||||
}
|
||||
|
||||
// Use adds the mutation hooks to all the entity clients.
|
||||
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
|
||||
func (c *Client) Use(hooks ...Hook) {
|
||||
c.User.Use(hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds the query interceptors to all the entity clients.
|
||||
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
|
||||
func (c *Client) Intercept(interceptors ...Interceptor) {
|
||||
c.User.Intercept(interceptors...)
|
||||
}
|
||||
|
||||
// Mutate implements the ent.Mutator interface.
|
||||
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
|
||||
switch m := m.(type) {
|
||||
case *UserMutation:
|
||||
return c.User.mutate(ctx, m)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
|
||||
}
|
||||
}
|
||||
|
||||
// UserClient is a client for the User schema.
|
||||
type UserClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewUserClient returns a client for the User from the given config.
|
||||
func NewUserClient(c config) *UserClient {
|
||||
return &UserClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
|
||||
func (c *UserClient) Use(hooks ...Hook) {
|
||||
c.hooks.User = append(c.hooks.User, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
|
||||
func (c *UserClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.User = append(c.inters.User, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a User entity.
|
||||
func (c *UserClient) Create() *UserCreate {
|
||||
mutation := newUserMutation(c.config, OpCreate)
|
||||
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of User entities.
|
||||
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
|
||||
return &UserCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for User.
|
||||
func (c *UserClient) Update() *UserUpdate {
|
||||
mutation := newUserMutation(c.config, OpUpdate)
|
||||
return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *UserClient) UpdateOne(u *User) *UserUpdateOne {
|
||||
mutation := newUserMutation(c.config, OpUpdateOne, withUser(u))
|
||||
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *UserClient) UpdateOneID(id uuid.UUID) *UserUpdateOne {
|
||||
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
|
||||
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for User.
|
||||
func (c *UserClient) Delete() *UserDelete {
|
||||
mutation := newUserMutation(c.config, OpDelete)
|
||||
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *UserClient) DeleteOne(u *User) *UserDeleteOne {
|
||||
return c.DeleteOneID(u.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *UserClient) DeleteOneID(id uuid.UUID) *UserDeleteOne {
|
||||
builder := c.Delete().Where(user.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &UserDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for User.
|
||||
func (c *UserClient) Query() *UserQuery {
|
||||
return &UserQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeUser},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a User entity by its id.
|
||||
func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
return c.Query().Where(user.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *UserClient) GetX(ctx context.Context, id uuid.UUID) *User {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *UserClient) Hooks() []Hook {
|
||||
return c.hooks.User
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *UserClient) Interceptors() []Interceptor {
|
||||
return c.inters.User
|
||||
}
|
||||
|
||||
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// hooks and interceptors per client, for fast access.
|
||||
type (
|
||||
hooks struct {
|
||||
User []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
User []ent.Interceptor
|
||||
}
|
||||
)
|
616
ent/ent.go
Normal file
616
ent/ent.go
Normal file
@ -0,0 +1,616 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
)
|
||||
|
||||
// ent aliases to avoid import conflicts in user's code.
|
||||
type (
|
||||
Op = ent.Op
|
||||
Hook = ent.Hook
|
||||
Value = ent.Value
|
||||
Query = ent.Query
|
||||
QueryContext = ent.QueryContext
|
||||
Querier = ent.Querier
|
||||
QuerierFunc = ent.QuerierFunc
|
||||
Interceptor = ent.Interceptor
|
||||
InterceptFunc = ent.InterceptFunc
|
||||
Traverser = ent.Traverser
|
||||
TraverseFunc = ent.TraverseFunc
|
||||
Policy = ent.Policy
|
||||
Mutator = ent.Mutator
|
||||
Mutation = ent.Mutation
|
||||
MutateFunc = ent.MutateFunc
|
||||
)
|
||||
|
||||
type clientCtxKey struct{}
|
||||
|
||||
// FromContext returns a Client stored inside a context, or nil if there isn't one.
|
||||
func FromContext(ctx context.Context) *Client {
|
||||
c, _ := ctx.Value(clientCtxKey{}).(*Client)
|
||||
return c
|
||||
}
|
||||
|
||||
// NewContext returns a new context with the given Client attached.
|
||||
func NewContext(parent context.Context, c *Client) context.Context {
|
||||
return context.WithValue(parent, clientCtxKey{}, c)
|
||||
}
|
||||
|
||||
type txCtxKey struct{}
|
||||
|
||||
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
|
||||
func TxFromContext(ctx context.Context) *Tx {
|
||||
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
|
||||
return tx
|
||||
}
|
||||
|
||||
// NewTxContext returns a new context with the given Tx attached.
|
||||
func NewTxContext(parent context.Context, tx *Tx) context.Context {
|
||||
return context.WithValue(parent, txCtxKey{}, tx)
|
||||
}
|
||||
|
||||
// OrderFunc applies an ordering on the sql selector.
|
||||
type OrderFunc func(*sql.Selector)
|
||||
|
||||
// columnChecker returns a function indicates if the column exists in the given column.
|
||||
func columnChecker(table string) func(string) error {
|
||||
checks := map[string]func(string) bool{
|
||||
user.Table: user.ValidColumn,
|
||||
}
|
||||
check, ok := checks[table]
|
||||
if !ok {
|
||||
return func(string) error {
|
||||
return fmt.Errorf("unknown table %q", table)
|
||||
}
|
||||
}
|
||||
return func(column string) error {
|
||||
if !check(column) {
|
||||
return fmt.Errorf("unknown column %q for table %q", column, table)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Asc applies the given fields in ASC order.
|
||||
func Asc(fields ...string) OrderFunc {
|
||||
return func(s *sql.Selector) {
|
||||
check := columnChecker(s.TableName())
|
||||
for _, f := range fields {
|
||||
if err := check(f); err != nil {
|
||||
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
|
||||
}
|
||||
s.OrderBy(sql.Asc(s.C(f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Desc applies the given fields in DESC order.
|
||||
func Desc(fields ...string) OrderFunc {
|
||||
return func(s *sql.Selector) {
|
||||
check := columnChecker(s.TableName())
|
||||
for _, f := range fields {
|
||||
if err := check(f); err != nil {
|
||||
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
|
||||
}
|
||||
s.OrderBy(sql.Desc(s.C(f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
|
||||
type AggregateFunc func(*sql.Selector) string
|
||||
|
||||
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
|
||||
//
|
||||
// GroupBy(field1, field2).
|
||||
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
|
||||
// Scan(ctx, &v)
|
||||
func As(fn AggregateFunc, end string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
return sql.As(fn(s), end)
|
||||
}
|
||||
}
|
||||
|
||||
// Count applies the "count" aggregation function on each group.
|
||||
func Count() AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
return sql.Count("*")
|
||||
}
|
||||
}
|
||||
|
||||
// Max applies the "max" aggregation function on the given field of each group.
|
||||
func Max(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Max(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Mean applies the "mean" aggregation function on the given field of each group.
|
||||
func Mean(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Avg(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Min applies the "min" aggregation function on the given field of each group.
|
||||
func Min(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Min(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Sum applies the "sum" aggregation function on the given field of each group.
|
||||
func Sum(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
check := columnChecker(s.TableName())
|
||||
if err := check(field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Sum(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// ValidationError returns when validating a field or edge fails.
|
||||
type ValidationError struct {
|
||||
Name string // Field or edge name.
|
||||
err error
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *ValidationError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
// Unwrap implements the errors.Wrapper interface.
|
||||
func (e *ValidationError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
// IsValidationError returns a boolean indicating whether the error is a validation error.
|
||||
func IsValidationError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *ValidationError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
|
||||
type NotFoundError struct {
|
||||
label string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotFoundError) Error() string {
|
||||
return "ent: " + e.label + " not found"
|
||||
}
|
||||
|
||||
// IsNotFound returns a boolean indicating whether the error is a not found error.
|
||||
func IsNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotFoundError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// MaskNotFound masks not found error.
|
||||
func MaskNotFound(err error) error {
|
||||
if IsNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
|
||||
type NotSingularError struct {
|
||||
label string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotSingularError) Error() string {
|
||||
return "ent: " + e.label + " not singular"
|
||||
}
|
||||
|
||||
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
|
||||
func IsNotSingular(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotSingularError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// NotLoadedError returns when trying to get a node that was not loaded by the query.
|
||||
type NotLoadedError struct {
|
||||
edge string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotLoadedError) Error() string {
|
||||
return "ent: " + e.edge + " edge was not loaded"
|
||||
}
|
||||
|
||||
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
|
||||
func IsNotLoaded(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotLoadedError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// ConstraintError returns when trying to create/update one or more entities and
|
||||
// one or more of their constraints failed. For example, violation of edge or
|
||||
// field uniqueness.
|
||||
type ConstraintError struct {
|
||||
msg string
|
||||
wrap error
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e ConstraintError) Error() string {
|
||||
return "ent: constraint failed: " + e.msg
|
||||
}
|
||||
|
||||
// Unwrap implements the errors.Wrapper interface.
|
||||
func (e *ConstraintError) Unwrap() error {
|
||||
return e.wrap
|
||||
}
|
||||
|
||||
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
|
||||
func IsConstraintError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *ConstraintError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// selector embedded by the different Select/GroupBy builders.
|
||||
type selector struct {
|
||||
label string
|
||||
flds *[]string
|
||||
fns []AggregateFunc
|
||||
scan func(context.Context, any) error
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (s *selector) ScanX(ctx context.Context, v any) {
|
||||
if err := s.scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (s *selector) StringsX(ctx context.Context) []string {
|
||||
v, err := s.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// String returns a single string from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) String(ctx context.Context) (_ string, err error) {
|
||||
var v []string
|
||||
if v, err = s.Strings(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// StringX is like String, but panics if an error occurs.
|
||||
func (s *selector) StringX(ctx context.Context) string {
|
||||
v, err := s.String(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (s *selector) IntsX(ctx context.Context) []int {
|
||||
v, err := s.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Int returns a single int from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Int(ctx context.Context) (_ int, err error) {
|
||||
var v []int
|
||||
if v, err = s.Ints(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// IntX is like Int, but panics if an error occurs.
|
||||
func (s *selector) IntX(ctx context.Context) int {
|
||||
v, err := s.Int(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (s *selector) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := s.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
|
||||
var v []float64
|
||||
if v, err = s.Float64s(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Float64X is like Float64, but panics if an error occurs.
|
||||
func (s *selector) Float64X(ctx context.Context) float64 {
|
||||
v, err := s.Float64(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (s *selector) BoolsX(ctx context.Context) []bool {
|
||||
v, err := s.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
|
||||
var v []bool
|
||||
if v, err = s.Bools(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// BoolX is like Bool, but panics if an error occurs.
|
||||
func (s *selector) BoolX(ctx context.Context) bool {
|
||||
v, err := s.Bool(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// withHooks invokes the builder operation with the given hooks, if any.
|
||||
func withHooks[V Value, M any, PM interface {
|
||||
*M
|
||||
Mutation
|
||||
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
|
||||
if len(hooks) == 0 {
|
||||
return exec(ctx)
|
||||
}
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutationT, ok := any(m).(PM)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
// Set the mutation to the builder.
|
||||
*mutation = *mutationT
|
||||
return exec(ctx)
|
||||
})
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
if hooks[i] == nil {
|
||||
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, mutation)
|
||||
if err != nil {
|
||||
return value, err
|
||||
}
|
||||
nv, ok := v.(V)
|
||||
if !ok {
|
||||
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
|
||||
}
|
||||
return nv, nil
|
||||
}
|
||||
|
||||
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
|
||||
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
|
||||
if ent.QueryFromContext(ctx) == nil {
|
||||
qc.Op = op
|
||||
ctx = ent.NewQueryContext(ctx, qc)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func querierAll[V Value, Q interface {
|
||||
sqlAll(context.Context, ...queryHook) (V, error)
|
||||
}]() Querier {
|
||||
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
return query.sqlAll(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func querierCount[Q interface {
|
||||
sqlCount(context.Context) (int, error)
|
||||
}]() Querier {
|
||||
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
return query.sqlCount(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
|
||||
for i := len(inters) - 1; i >= 0; i-- {
|
||||
qr = inters[i].Intercept(qr)
|
||||
}
|
||||
rv, err := qr.Query(ctx, q)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
vt, ok := rv.(V)
|
||||
if !ok {
|
||||
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
|
||||
}
|
||||
return vt, nil
|
||||
}
|
||||
|
||||
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
|
||||
sqlScan(context.Context, Q1, any) error
|
||||
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
|
||||
rv := reflect.ValueOf(v)
|
||||
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q1)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
|
||||
return rv.Elem().Interface(), nil
|
||||
}
|
||||
return v, nil
|
||||
})
|
||||
for i := len(inters) - 1; i >= 0; i-- {
|
||||
qr = inters[i].Intercept(qr)
|
||||
}
|
||||
vv, err := qr.Query(ctx, rootQuery)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch rv2 := reflect.ValueOf(vv); {
|
||||
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
|
||||
case rv.Type() == rv2.Type():
|
||||
rv.Elem().Set(rv2.Elem())
|
||||
case rv.Elem().Type() == rv2.Type():
|
||||
rv.Elem().Set(rv2)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// queryHook describes an internal hook for the different sqlAll methods.
|
||||
type queryHook func(context.Context, *sqlgraph.QuerySpec)
|
84
ent/enttest/enttest.go
Normal file
84
ent/enttest/enttest.go
Normal file
@ -0,0 +1,84 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package enttest
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||||
// required by schema hooks.
|
||||
_ "git.dotya.ml/mirre-mt/pcmt/ent/runtime"
|
||||
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/migrate"
|
||||
)
|
||||
|
||||
type (
|
||||
// TestingT is the interface that is shared between
|
||||
// testing.T and testing.B and used by enttest.
|
||||
TestingT interface {
|
||||
FailNow()
|
||||
Error(...any)
|
||||
}
|
||||
|
||||
// Option configures client creation.
|
||||
Option func(*options)
|
||||
|
||||
options struct {
|
||||
opts []ent.Option
|
||||
migrateOpts []schema.MigrateOption
|
||||
}
|
||||
)
|
||||
|
||||
// WithOptions forwards options to client creation.
|
||||
func WithOptions(opts ...ent.Option) Option {
|
||||
return func(o *options) {
|
||||
o.opts = append(o.opts, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithMigrateOptions forwards options to auto migration.
|
||||
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
|
||||
return func(o *options) {
|
||||
o.migrateOpts = append(o.migrateOpts, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
func newOptions(opts []Option) *options {
|
||||
o := &options{}
|
||||
for _, opt := range opts {
|
||||
opt(o)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// Open calls ent.Open and auto-run migration.
|
||||
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
|
||||
o := newOptions(opts)
|
||||
c, err := ent.Open(driverName, dataSourceName, o.opts...)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
migrateSchema(t, c, o)
|
||||
return c
|
||||
}
|
||||
|
||||
// NewClient calls ent.NewClient and auto-run migration.
|
||||
func NewClient(t TestingT, opts ...Option) *ent.Client {
|
||||
o := newOptions(opts)
|
||||
c := ent.NewClient(o.opts...)
|
||||
migrateSchema(t, c, o)
|
||||
return c
|
||||
}
|
||||
func migrateSchema(t TestingT, c *ent.Client, o *options) {
|
||||
tables, err := schema.CopyTables(migrate.Tables)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
3
ent/generate.go
Normal file
3
ent/generate.go
Normal file
@ -0,0 +1,3 @@
|
||||
package ent
|
||||
|
||||
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema
|
199
ent/hook/hook.go
Normal file
199
ent/hook/hook.go
Normal file
@ -0,0 +1,199 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package hook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||||
)
|
||||
|
||||
// The UserFunc type is an adapter to allow the use of ordinary
|
||||
// function as User mutator.
|
||||
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.UserMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
|
||||
}
|
||||
|
||||
// Condition is a hook condition function.
|
||||
type Condition func(context.Context, ent.Mutation) bool
|
||||
|
||||
// And groups conditions with the AND operator.
|
||||
func And(first, second Condition, rest ...Condition) Condition {
|
||||
return func(ctx context.Context, m ent.Mutation) bool {
|
||||
if !first(ctx, m) || !second(ctx, m) {
|
||||
return false
|
||||
}
|
||||
for _, cond := range rest {
|
||||
if !cond(ctx, m) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Or groups conditions with the OR operator.
|
||||
func Or(first, second Condition, rest ...Condition) Condition {
|
||||
return func(ctx context.Context, m ent.Mutation) bool {
|
||||
if first(ctx, m) || second(ctx, m) {
|
||||
return true
|
||||
}
|
||||
for _, cond := range rest {
|
||||
if cond(ctx, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Not negates a given condition.
|
||||
func Not(cond Condition) Condition {
|
||||
return func(ctx context.Context, m ent.Mutation) bool {
|
||||
return !cond(ctx, m)
|
||||
}
|
||||
}
|
||||
|
||||
// HasOp is a condition testing mutation operation.
|
||||
func HasOp(op ent.Op) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
return m.Op().Is(op)
|
||||
}
|
||||
}
|
||||
|
||||
// HasAddedFields is a condition validating `.AddedField` on fields.
|
||||
func HasAddedFields(field string, fields ...string) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
if _, exists := m.AddedField(field); !exists {
|
||||
return false
|
||||
}
|
||||
for _, field := range fields {
|
||||
if _, exists := m.AddedField(field); !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// HasClearedFields is a condition validating `.FieldCleared` on fields.
|
||||
func HasClearedFields(field string, fields ...string) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
if exists := m.FieldCleared(field); !exists {
|
||||
return false
|
||||
}
|
||||
for _, field := range fields {
|
||||
if exists := m.FieldCleared(field); !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// HasFields is a condition validating `.Field` on fields.
|
||||
func HasFields(field string, fields ...string) Condition {
|
||||
return func(_ context.Context, m ent.Mutation) bool {
|
||||
if _, exists := m.Field(field); !exists {
|
||||
return false
|
||||
}
|
||||
for _, field := range fields {
|
||||
if _, exists := m.Field(field); !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// If executes the given hook under condition.
|
||||
//
|
||||
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
|
||||
func If(hk ent.Hook, cond Condition) ent.Hook {
|
||||
return func(next ent.Mutator) ent.Mutator {
|
||||
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if cond(ctx, m) {
|
||||
return hk(next).Mutate(ctx, m)
|
||||
}
|
||||
return next.Mutate(ctx, m)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// On executes the given hook only for the given operation.
|
||||
//
|
||||
// hook.On(Log, ent.Delete|ent.Create)
|
||||
func On(hk ent.Hook, op ent.Op) ent.Hook {
|
||||
return If(hk, HasOp(op))
|
||||
}
|
||||
|
||||
// Unless skips the given hook only for the given operation.
|
||||
//
|
||||
// hook.Unless(Log, ent.Update|ent.UpdateOne)
|
||||
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
|
||||
return If(hk, Not(HasOp(op)))
|
||||
}
|
||||
|
||||
// FixedError is a hook returning a fixed error.
|
||||
func FixedError(err error) ent.Hook {
|
||||
return func(ent.Mutator) ent.Mutator {
|
||||
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
|
||||
return nil, err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Reject returns a hook that rejects all operations that match op.
|
||||
//
|
||||
// func (T) Hooks() []ent.Hook {
|
||||
// return []ent.Hook{
|
||||
// Reject(ent.Delete|ent.Update),
|
||||
// }
|
||||
// }
|
||||
func Reject(op ent.Op) ent.Hook {
|
||||
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
|
||||
return On(hk, op)
|
||||
}
|
||||
|
||||
// Chain acts as a list of hooks and is effectively immutable.
|
||||
// Once created, it will always hold the same set of hooks in the same order.
|
||||
type Chain struct {
|
||||
hooks []ent.Hook
|
||||
}
|
||||
|
||||
// NewChain creates a new chain of hooks.
|
||||
func NewChain(hooks ...ent.Hook) Chain {
|
||||
return Chain{append([]ent.Hook(nil), hooks...)}
|
||||
}
|
||||
|
||||
// Hook chains the list of hooks and returns the final hook.
|
||||
func (c Chain) Hook() ent.Hook {
|
||||
return func(mutator ent.Mutator) ent.Mutator {
|
||||
for i := len(c.hooks) - 1; i >= 0; i-- {
|
||||
mutator = c.hooks[i](mutator)
|
||||
}
|
||||
return mutator
|
||||
}
|
||||
}
|
||||
|
||||
// Append extends a chain, adding the specified hook
|
||||
// as the last ones in the mutation flow.
|
||||
func (c Chain) Append(hooks ...ent.Hook) Chain {
|
||||
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
|
||||
newHooks = append(newHooks, c.hooks...)
|
||||
newHooks = append(newHooks, hooks...)
|
||||
return Chain{newHooks}
|
||||
}
|
||||
|
||||
// Extend extends a chain, adding the specified chain
|
||||
// as the last ones in the mutation flow.
|
||||
func (c Chain) Extend(chain Chain) Chain {
|
||||
return c.Append(chain.hooks...)
|
||||
}
|
64
ent/migrate/migrate.go
Normal file
64
ent/migrate/migrate.go
Normal file
@ -0,0 +1,64 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
// WithGlobalUniqueID sets the universal ids options to the migration.
|
||||
// If this option is enabled, ent migration will allocate a 1<<32 range
|
||||
// for the ids of each entity (table).
|
||||
// Note that this option cannot be applied on tables that already exist.
|
||||
WithGlobalUniqueID = schema.WithGlobalUniqueID
|
||||
// WithDropColumn sets the drop column option to the migration.
|
||||
// If this option is enabled, ent migration will drop old columns
|
||||
// that were used for both fields and edges. This defaults to false.
|
||||
WithDropColumn = schema.WithDropColumn
|
||||
// WithDropIndex sets the drop index option to the migration.
|
||||
// If this option is enabled, ent migration will drop old indexes
|
||||
// that were defined in the schema. This defaults to false.
|
||||
// Note that unique constraints are defined using `UNIQUE INDEX`,
|
||||
// and therefore, it's recommended to enable this option to get more
|
||||
// flexibility in the schema changes.
|
||||
WithDropIndex = schema.WithDropIndex
|
||||
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
|
||||
WithForeignKeys = schema.WithForeignKeys
|
||||
)
|
||||
|
||||
// Schema is the API for creating, migrating and dropping a schema.
|
||||
type Schema struct {
|
||||
drv dialect.Driver
|
||||
}
|
||||
|
||||
// NewSchema creates a new schema client.
|
||||
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
|
||||
|
||||
// Create creates all schema resources.
|
||||
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
|
||||
return Create(ctx, s, Tables, opts...)
|
||||
}
|
||||
|
||||
// Create creates all table resources using the given schema driver.
|
||||
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.Create(ctx, tables...)
|
||||
}
|
||||
|
||||
// WriteTo writes the schema changes to w instead of running them against the database.
|
||||
//
|
||||
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
|
||||
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
|
||||
}
|
34
ent/migrate/schema.go
Normal file
34
ent/migrate/schema.go
Normal file
@ -0,0 +1,34 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
// UsersColumns holds the columns for the "users" table.
|
||||
UsersColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID, Unique: true},
|
||||
{Name: "username", Type: field.TypeString, Unique: true},
|
||||
{Name: "password", Type: field.TypeString},
|
||||
{Name: "is_admin", Type: field.TypeBool, Default: false},
|
||||
{Name: "is_active", Type: field.TypeBool, Default: true},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "updated_at", Type: field.TypeTime},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
UsersTable = &schema.Table{
|
||||
Name: "users",
|
||||
Columns: UsersColumns,
|
||||
PrimaryKey: []*schema.Column{UsersColumns[0]},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
UsersTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
}
|
631
ent/mutation.go
Normal file
631
ent/mutation.go
Normal file
@ -0,0 +1,631 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/predicate"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// Operation types.
|
||||
OpCreate = ent.OpCreate
|
||||
OpDelete = ent.OpDelete
|
||||
OpDeleteOne = ent.OpDeleteOne
|
||||
OpUpdate = ent.OpUpdate
|
||||
OpUpdateOne = ent.OpUpdateOne
|
||||
|
||||
// Node types.
|
||||
TypeUser = "User"
|
||||
)
|
||||
|
||||
// UserMutation represents an operation that mutates the User nodes in the graph.
|
||||
type UserMutation struct {
|
||||
config
|
||||
op Op
|
||||
typ string
|
||||
id *uuid.UUID
|
||||
username *string
|
||||
password *string
|
||||
is_admin *bool
|
||||
is_active *bool
|
||||
created_at *time.Time
|
||||
updated_at *time.Time
|
||||
clearedFields map[string]struct{}
|
||||
done bool
|
||||
oldValue func(context.Context) (*User, error)
|
||||
predicates []predicate.User
|
||||
}
|
||||
|
||||
var _ ent.Mutation = (*UserMutation)(nil)
|
||||
|
||||
// userOption allows management of the mutation configuration using functional options.
|
||||
type userOption func(*UserMutation)
|
||||
|
||||
// newUserMutation creates new mutation for the User entity.
|
||||
func newUserMutation(c config, op Op, opts ...userOption) *UserMutation {
|
||||
m := &UserMutation{
|
||||
config: c,
|
||||
op: op,
|
||||
typ: TypeUser,
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// withUserID sets the ID field of the mutation.
|
||||
func withUserID(id uuid.UUID) userOption {
|
||||
return func(m *UserMutation) {
|
||||
var (
|
||||
err error
|
||||
once sync.Once
|
||||
value *User
|
||||
)
|
||||
m.oldValue = func(ctx context.Context) (*User, error) {
|
||||
once.Do(func() {
|
||||
if m.done {
|
||||
err = errors.New("querying old values post mutation is not allowed")
|
||||
} else {
|
||||
value, err = m.Client().User.Get(ctx, id)
|
||||
}
|
||||
})
|
||||
return value, err
|
||||
}
|
||||
m.id = &id
|
||||
}
|
||||
}
|
||||
|
||||
// withUser sets the old User of the mutation.
|
||||
func withUser(node *User) userOption {
|
||||
return func(m *UserMutation) {
|
||||
m.oldValue = func(context.Context) (*User, error) {
|
||||
return node, nil
|
||||
}
|
||||
m.id = &node.ID
|
||||
}
|
||||
}
|
||||
|
||||
// Client returns a new `ent.Client` from the mutation. If the mutation was
|
||||
// executed in a transaction (ent.Tx), a transactional client is returned.
|
||||
func (m UserMutation) Client() *Client {
|
||||
client := &Client{config: m.config}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
|
||||
// it returns an error otherwise.
|
||||
func (m UserMutation) Tx() (*Tx, error) {
|
||||
if _, ok := m.driver.(*txDriver); !ok {
|
||||
return nil, errors.New("ent: mutation is not running in a transaction")
|
||||
}
|
||||
tx := &Tx{config: m.config}
|
||||
tx.init()
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
// SetID sets the value of the id field. Note that this
|
||||
// operation is only accepted on creation of User entities.
|
||||
func (m *UserMutation) SetID(id uuid.UUID) {
|
||||
m.id = &id
|
||||
}
|
||||
|
||||
// ID returns the ID value in the mutation. Note that the ID is only available
|
||||
// if it was provided to the builder or after it was returned from the database.
|
||||
func (m *UserMutation) ID() (id uuid.UUID, exists bool) {
|
||||
if m.id == nil {
|
||||
return
|
||||
}
|
||||
return *m.id, true
|
||||
}
|
||||
|
||||
// IDs queries the database and returns the entity ids that match the mutation's predicate.
|
||||
// That means, if the mutation is applied within a transaction with an isolation level such
|
||||
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
|
||||
// or updated by the mutation.
|
||||
func (m *UserMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
switch {
|
||||
case m.op.Is(OpUpdateOne | OpDeleteOne):
|
||||
id, exists := m.ID()
|
||||
if exists {
|
||||
return []uuid.UUID{id}, nil
|
||||
}
|
||||
fallthrough
|
||||
case m.op.Is(OpUpdate | OpDelete):
|
||||
return m.Client().User.Query().Where(m.predicates...).IDs(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
|
||||
}
|
||||
}
|
||||
|
||||
// SetUsername sets the "username" field.
|
||||
func (m *UserMutation) SetUsername(s string) {
|
||||
m.username = &s
|
||||
}
|
||||
|
||||
// Username returns the value of the "username" field in the mutation.
|
||||
func (m *UserMutation) Username() (r string, exists bool) {
|
||||
v := m.username
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldUsername returns the old "username" field's value of the User entity.
|
||||
// If the User object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldUsername is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldUsername requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldUsername: %w", err)
|
||||
}
|
||||
return oldValue.Username, nil
|
||||
}
|
||||
|
||||
// ResetUsername resets all changes to the "username" field.
|
||||
func (m *UserMutation) ResetUsername() {
|
||||
m.username = nil
|
||||
}
|
||||
|
||||
// SetPassword sets the "password" field.
|
||||
func (m *UserMutation) SetPassword(s string) {
|
||||
m.password = &s
|
||||
}
|
||||
|
||||
// Password returns the value of the "password" field in the mutation.
|
||||
func (m *UserMutation) Password() (r string, exists bool) {
|
||||
v := m.password
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldPassword returns the old "password" field's value of the User entity.
|
||||
// If the User object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UserMutation) OldPassword(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldPassword is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldPassword requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldPassword: %w", err)
|
||||
}
|
||||
return oldValue.Password, nil
|
||||
}
|
||||
|
||||
// ResetPassword resets all changes to the "password" field.
|
||||
func (m *UserMutation) ResetPassword() {
|
||||
m.password = nil
|
||||
}
|
||||
|
||||
// SetIsAdmin sets the "is_admin" field.
|
||||
func (m *UserMutation) SetIsAdmin(b bool) {
|
||||
m.is_admin = &b
|
||||
}
|
||||
|
||||
// IsAdmin returns the value of the "is_admin" field in the mutation.
|
||||
func (m *UserMutation) IsAdmin() (r bool, exists bool) {
|
||||
v := m.is_admin
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldIsAdmin returns the old "is_admin" field's value of the User entity.
|
||||
// If the User object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UserMutation) OldIsAdmin(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldIsAdmin is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldIsAdmin requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldIsAdmin: %w", err)
|
||||
}
|
||||
return oldValue.IsAdmin, nil
|
||||
}
|
||||
|
||||
// ResetIsAdmin resets all changes to the "is_admin" field.
|
||||
func (m *UserMutation) ResetIsAdmin() {
|
||||
m.is_admin = nil
|
||||
}
|
||||
|
||||
// SetIsActive sets the "is_active" field.
|
||||
func (m *UserMutation) SetIsActive(b bool) {
|
||||
m.is_active = &b
|
||||
}
|
||||
|
||||
// IsActive returns the value of the "is_active" field in the mutation.
|
||||
func (m *UserMutation) IsActive() (r bool, exists bool) {
|
||||
v := m.is_active
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldIsActive returns the old "is_active" field's value of the User entity.
|
||||
// If the User object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UserMutation) OldIsActive(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldIsActive is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldIsActive requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldIsActive: %w", err)
|
||||
}
|
||||
return oldValue.IsActive, nil
|
||||
}
|
||||
|
||||
// ResetIsActive resets all changes to the "is_active" field.
|
||||
func (m *UserMutation) ResetIsActive() {
|
||||
m.is_active = nil
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (m *UserMutation) SetCreatedAt(t time.Time) {
|
||||
m.created_at = &t
|
||||
}
|
||||
|
||||
// CreatedAt returns the value of the "created_at" field in the mutation.
|
||||
func (m *UserMutation) CreatedAt() (r time.Time, exists bool) {
|
||||
v := m.created_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldCreatedAt returns the old "created_at" field's value of the User entity.
|
||||
// If the User object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
|
||||
}
|
||||
return oldValue.CreatedAt, nil
|
||||
}
|
||||
|
||||
// ResetCreatedAt resets all changes to the "created_at" field.
|
||||
func (m *UserMutation) ResetCreatedAt() {
|
||||
m.created_at = nil
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (m *UserMutation) SetUpdatedAt(t time.Time) {
|
||||
m.updated_at = &t
|
||||
}
|
||||
|
||||
// UpdatedAt returns the value of the "updated_at" field in the mutation.
|
||||
func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) {
|
||||
v := m.updated_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldUpdatedAt returns the old "updated_at" field's value of the User entity.
|
||||
// If the User object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
|
||||
}
|
||||
return oldValue.UpdatedAt, nil
|
||||
}
|
||||
|
||||
// ResetUpdatedAt resets all changes to the "updated_at" field.
|
||||
func (m *UserMutation) ResetUpdatedAt() {
|
||||
m.updated_at = nil
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserMutation builder.
|
||||
func (m *UserMutation) Where(ps ...predicate.User) {
|
||||
m.predicates = append(m.predicates, ps...)
|
||||
}
|
||||
|
||||
// WhereP appends storage-level predicates to the UserMutation builder. Using this method,
|
||||
// users can use type-assertion to append predicates that do not depend on any generated package.
|
||||
func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) {
|
||||
p := make([]predicate.User, len(ps))
|
||||
for i := range ps {
|
||||
p[i] = ps[i]
|
||||
}
|
||||
m.Where(p...)
|
||||
}
|
||||
|
||||
// Op returns the operation name.
|
||||
func (m *UserMutation) Op() Op {
|
||||
return m.op
|
||||
}
|
||||
|
||||
// SetOp allows setting the mutation operation.
|
||||
func (m *UserMutation) SetOp(op Op) {
|
||||
m.op = op
|
||||
}
|
||||
|
||||
// Type returns the node type of this mutation (User).
|
||||
func (m *UserMutation) Type() string {
|
||||
return m.typ
|
||||
}
|
||||
|
||||
// Fields returns all fields that were changed during this mutation. Note that in
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *UserMutation) Fields() []string {
|
||||
fields := make([]string, 0, 6)
|
||||
if m.username != nil {
|
||||
fields = append(fields, user.FieldUsername)
|
||||
}
|
||||
if m.password != nil {
|
||||
fields = append(fields, user.FieldPassword)
|
||||
}
|
||||
if m.is_admin != nil {
|
||||
fields = append(fields, user.FieldIsAdmin)
|
||||
}
|
||||
if m.is_active != nil {
|
||||
fields = append(fields, user.FieldIsActive)
|
||||
}
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, user.FieldCreatedAt)
|
||||
}
|
||||
if m.updated_at != nil {
|
||||
fields = append(fields, user.FieldUpdatedAt)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns the value of a field with the given name. The second boolean
|
||||
// return value indicates that this field was not set, or was not defined in the
|
||||
// schema.
|
||||
func (m *UserMutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case user.FieldUsername:
|
||||
return m.Username()
|
||||
case user.FieldPassword:
|
||||
return m.Password()
|
||||
case user.FieldIsAdmin:
|
||||
return m.IsAdmin()
|
||||
case user.FieldIsActive:
|
||||
return m.IsActive()
|
||||
case user.FieldCreatedAt:
|
||||
return m.CreatedAt()
|
||||
case user.FieldUpdatedAt:
|
||||
return m.UpdatedAt()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
switch name {
|
||||
case user.FieldUsername:
|
||||
return m.OldUsername(ctx)
|
||||
case user.FieldPassword:
|
||||
return m.OldPassword(ctx)
|
||||
case user.FieldIsAdmin:
|
||||
return m.OldIsAdmin(ctx)
|
||||
case user.FieldIsActive:
|
||||
return m.OldIsActive(ctx)
|
||||
case user.FieldCreatedAt:
|
||||
return m.OldCreatedAt(ctx)
|
||||
case user.FieldUpdatedAt:
|
||||
return m.OldUpdatedAt(ctx)
|
||||
}
|
||||
return nil, fmt.Errorf("unknown User field %s", name)
|
||||
}
|
||||
|
||||
// SetField sets the value of a field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *UserMutation) SetField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case user.FieldUsername:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetUsername(v)
|
||||
return nil
|
||||
case user.FieldPassword:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetPassword(v)
|
||||
return nil
|
||||
case user.FieldIsAdmin:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetIsAdmin(v)
|
||||
return nil
|
||||
case user.FieldIsActive:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetIsActive(v)
|
||||
return nil
|
||||
case user.FieldCreatedAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetCreatedAt(v)
|
||||
return nil
|
||||
case user.FieldUpdatedAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetUpdatedAt(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown User field %s", name)
|
||||
}
|
||||
|
||||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *UserMutation) AddedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddedField returns the numeric value that was incremented/decremented on a field
|
||||
// with the given name. The second boolean return value indicates that this field
|
||||
// was not set, or was not defined in the schema.
|
||||
func (m *UserMutation) AddedField(name string) (ent.Value, bool) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// AddField adds the value to the field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *UserMutation) AddField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
}
|
||||
return fmt.Errorf("unknown User numeric field %s", name)
|
||||
}
|
||||
|
||||
// ClearedFields returns all nullable fields that were cleared during this
|
||||
// mutation.
|
||||
func (m *UserMutation) ClearedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// FieldCleared returns a boolean indicating if a field with the given name was
|
||||
// cleared in this mutation.
|
||||
func (m *UserMutation) FieldCleared(name string) bool {
|
||||
_, ok := m.clearedFields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ClearField clears the value of the field with the given name. It returns an
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *UserMutation) ClearField(name string) error {
|
||||
return fmt.Errorf("unknown User nullable field %s", name)
|
||||
}
|
||||
|
||||
// ResetField resets all changes in the mutation for the field with the given name.
|
||||
// It returns an error if the field is not defined in the schema.
|
||||
func (m *UserMutation) ResetField(name string) error {
|
||||
switch name {
|
||||
case user.FieldUsername:
|
||||
m.ResetUsername()
|
||||
return nil
|
||||
case user.FieldPassword:
|
||||
m.ResetPassword()
|
||||
return nil
|
||||
case user.FieldIsAdmin:
|
||||
m.ResetIsAdmin()
|
||||
return nil
|
||||
case user.FieldIsActive:
|
||||
m.ResetIsActive()
|
||||
return nil
|
||||
case user.FieldCreatedAt:
|
||||
m.ResetCreatedAt()
|
||||
return nil
|
||||
case user.FieldUpdatedAt:
|
||||
m.ResetUpdatedAt()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown User field %s", name)
|
||||
}
|
||||
|
||||
// AddedEdges returns all edge names that were set/added in this mutation.
|
||||
func (m *UserMutation) AddedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
|
||||
// name in this mutation.
|
||||
func (m *UserMutation) AddedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *UserMutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
|
||||
// the given name in this mutation.
|
||||
func (m *UserMutation) RemovedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearedEdges returns all edge names that were cleared in this mutation.
|
||||
func (m *UserMutation) ClearedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// EdgeCleared returns a boolean which indicates if the edge with the given name
|
||||
// was cleared in this mutation.
|
||||
func (m *UserMutation) EdgeCleared(name string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearEdge clears the value of the edge with the given name. It returns an error
|
||||
// if that edge is not defined in the schema.
|
||||
func (m *UserMutation) ClearEdge(name string) error {
|
||||
return fmt.Errorf("unknown User unique edge %s", name)
|
||||
}
|
||||
|
||||
// ResetEdge resets all changes to the edge with the given name in this mutation.
|
||||
// It returns an error if the edge is not defined in the schema.
|
||||
func (m *UserMutation) ResetEdge(name string) error {
|
||||
return fmt.Errorf("unknown User edge %s", name)
|
||||
}
|
10
ent/predicate/predicate.go
Normal file
10
ent/predicate/predicate.go
Normal file
@ -0,0 +1,10 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package predicate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// User is the predicate function for user builders.
|
||||
type User func(*sql.Selector)
|
49
ent/runtime.go
Normal file
49
ent/runtime.go
Normal file
@ -0,0 +1,49 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/schema"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// The init function reads all schema descriptors with runtime code
|
||||
// (default values, validators, hooks and policies) and stitches it
|
||||
// to their package variables.
|
||||
func init() {
|
||||
userFields := schema.User{}.Fields()
|
||||
_ = userFields
|
||||
// userDescUsername is the schema descriptor for username field.
|
||||
userDescUsername := userFields[1].Descriptor()
|
||||
// user.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
|
||||
user.UsernameValidator = userDescUsername.Validators[0].(func(string) error)
|
||||
// userDescPassword is the schema descriptor for password field.
|
||||
userDescPassword := userFields[2].Descriptor()
|
||||
// user.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
|
||||
user.PasswordValidator = userDescPassword.Validators[0].(func(string) error)
|
||||
// userDescIsAdmin is the schema descriptor for is_admin field.
|
||||
userDescIsAdmin := userFields[3].Descriptor()
|
||||
// user.DefaultIsAdmin holds the default value on creation for the is_admin field.
|
||||
user.DefaultIsAdmin = userDescIsAdmin.Default.(bool)
|
||||
// userDescIsActive is the schema descriptor for is_active field.
|
||||
userDescIsActive := userFields[4].Descriptor()
|
||||
// user.DefaultIsActive holds the default value on creation for the is_active field.
|
||||
user.DefaultIsActive = userDescIsActive.Default.(bool)
|
||||
// userDescCreatedAt is the schema descriptor for created_at field.
|
||||
userDescCreatedAt := userFields[5].Descriptor()
|
||||
// user.DefaultCreatedAt holds the default value on creation for the created_at field.
|
||||
user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
|
||||
// userDescUpdatedAt is the schema descriptor for updated_at field.
|
||||
userDescUpdatedAt := userFields[6].Descriptor()
|
||||
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
|
||||
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
|
||||
// user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
|
||||
user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time)
|
||||
// userDescID is the schema descriptor for id field.
|
||||
userDescID := userFields[0].Descriptor()
|
||||
// user.DefaultID holds the default value on creation for the id field.
|
||||
user.DefaultID = userDescID.Default.(func() uuid.UUID)
|
||||
}
|
10
ent/runtime/runtime.go
Normal file
10
ent/runtime/runtime.go
Normal file
@ -0,0 +1,10 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package runtime
|
||||
|
||||
// The schema-stitching logic is generated in git.dotya.ml/mirre-mt/pcmt/ent/runtime.go
|
||||
|
||||
const (
|
||||
Version = "v0.11.10" // Version of ent codegen.
|
||||
Sum = "h1:iqn32ybY5HRW3xSAyMNdNKpZhKgMf1Zunsej9yPKUI8=" // Sum of ent codegen.
|
||||
)
|
45
ent/schema/user.go
Normal file
45
ent/schema/user.go
Normal file
@ -0,0 +1,45 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// User holds the schema definition for the User entity.
|
||||
type User struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the User.
|
||||
func (User) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.UUID("id", uuid.UUID{}).
|
||||
Default(uuid.New).
|
||||
Unique().
|
||||
Immutable(),
|
||||
field.String("username").
|
||||
NotEmpty().
|
||||
Unique(),
|
||||
field.String("password").
|
||||
Sensitive().
|
||||
NotEmpty(),
|
||||
field.Bool("is_admin").
|
||||
Default(false),
|
||||
field.Bool("is_active").
|
||||
Default(true),
|
||||
field.Time("created_at").
|
||||
Default(time.Now).
|
||||
Immutable(),
|
||||
field.Time("updated_at").
|
||||
Default(time.Now).
|
||||
UpdateDefault(time.Now),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the User.
|
||||
func (User) Edges() []ent.Edge {
|
||||
return nil
|
||||
}
|
210
ent/tx.go
Normal file
210
ent/tx.go
Normal file
@ -0,0 +1,210 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
)
|
||||
|
||||
// Tx is a transactional client that is created by calling Client.Tx().
|
||||
type Tx struct {
|
||||
config
|
||||
// User is the client for interacting with the User builders.
|
||||
User *UserClient
|
||||
|
||||
// lazily loaded.
|
||||
client *Client
|
||||
clientOnce sync.Once
|
||||
// ctx lives for the life of the transaction. It is
|
||||
// the same context used by the underlying connection.
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
type (
|
||||
// Committer is the interface that wraps the Commit method.
|
||||
Committer interface {
|
||||
Commit(context.Context, *Tx) error
|
||||
}
|
||||
|
||||
// The CommitFunc type is an adapter to allow the use of ordinary
|
||||
// function as a Committer. If f is a function with the appropriate
|
||||
// signature, CommitFunc(f) is a Committer that calls f.
|
||||
CommitFunc func(context.Context, *Tx) error
|
||||
|
||||
// CommitHook defines the "commit middleware". A function that gets a Committer
|
||||
// and returns a Committer. For example:
|
||||
//
|
||||
// hook := func(next ent.Committer) ent.Committer {
|
||||
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
|
||||
// // Do some stuff before.
|
||||
// if err := next.Commit(ctx, tx); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // Do some stuff after.
|
||||
// return nil
|
||||
// })
|
||||
// }
|
||||
//
|
||||
CommitHook func(Committer) Committer
|
||||
)
|
||||
|
||||
// Commit calls f(ctx, m).
|
||||
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
|
||||
return f(ctx, tx)
|
||||
}
|
||||
|
||||
// Commit commits the transaction.
|
||||
func (tx *Tx) Commit() error {
|
||||
txDriver := tx.config.driver.(*txDriver)
|
||||
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
|
||||
return txDriver.tx.Commit()
|
||||
})
|
||||
txDriver.mu.Lock()
|
||||
hooks := append([]CommitHook(nil), txDriver.onCommit...)
|
||||
txDriver.mu.Unlock()
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
fn = hooks[i](fn)
|
||||
}
|
||||
return fn.Commit(tx.ctx, tx)
|
||||
}
|
||||
|
||||
// OnCommit adds a hook to call on commit.
|
||||
func (tx *Tx) OnCommit(f CommitHook) {
|
||||
txDriver := tx.config.driver.(*txDriver)
|
||||
txDriver.mu.Lock()
|
||||
txDriver.onCommit = append(txDriver.onCommit, f)
|
||||
txDriver.mu.Unlock()
|
||||
}
|
||||
|
||||
type (
|
||||
// Rollbacker is the interface that wraps the Rollback method.
|
||||
Rollbacker interface {
|
||||
Rollback(context.Context, *Tx) error
|
||||
}
|
||||
|
||||
// The RollbackFunc type is an adapter to allow the use of ordinary
|
||||
// function as a Rollbacker. If f is a function with the appropriate
|
||||
// signature, RollbackFunc(f) is a Rollbacker that calls f.
|
||||
RollbackFunc func(context.Context, *Tx) error
|
||||
|
||||
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
|
||||
// and returns a Rollbacker. For example:
|
||||
//
|
||||
// hook := func(next ent.Rollbacker) ent.Rollbacker {
|
||||
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
|
||||
// // Do some stuff before.
|
||||
// if err := next.Rollback(ctx, tx); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // Do some stuff after.
|
||||
// return nil
|
||||
// })
|
||||
// }
|
||||
//
|
||||
RollbackHook func(Rollbacker) Rollbacker
|
||||
)
|
||||
|
||||
// Rollback calls f(ctx, m).
|
||||
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
|
||||
return f(ctx, tx)
|
||||
}
|
||||
|
||||
// Rollback rollbacks the transaction.
|
||||
func (tx *Tx) Rollback() error {
|
||||
txDriver := tx.config.driver.(*txDriver)
|
||||
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
|
||||
return txDriver.tx.Rollback()
|
||||
})
|
||||
txDriver.mu.Lock()
|
||||
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
|
||||
txDriver.mu.Unlock()
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
fn = hooks[i](fn)
|
||||
}
|
||||
return fn.Rollback(tx.ctx, tx)
|
||||
}
|
||||
|
||||
// OnRollback adds a hook to call on rollback.
|
||||
func (tx *Tx) OnRollback(f RollbackHook) {
|
||||
txDriver := tx.config.driver.(*txDriver)
|
||||
txDriver.mu.Lock()
|
||||
txDriver.onRollback = append(txDriver.onRollback, f)
|
||||
txDriver.mu.Unlock()
|
||||
}
|
||||
|
||||
// Client returns a Client that binds to current transaction.
|
||||
func (tx *Tx) Client() *Client {
|
||||
tx.clientOnce.Do(func() {
|
||||
tx.client = &Client{config: tx.config}
|
||||
tx.client.init()
|
||||
})
|
||||
return tx.client
|
||||
}
|
||||
|
||||
func (tx *Tx) init() {
|
||||
tx.User = NewUserClient(tx.config)
|
||||
}
|
||||
|
||||
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
|
||||
// The idea is to support transactions without adding any extra code to the builders.
|
||||
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
|
||||
// Commit and Rollback are nop for the internal builders and the user must call one
|
||||
// of them in order to commit or rollback the transaction.
|
||||
//
|
||||
// If a closed transaction is embedded in one of the generated entities, and the entity
|
||||
// applies a query, for example: User.QueryXXX(), the query will be executed
|
||||
// through the driver which created this transaction.
|
||||
//
|
||||
// Note that txDriver is not goroutine safe.
|
||||
type txDriver struct {
|
||||
// the driver we started the transaction from.
|
||||
drv dialect.Driver
|
||||
// tx is the underlying transaction.
|
||||
tx dialect.Tx
|
||||
// completion hooks.
|
||||
mu sync.Mutex
|
||||
onCommit []CommitHook
|
||||
onRollback []RollbackHook
|
||||
}
|
||||
|
||||
// newTx creates a new transactional driver.
|
||||
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
|
||||
tx, err := drv.Tx(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &txDriver{tx: tx, drv: drv}, nil
|
||||
}
|
||||
|
||||
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
|
||||
// from the internal builders. Should be called only by the internal builders.
|
||||
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
|
||||
|
||||
// Dialect returns the dialect of the driver we started the transaction from.
|
||||
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
|
||||
|
||||
// Close is a nop close.
|
||||
func (*txDriver) Close() error { return nil }
|
||||
|
||||
// Commit is a nop commit for the internal builders.
|
||||
// User must call `Tx.Commit` in order to commit the transaction.
|
||||
func (*txDriver) Commit() error { return nil }
|
||||
|
||||
// Rollback is a nop rollback for the internal builders.
|
||||
// User must call `Tx.Rollback` in order to rollback the transaction.
|
||||
func (*txDriver) Rollback() error { return nil }
|
||||
|
||||
// Exec calls tx.Exec.
|
||||
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
|
||||
return tx.tx.Exec(ctx, query, args, v)
|
||||
}
|
||||
|
||||
// Query calls tx.Query.
|
||||
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
|
||||
return tx.tx.Query(ctx, query, args, v)
|
||||
}
|
||||
|
||||
var _ dialect.Driver = (*txDriver)(nil)
|
153
ent/user.go
Normal file
153
ent/user.go
Normal file
@ -0,0 +1,153 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// User is the model entity for the User schema.
|
||||
type User struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID uuid.UUID `json:"id,omitempty"`
|
||||
// Username holds the value of the "username" field.
|
||||
Username string `json:"username,omitempty"`
|
||||
// Password holds the value of the "password" field.
|
||||
Password string `json:"-"`
|
||||
// IsAdmin holds the value of the "is_admin" field.
|
||||
IsAdmin bool `json:"is_admin,omitempty"`
|
||||
// IsActive holds the value of the "is_active" field.
|
||||
IsActive bool `json:"is_active,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"`
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*User) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case user.FieldIsAdmin, user.FieldIsActive:
|
||||
values[i] = new(sql.NullBool)
|
||||
case user.FieldUsername, user.FieldPassword:
|
||||
values[i] = new(sql.NullString)
|
||||
case user.FieldCreatedAt, user.FieldUpdatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
case user.FieldID:
|
||||
values[i] = new(uuid.UUID)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected column %q for type User", columns[i])
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the User fields.
|
||||
func (u *User) assignValues(columns []string, values []any) error {
|
||||
if m, n := len(values), len(columns); m < n {
|
||||
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
|
||||
}
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case user.FieldID:
|
||||
if value, ok := values[i].(*uuid.UUID); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value != nil {
|
||||
u.ID = *value
|
||||
}
|
||||
case user.FieldUsername:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field username", values[i])
|
||||
} else if value.Valid {
|
||||
u.Username = value.String
|
||||
}
|
||||
case user.FieldPassword:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field password", values[i])
|
||||
} else if value.Valid {
|
||||
u.Password = value.String
|
||||
}
|
||||
case user.FieldIsAdmin:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field is_admin", values[i])
|
||||
} else if value.Valid {
|
||||
u.IsAdmin = value.Bool
|
||||
}
|
||||
case user.FieldIsActive:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field is_active", values[i])
|
||||
} else if value.Valid {
|
||||
u.IsActive = value.Bool
|
||||
}
|
||||
case user.FieldCreatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field created_at", values[i])
|
||||
} else if value.Valid {
|
||||
u.CreatedAt = value.Time
|
||||
}
|
||||
case user.FieldUpdatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
|
||||
} else if value.Valid {
|
||||
u.UpdatedAt = value.Time
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this User.
|
||||
// Note that you need to call User.Unwrap() before calling this method if this User
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (u *User) Update() *UserUpdateOne {
|
||||
return NewUserClient(u.config).UpdateOne(u)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the User entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (u *User) Unwrap() *User {
|
||||
_tx, ok := u.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: User is not a transactional entity")
|
||||
}
|
||||
u.config.driver = _tx.drv
|
||||
return u
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (u *User) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("User(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", u.ID))
|
||||
builder.WriteString("username=")
|
||||
builder.WriteString(u.Username)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("password=<sensitive>")
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("is_admin=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.IsAdmin))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("is_active=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.IsActive))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("updated_at=")
|
||||
builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Users is a parsable slice of User.
|
||||
type Users []*User
|
70
ent/user/user.go
Normal file
70
ent/user/user.go
Normal file
@ -0,0 +1,70 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the user type in the database.
|
||||
Label = "user"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldUsername holds the string denoting the username field in the database.
|
||||
FieldUsername = "username"
|
||||
// FieldPassword holds the string denoting the password field in the database.
|
||||
FieldPassword = "password"
|
||||
// FieldIsAdmin holds the string denoting the is_admin field in the database.
|
||||
FieldIsAdmin = "is_admin"
|
||||
// FieldIsActive holds the string denoting the is_active field in the database.
|
||||
FieldIsActive = "is_active"
|
||||
// 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"
|
||||
// Table holds the table name of the user in the database.
|
||||
Table = "users"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for user fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldUsername,
|
||||
FieldPassword,
|
||||
FieldIsAdmin,
|
||||
FieldIsActive,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
|
||||
UsernameValidator func(string) error
|
||||
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
|
||||
PasswordValidator func(string) error
|
||||
// DefaultIsAdmin holds the default value on creation for the "is_admin" field.
|
||||
DefaultIsAdmin bool
|
||||
// DefaultIsActive holds the default value on creation for the "is_active" field.
|
||||
DefaultIsActive bool
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
|
||||
DefaultUpdatedAt func() time.Time
|
||||
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
|
||||
UpdateDefaultUpdatedAt func() time.Time
|
||||
// DefaultID holds the default value on creation for the "id" field.
|
||||
DefaultID func() uuid.UUID
|
||||
)
|
348
ent/user/where.go
Normal file
348
ent/user/where.go
Normal file
@ -0,0 +1,348 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/predicate"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id uuid.UUID) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
|
||||
func Username(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldUsername, v))
|
||||
}
|
||||
|
||||
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
|
||||
func Password(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldPassword, v))
|
||||
}
|
||||
|
||||
// IsAdmin applies equality check predicate on the "is_admin" field. It's identical to IsAdminEQ.
|
||||
func IsAdmin(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldIsAdmin, v))
|
||||
}
|
||||
|
||||
// IsActive applies equality check predicate on the "is_active" field. It's identical to IsActiveEQ.
|
||||
func IsActive(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldIsActive, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UsernameEQ applies the EQ predicate on the "username" field.
|
||||
func UsernameEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameNEQ applies the NEQ predicate on the "username" field.
|
||||
func UsernameNEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameIn applies the In predicate on the "username" field.
|
||||
func UsernameIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldUsername, vs...))
|
||||
}
|
||||
|
||||
// UsernameNotIn applies the NotIn predicate on the "username" field.
|
||||
func UsernameNotIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldUsername, vs...))
|
||||
}
|
||||
|
||||
// UsernameGT applies the GT predicate on the "username" field.
|
||||
func UsernameGT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameGTE applies the GTE predicate on the "username" field.
|
||||
func UsernameGTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameLT applies the LT predicate on the "username" field.
|
||||
func UsernameLT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameLTE applies the LTE predicate on the "username" field.
|
||||
func UsernameLTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameContains applies the Contains predicate on the "username" field.
|
||||
func UsernameContains(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContains(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
|
||||
func UsernameHasPrefix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasPrefix(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
|
||||
func UsernameHasSuffix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasSuffix(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
|
||||
func UsernameEqualFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldUsername, v))
|
||||
}
|
||||
|
||||
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
|
||||
func UsernameContainsFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldUsername, v))
|
||||
}
|
||||
|
||||
// PasswordEQ applies the EQ predicate on the "password" field.
|
||||
func PasswordEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordNEQ applies the NEQ predicate on the "password" field.
|
||||
func PasswordNEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordIn applies the In predicate on the "password" field.
|
||||
func PasswordIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldPassword, vs...))
|
||||
}
|
||||
|
||||
// PasswordNotIn applies the NotIn predicate on the "password" field.
|
||||
func PasswordNotIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldPassword, vs...))
|
||||
}
|
||||
|
||||
// PasswordGT applies the GT predicate on the "password" field.
|
||||
func PasswordGT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordGTE applies the GTE predicate on the "password" field.
|
||||
func PasswordGTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordLT applies the LT predicate on the "password" field.
|
||||
func PasswordLT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordLTE applies the LTE predicate on the "password" field.
|
||||
func PasswordLTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordContains applies the Contains predicate on the "password" field.
|
||||
func PasswordContains(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContains(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
|
||||
func PasswordHasPrefix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasPrefix(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
|
||||
func PasswordHasSuffix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasSuffix(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
|
||||
func PasswordEqualFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldPassword, v))
|
||||
}
|
||||
|
||||
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
|
||||
func PasswordContainsFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldPassword, v))
|
||||
}
|
||||
|
||||
// IsAdminEQ applies the EQ predicate on the "is_admin" field.
|
||||
func IsAdminEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldIsAdmin, v))
|
||||
}
|
||||
|
||||
// IsAdminNEQ applies the NEQ predicate on the "is_admin" field.
|
||||
func IsAdminNEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldIsAdmin, v))
|
||||
}
|
||||
|
||||
// IsActiveEQ applies the EQ predicate on the "is_active" field.
|
||||
func IsActiveEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldIsActive, v))
|
||||
}
|
||||
|
||||
// IsActiveNEQ applies the NEQ predicate on the "is_active" field.
|
||||
func IsActiveNEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldIsActive, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.User) predicate.User {
|
||||
return predicate.User(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.User) predicate.User {
|
||||
return predicate.User(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.User) predicate.User {
|
||||
return predicate.User(func(s *sql.Selector) {
|
||||
p(s.Not())
|
||||
})
|
||||
}
|
333
ent/user_create.go
Normal file
333
ent/user_create.go
Normal file
@ -0,0 +1,333 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// UserCreate is the builder for creating a User entity.
|
||||
type UserCreate struct {
|
||||
config
|
||||
mutation *UserMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetUsername sets the "username" field.
|
||||
func (uc *UserCreate) SetUsername(s string) *UserCreate {
|
||||
uc.mutation.SetUsername(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetPassword sets the "password" field.
|
||||
func (uc *UserCreate) SetPassword(s string) *UserCreate {
|
||||
uc.mutation.SetPassword(s)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetIsAdmin sets the "is_admin" field.
|
||||
func (uc *UserCreate) SetIsAdmin(b bool) *UserCreate {
|
||||
uc.mutation.SetIsAdmin(b)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableIsAdmin sets the "is_admin" field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableIsAdmin(b *bool) *UserCreate {
|
||||
if b != nil {
|
||||
uc.SetIsAdmin(*b)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetIsActive sets the "is_active" field.
|
||||
func (uc *UserCreate) SetIsActive(b bool) *UserCreate {
|
||||
uc.mutation.SetIsActive(b)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableIsActive sets the "is_active" field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableIsActive(b *bool) *UserCreate {
|
||||
if b != nil {
|
||||
uc.SetIsActive(*b)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (uc *UserCreate) SetCreatedAt(t time.Time) *UserCreate {
|
||||
uc.mutation.SetCreatedAt(t)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableCreatedAt(t *time.Time) *UserCreate {
|
||||
if t != nil {
|
||||
uc.SetCreatedAt(*t)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (uc *UserCreate) SetUpdatedAt(t time.Time) *UserCreate {
|
||||
uc.mutation.SetUpdatedAt(t)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableUpdatedAt(t *time.Time) *UserCreate {
|
||||
if t != nil {
|
||||
uc.SetUpdatedAt(*t)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (uc *UserCreate) SetID(u uuid.UUID) *UserCreate {
|
||||
uc.mutation.SetID(u)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableID sets the "id" field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableID(u *uuid.UUID) *UserCreate {
|
||||
if u != nil {
|
||||
uc.SetID(*u)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (uc *UserCreate) Mutation() *UserMutation {
|
||||
return uc.mutation
|
||||
}
|
||||
|
||||
// Save creates the User in the database.
|
||||
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
|
||||
uc.defaults()
|
||||
return withHooks[*User, UserMutation](ctx, uc.sqlSave, uc.mutation, uc.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (uc *UserCreate) SaveX(ctx context.Context) *User {
|
||||
v, err := uc.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (uc *UserCreate) Exec(ctx context.Context) error {
|
||||
_, err := uc.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (uc *UserCreate) ExecX(ctx context.Context) {
|
||||
if err := uc.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (uc *UserCreate) defaults() {
|
||||
if _, ok := uc.mutation.IsAdmin(); !ok {
|
||||
v := user.DefaultIsAdmin
|
||||
uc.mutation.SetIsAdmin(v)
|
||||
}
|
||||
if _, ok := uc.mutation.IsActive(); !ok {
|
||||
v := user.DefaultIsActive
|
||||
uc.mutation.SetIsActive(v)
|
||||
}
|
||||
if _, ok := uc.mutation.CreatedAt(); !ok {
|
||||
v := user.DefaultCreatedAt()
|
||||
uc.mutation.SetCreatedAt(v)
|
||||
}
|
||||
if _, ok := uc.mutation.UpdatedAt(); !ok {
|
||||
v := user.DefaultUpdatedAt()
|
||||
uc.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
if _, ok := uc.mutation.ID(); !ok {
|
||||
v := user.DefaultID()
|
||||
uc.mutation.SetID(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (uc *UserCreate) check() error {
|
||||
if _, ok := uc.mutation.Username(); !ok {
|
||||
return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "User.username"`)}
|
||||
}
|
||||
if v, ok := uc.mutation.Username(); ok {
|
||||
if err := user.UsernameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := uc.mutation.Password(); !ok {
|
||||
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "User.password"`)}
|
||||
}
|
||||
if v, ok := uc.mutation.Password(); ok {
|
||||
if err := user.PasswordValidator(v); err != nil {
|
||||
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := uc.mutation.IsAdmin(); !ok {
|
||||
return &ValidationError{Name: "is_admin", err: errors.New(`ent: missing required field "User.is_admin"`)}
|
||||
}
|
||||
if _, ok := uc.mutation.IsActive(); !ok {
|
||||
return &ValidationError{Name: "is_active", err: errors.New(`ent: missing required field "User.is_active"`)}
|
||||
}
|
||||
if _, ok := uc.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "User.created_at"`)}
|
||||
}
|
||||
if _, ok := uc.mutation.UpdatedAt(); !ok {
|
||||
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "User.updated_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
|
||||
if err := uc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := uc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, uc.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
|
||||
}
|
||||
}
|
||||
uc.mutation.id = &_node.ID
|
||||
uc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &User{config: uc.config}
|
||||
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
|
||||
)
|
||||
if id, ok := uc.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = &id
|
||||
}
|
||||
if value, ok := uc.mutation.Username(); ok {
|
||||
_spec.SetField(user.FieldUsername, field.TypeString, value)
|
||||
_node.Username = value
|
||||
}
|
||||
if value, ok := uc.mutation.Password(); ok {
|
||||
_spec.SetField(user.FieldPassword, field.TypeString, value)
|
||||
_node.Password = value
|
||||
}
|
||||
if value, ok := uc.mutation.IsAdmin(); ok {
|
||||
_spec.SetField(user.FieldIsAdmin, field.TypeBool, value)
|
||||
_node.IsAdmin = value
|
||||
}
|
||||
if value, ok := uc.mutation.IsActive(); ok {
|
||||
_spec.SetField(user.FieldIsActive, field.TypeBool, value)
|
||||
_node.IsActive = value
|
||||
}
|
||||
if value, ok := uc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := uc.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// UserCreateBulk is the builder for creating many User entities in bulk.
|
||||
type UserCreateBulk struct {
|
||||
config
|
||||
builders []*UserCreate
|
||||
}
|
||||
|
||||
// Save creates the User entities in the database.
|
||||
func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
|
||||
specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
|
||||
nodes := make([]*User, len(ucb.builders))
|
||||
mutators := make([]Mutator, len(ucb.builders))
|
||||
for i := range ucb.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := ucb.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*UserMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
var err error
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, ucb.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, ucb.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, ucb.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User {
|
||||
v, err := ucb.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (ucb *UserCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := ucb.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ucb *UserCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := ucb.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
88
ent/user_delete.go
Normal file
88
ent/user_delete.go
Normal file
@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/predicate"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
)
|
||||
|
||||
// UserDelete is the builder for deleting a User entity.
|
||||
type UserDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserDelete builder.
|
||||
func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete {
|
||||
ud.mutation.Where(ps...)
|
||||
return ud
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (ud *UserDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks[int, UserMutation](ctx, ud.sqlExec, ud.mutation, ud.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (ud *UserDelete) ExecX(ctx context.Context) int {
|
||||
n, err := ud.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
|
||||
if ps := ud.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
ud.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// UserDeleteOne is the builder for deleting a single User entity.
|
||||
type UserDeleteOne struct {
|
||||
ud *UserDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserDelete builder.
|
||||
func (udo *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
|
||||
udo.ud.mutation.Where(ps...)
|
||||
return udo
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (udo *UserDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := udo.ud.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{user.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (udo *UserDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := udo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
527
ent/user_query.go
Normal file
527
ent/user_query.go
Normal file
@ -0,0 +1,527 @@
|
||||
// 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"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/predicate"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// UserQuery is the builder for querying User entities.
|
||||
type UserQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []OrderFunc
|
||||
inters []Interceptor
|
||||
predicates []predicate.User
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the UserQuery builder.
|
||||
func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery {
|
||||
uq.predicates = append(uq.predicates, ps...)
|
||||
return uq
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (uq *UserQuery) Limit(limit int) *UserQuery {
|
||||
uq.ctx.Limit = &limit
|
||||
return uq
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (uq *UserQuery) Offset(offset int) *UserQuery {
|
||||
uq.ctx.Offset = &offset
|
||||
return uq
|
||||
}
|
||||
|
||||
// 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 (uq *UserQuery) Unique(unique bool) *UserQuery {
|
||||
uq.ctx.Unique = &unique
|
||||
return uq
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (uq *UserQuery) Order(o ...OrderFunc) *UserQuery {
|
||||
uq.order = append(uq.order, o...)
|
||||
return uq
|
||||
}
|
||||
|
||||
// First returns the first User entity from the query.
|
||||
// Returns a *NotFoundError when no User was found.
|
||||
func (uq *UserQuery) First(ctx context.Context) (*User, error) {
|
||||
nodes, err := uq.Limit(1).All(setContextOp(ctx, uq.ctx, "First"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{user.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (uq *UserQuery) FirstX(ctx context.Context) *User {
|
||||
node, err := uq.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first User ID from the query.
|
||||
// Returns a *NotFoundError when no User ID was found.
|
||||
func (uq *UserQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = uq.Limit(1).IDs(setContextOp(ctx, uq.ctx, "FirstID")); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{user.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (uq *UserQuery) FirstIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := uq.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single User entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one User entity is found.
|
||||
// Returns a *NotFoundError when no User entities are found.
|
||||
func (uq *UserQuery) Only(ctx context.Context) (*User, error) {
|
||||
nodes, err := uq.Limit(2).All(setContextOp(ctx, uq.ctx, "Only"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{user.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{user.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (uq *UserQuery) OnlyX(ctx context.Context) *User {
|
||||
node, err := uq.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only User ID in the query.
|
||||
// Returns a *NotSingularError when more than one User ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (uq *UserQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
|
||||
var ids []uuid.UUID
|
||||
if ids, err = uq.Limit(2).IDs(setContextOp(ctx, uq.ctx, "OnlyID")); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{user.Label}
|
||||
default:
|
||||
err = &NotSingularError{user.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (uq *UserQuery) OnlyIDX(ctx context.Context) uuid.UUID {
|
||||
id, err := uq.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Users.
|
||||
func (uq *UserQuery) All(ctx context.Context) ([]*User, error) {
|
||||
ctx = setContextOp(ctx, uq.ctx, "All")
|
||||
if err := uq.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*User, *UserQuery]()
|
||||
return withInterceptors[[]*User](ctx, uq, qr, uq.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (uq *UserQuery) AllX(ctx context.Context) []*User {
|
||||
nodes, err := uq.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of User IDs.
|
||||
func (uq *UserQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
|
||||
if uq.ctx.Unique == nil && uq.path != nil {
|
||||
uq.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, uq.ctx, "IDs")
|
||||
if err = uq.Select(user.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (uq *UserQuery) IDsX(ctx context.Context) []uuid.UUID {
|
||||
ids, err := uq.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (uq *UserQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, uq.ctx, "Count")
|
||||
if err := uq.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, uq, querierCount[*UserQuery](), uq.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (uq *UserQuery) CountX(ctx context.Context) int {
|
||||
count, err := uq.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (uq *UserQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, uq.ctx, "Exist")
|
||||
switch _, err := uq.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (uq *UserQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := uq.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (uq *UserQuery) Clone() *UserQuery {
|
||||
if uq == nil {
|
||||
return nil
|
||||
}
|
||||
return &UserQuery{
|
||||
config: uq.config,
|
||||
ctx: uq.ctx.Clone(),
|
||||
order: append([]OrderFunc{}, uq.order...),
|
||||
inters: append([]Interceptor{}, uq.inters...),
|
||||
predicates: append([]predicate.User{}, uq.predicates...),
|
||||
// clone intermediate query.
|
||||
sql: uq.sql.Clone(),
|
||||
path: uq.path,
|
||||
}
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Username string `json:"username,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// GroupBy(user.FieldUsername).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
|
||||
uq.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &UserGroupBy{build: uq}
|
||||
grbuild.flds = &uq.ctx.Fields
|
||||
grbuild.label = user.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Username string `json:"username,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// Select(user.FieldUsername).
|
||||
// Scan(ctx, &v)
|
||||
func (uq *UserQuery) Select(fields ...string) *UserSelect {
|
||||
uq.ctx.Fields = append(uq.ctx.Fields, fields...)
|
||||
sbuild := &UserSelect{UserQuery: uq}
|
||||
sbuild.label = user.Label
|
||||
sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a UserSelect configured with the given aggregations.
|
||||
func (uq *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
|
||||
return uq.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (uq *UserQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range uq.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, uq); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range uq.ctx.Fields {
|
||||
if !user.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if uq.path != nil {
|
||||
prev, err := uq.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
uq.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
|
||||
var (
|
||||
nodes = []*User{}
|
||||
_spec = uq.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*User).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &User{config: uq.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := uq.querySpec()
|
||||
_spec.Node.Columns = uq.ctx.Fields
|
||||
if len(uq.ctx.Fields) > 0 {
|
||||
_spec.Unique = uq.ctx.Unique != nil && *uq.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, uq.driver, _spec)
|
||||
}
|
||||
|
||||
func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
|
||||
_spec.From = uq.sql
|
||||
if unique := uq.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if uq.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := uq.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != user.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := uq.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := uq.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := uq.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := uq.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(uq.driver.Dialect())
|
||||
t1 := builder.Table(user.Table)
|
||||
columns := uq.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = user.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if uq.sql != nil {
|
||||
selector = uq.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if uq.ctx.Unique != nil && *uq.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range uq.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range uq.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := uq.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := uq.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// UserGroupBy is the group-by builder for User entities.
|
||||
type UserGroupBy struct {
|
||||
selector
|
||||
build *UserQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
|
||||
ugb.fns = append(ugb.fns, fns...)
|
||||
return ugb
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (ugb *UserGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, ugb.build.ctx, "GroupBy")
|
||||
if err := ugb.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v)
|
||||
}
|
||||
|
||||
func (ugb *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(ugb.fns))
|
||||
for _, fn := range ugb.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*ugb.flds)+len(ugb.fns))
|
||||
for _, f := range *ugb.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*ugb.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := ugb.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// UserSelect is the builder for selecting fields of User entities.
|
||||
type UserSelect struct {
|
||||
*UserQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (us *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
|
||||
us.fns = append(us.fns, fns...)
|
||||
return us
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (us *UserSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, us.ctx, "Select")
|
||||
if err := us.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*UserQuery, *UserSelect](ctx, us.UserQuery, us, us.inters, v)
|
||||
}
|
||||
|
||||
func (us *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(us.fns))
|
||||
for _, fn := range us.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*us.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := us.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
352
ent/user_update.go
Normal file
352
ent/user_update.go
Normal file
@ -0,0 +1,352 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/predicate"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
)
|
||||
|
||||
// UserUpdate is the builder for updating User entities.
|
||||
type UserUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserUpdate builder.
|
||||
func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
|
||||
uu.mutation.Where(ps...)
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetUsername sets the "username" field.
|
||||
func (uu *UserUpdate) SetUsername(s string) *UserUpdate {
|
||||
uu.mutation.SetUsername(s)
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetPassword sets the "password" field.
|
||||
func (uu *UserUpdate) SetPassword(s string) *UserUpdate {
|
||||
uu.mutation.SetPassword(s)
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetIsAdmin sets the "is_admin" field.
|
||||
func (uu *UserUpdate) SetIsAdmin(b bool) *UserUpdate {
|
||||
uu.mutation.SetIsAdmin(b)
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetNillableIsAdmin sets the "is_admin" field if the given value is not nil.
|
||||
func (uu *UserUpdate) SetNillableIsAdmin(b *bool) *UserUpdate {
|
||||
if b != nil {
|
||||
uu.SetIsAdmin(*b)
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetIsActive sets the "is_active" field.
|
||||
func (uu *UserUpdate) SetIsActive(b bool) *UserUpdate {
|
||||
uu.mutation.SetIsActive(b)
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetNillableIsActive sets the "is_active" field if the given value is not nil.
|
||||
func (uu *UserUpdate) SetNillableIsActive(b *bool) *UserUpdate {
|
||||
if b != nil {
|
||||
uu.SetIsActive(*b)
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (uu *UserUpdate) SetUpdatedAt(t time.Time) *UserUpdate {
|
||||
uu.mutation.SetUpdatedAt(t)
|
||||
return uu
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (uu *UserUpdate) Mutation() *UserMutation {
|
||||
return uu.mutation
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
|
||||
uu.defaults()
|
||||
return withHooks[int, UserMutation](ctx, uu.sqlSave, uu.mutation, uu.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (uu *UserUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := uu.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (uu *UserUpdate) Exec(ctx context.Context) error {
|
||||
_, err := uu.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (uu *UserUpdate) ExecX(ctx context.Context) {
|
||||
if err := uu.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (uu *UserUpdate) defaults() {
|
||||
if _, ok := uu.mutation.UpdatedAt(); !ok {
|
||||
v := user.UpdateDefaultUpdatedAt()
|
||||
uu.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (uu *UserUpdate) check() error {
|
||||
if v, ok := uu.mutation.Username(); ok {
|
||||
if err := user.UsernameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := uu.mutation.Password(); ok {
|
||||
if err := user.PasswordValidator(v); err != nil {
|
||||
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
||||
if err := uu.check(); err != nil {
|
||||
return n, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
|
||||
if ps := uu.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := uu.mutation.Username(); ok {
|
||||
_spec.SetField(user.FieldUsername, field.TypeString, value)
|
||||
}
|
||||
if value, ok := uu.mutation.Password(); ok {
|
||||
_spec.SetField(user.FieldPassword, field.TypeString, value)
|
||||
}
|
||||
if value, ok := uu.mutation.IsAdmin(); ok {
|
||||
_spec.SetField(user.FieldIsAdmin, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := uu.mutation.IsActive(); ok {
|
||||
_spec.SetField(user.FieldIsActive, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := uu.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{user.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
uu.mutation.done = true
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// UserUpdateOne is the builder for updating a single User entity.
|
||||
type UserUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// SetUsername sets the "username" field.
|
||||
func (uuo *UserUpdateOne) SetUsername(s string) *UserUpdateOne {
|
||||
uuo.mutation.SetUsername(s)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetPassword sets the "password" field.
|
||||
func (uuo *UserUpdateOne) SetPassword(s string) *UserUpdateOne {
|
||||
uuo.mutation.SetPassword(s)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetIsAdmin sets the "is_admin" field.
|
||||
func (uuo *UserUpdateOne) SetIsAdmin(b bool) *UserUpdateOne {
|
||||
uuo.mutation.SetIsAdmin(b)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetNillableIsAdmin sets the "is_admin" field if the given value is not nil.
|
||||
func (uuo *UserUpdateOne) SetNillableIsAdmin(b *bool) *UserUpdateOne {
|
||||
if b != nil {
|
||||
uuo.SetIsAdmin(*b)
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetIsActive sets the "is_active" field.
|
||||
func (uuo *UserUpdateOne) SetIsActive(b bool) *UserUpdateOne {
|
||||
uuo.mutation.SetIsActive(b)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetNillableIsActive sets the "is_active" field if the given value is not nil.
|
||||
func (uuo *UserUpdateOne) SetNillableIsActive(b *bool) *UserUpdateOne {
|
||||
if b != nil {
|
||||
uuo.SetIsActive(*b)
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (uuo *UserUpdateOne) SetUpdatedAt(t time.Time) *UserUpdateOne {
|
||||
uuo.mutation.SetUpdatedAt(t)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (uuo *UserUpdateOne) Mutation() *UserMutation {
|
||||
return uuo.mutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserUpdate builder.
|
||||
func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
|
||||
uuo.mutation.Where(ps...)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
|
||||
uuo.fields = append([]string{field}, fields...)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated User entity.
|
||||
func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
|
||||
uuo.defaults()
|
||||
return withHooks[*User, UserMutation](ctx, uuo.sqlSave, uuo.mutation, uuo.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User {
|
||||
node, err := uuo.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (uuo *UserUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := uuo.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (uuo *UserUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := uuo.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (uuo *UserUpdateOne) defaults() {
|
||||
if _, ok := uuo.mutation.UpdatedAt(); !ok {
|
||||
v := user.UpdateDefaultUpdatedAt()
|
||||
uuo.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (uuo *UserUpdateOne) check() error {
|
||||
if v, ok := uuo.mutation.Username(); ok {
|
||||
if err := user.UsernameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := uuo.mutation.Password(); ok {
|
||||
if err := user.PasswordValidator(v); err != nil {
|
||||
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
|
||||
if err := uuo.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
|
||||
id, ok := uuo.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := uuo.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
|
||||
for _, f := range fields {
|
||||
if !user.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != user.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := uuo.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := uuo.mutation.Username(); ok {
|
||||
_spec.SetField(user.FieldUsername, field.TypeString, value)
|
||||
}
|
||||
if value, ok := uuo.mutation.Password(); ok {
|
||||
_spec.SetField(user.FieldPassword, field.TypeString, value)
|
||||
}
|
||||
if value, ok := uuo.mutation.IsAdmin(); ok {
|
||||
_spec.SetField(user.FieldIsAdmin, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := uuo.mutation.IsActive(); ok {
|
||||
_spec.SetField(user.FieldIsActive, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := uuo.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
_node = &User{config: uuo.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{user.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
uuo.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
32
go.mod
32
go.mod
@ -3,22 +3,52 @@ module git.dotya.ml/mirre-mt/pcmt
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.11.10
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/labstack/echo/v4 v4.10.2
|
||||
github.com/philandstuff/dhall-golang/v6 v6.0.2
|
||||
github.com/xiaoqidun/entps v0.0.0-20230328150929-94b1b92d8c03
|
||||
golang.org/x/crypto v0.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
ariga.io/atlas v0.9.2-0.20230303073438-03a4779a6338 // indirect
|
||||
github.com/agext/levenshtein v1.2.1 // indirect
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fxamacker/cbor/v2 v2.2.1-0.20200511212021-28e39be4a84f // indirect
|
||||
github.com/go-openapi/inflect v0.19.0 // indirect
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/hashicorp/hcl/v2 v2.13.0 // indirect
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
|
||||
github.com/labstack/gommon v0.4.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
golang.org/x/crypto v0.6.0 // indirect
|
||||
github.com/zclconf/go-cty v1.8.0 // indirect
|
||||
golang.org/x/mod v0.8.0 // indirect
|
||||
golang.org/x/net v0.7.0 // indirect
|
||||
golang.org/x/sys v0.5.0 // indirect
|
||||
golang.org/x/text v0.7.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
golang.org/x/tools v0.6.1-0.20230222164832-25d2519c8696 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
lukechampine.com/uint128 v1.2.0 // indirect
|
||||
modernc.org/cc/v3 v3.40.0 // indirect
|
||||
modernc.org/ccgo/v3 v3.16.13 // indirect
|
||||
modernc.org/libc v1.22.3 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/opt v0.1.3 // indirect
|
||||
modernc.org/sqlite v1.21.1 // indirect
|
||||
modernc.org/strutil v1.1.3 // indirect
|
||||
modernc.org/token v1.0.1 // indirect
|
||||
)
|
||||
|
95
go.sum
95
go.sum
@ -1,20 +1,52 @@
|
||||
ariga.io/atlas v0.9.2-0.20230303073438-03a4779a6338 h1:8kmSV3mbQKn0niZ/EdE11uhFvFKiW1VlaqVBIYOyahM=
|
||||
ariga.io/atlas v0.9.2-0.20230303073438-03a4779a6338/go.mod h1:T230JFcENj4ZZzMkZrXFDSkv+2kXkUgpJ5FQQ5hMcKU=
|
||||
entgo.io/ent v0.11.10 h1:iqn32ybY5HRW3xSAyMNdNKpZhKgMf1Zunsej9yPKUI8=
|
||||
entgo.io/ent v0.11.10/go.mod h1:mzTZ0trE+jCQw/fnzijbm5Mck/l8Gbg7gC/+L1COyzM=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
|
||||
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
|
||||
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fxamacker/cbor/v2 v2.2.1-0.20200511212021-28e39be4a84f h1:lvGFo/tDOSQ4FKu0d2694s8XyOfAL6FLR9DCD5BIUW4=
|
||||
github.com/fxamacker/cbor/v2 v2.2.1-0.20200511212021-28e39be4a84f/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo=
|
||||
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
|
||||
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
|
||||
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc=
|
||||
github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0=
|
||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4=
|
||||
github.com/labstack/echo/v4 v4.10.2 h1:n1jAhnq/elIFTHr1EYpiYtyKgx4RW9ccVgkqByZaN2M=
|
||||
github.com/labstack/echo/v4 v4.10.2/go.mod h1:OEyqf2//K1DFdE57vw2DRgWY0M7s65IVQO2FzvI4J5k=
|
||||
github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8=
|
||||
@ -28,6 +60,9 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
|
||||
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
@ -35,32 +70,48 @@ github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/philandstuff/dhall-golang/v6 v6.0.2 h1:jv8fi4ZYiFe6uGrprx6dY7L3xPcgmEqWZo3s8ABCzkw=
|
||||
github.com/philandstuff/dhall-golang/v6 v6.0.2/go.mod h1:XRoxjsqZM2y7KPFhjV7CSVdWpV5CwuTzGjAY/v+1SUU=
|
||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
|
||||
github.com/urfave/cli/v2 v2.2.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4=
|
||||
github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/xiaoqidun/entps v0.0.0-20230328150929-94b1b92d8c03 h1:vlehC7KJYZsRIDiihYR6dE5rQ6UqcKIp+hmuQTxVWHI=
|
||||
github.com/xiaoqidun/entps v0.0.0-20230328150929-94b1b92d8c03/go.mod h1:yrX8Sw34syrIn4GxVsuDk21AicyB/wooQEUjmNj3wbE=
|
||||
github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA=
|
||||
github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@ -71,10 +122,21 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
|
||||
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.6.1-0.20230222164832-25d2519c8696 h1:8985/C5IvACpd9DDXckSnjSBLKDgbxXiyODgi94zOPM=
|
||||
golang.org/x/tools v0.6.1-0.20230222164832-25d2519c8696/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
|
||||
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
@ -82,8 +144,33 @@ gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMy
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=
|
||||
lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
|
||||
modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw=
|
||||
modernc.org/cc/v3 v3.40.0/go.mod h1:/bTg4dnWkSXowUO6ssQKnOV0yMVxDYNIsIrzqTFDGH0=
|
||||
modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw=
|
||||
modernc.org/ccgo/v3 v3.16.13/go.mod h1:2Quk+5YgpImhPjv2Qsob1DnZ/4som1lJTodubIcoUkY=
|
||||
modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=
|
||||
modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=
|
||||
modernc.org/libc v1.22.3 h1:D/g6O5ftAfavceqlLOFwaZuA5KYafKwmr30A6iSqoyY=
|
||||
modernc.org/libc v1.22.3/go.mod h1:MQrloYP209xa2zHome2a8HLiLm6k0UT8CoHpV74tOFw=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
|
||||
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sqlite v1.21.1 h1:GyDFqNnESLOhwwDRaHGdp2jKLDzpyT/rNLglX3ZkMSU=
|
||||
modernc.org/sqlite v1.21.1/go.mod h1:XwQ0wZPIh1iKb5mkvCJ3szzbhk+tykC8ZWqTRTgYRwI=
|
||||
modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=
|
||||
modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=
|
||||
modernc.org/tcl v1.15.1 h1:mOQwiEK4p7HruMZcwKTZPw/aqtGM4aY00uzWhlKKYws=
|
||||
modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg=
|
||||
modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
modernc.org/z v1.7.0 h1:xkDw/KepgEjeizO2sNco+hqYkU12taxQFqPEmgm1GWE=
|
||||
|
39
handlers/config.go
Normal file
39
handlers/config.go
Normal file
@ -0,0 +1,39 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"log"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/config"
|
||||
)
|
||||
|
||||
var (
|
||||
conf *config.Config
|
||||
appver string
|
||||
)
|
||||
|
||||
func setConfig(c *config.Config) {
|
||||
if c != nil {
|
||||
log.Printf("setting handler config to %#v", conf)
|
||||
// c = conf
|
||||
log.Printf("set handler config to %#v", c)
|
||||
conf = c
|
||||
} else {
|
||||
log.Println("error passing conf to handlers")
|
||||
}
|
||||
}
|
||||
|
||||
func getConfig() *config.Config {
|
||||
return conf
|
||||
}
|
||||
|
||||
func setAppVer(v string) {
|
||||
log.Printf("handlers version: %s", v)
|
||||
appver = v
|
||||
}
|
||||
|
||||
func InitHandlers(version string, appconf *config.Config, tmpls fs.FS) {
|
||||
setConfig(appconf)
|
||||
setAppVer(version)
|
||||
initTemplates(tmpls)
|
||||
}
|
@ -1,13 +1,637 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||||
moduser "git.dotya.ml/mirre-mt/pcmt/modules/user"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type tplMap map[string]*template.Template
|
||||
|
||||
var (
|
||||
// tmpl *template.Template
|
||||
tmpls = template.New("")
|
||||
templateMap tplMap
|
||||
tmplFS fs.FS
|
||||
)
|
||||
|
||||
func listAllTmpls() []string {
|
||||
files, err := filepath.Glob("templates/*.tmpl")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// log.Println(files)
|
||||
for i, v := range files {
|
||||
files[i] = strings.TrimPrefix(v, "templates/")
|
||||
}
|
||||
|
||||
log.Println("returning files")
|
||||
return files
|
||||
}
|
||||
|
||||
func setFuncMap(t *template.Template) {
|
||||
t = t.Funcs(template.FuncMap{
|
||||
"ifIE": func() template.HTML { return template.HTML("<!--[if IE]>") },
|
||||
"endifIE": func() template.HTML { return template.HTML("<![endif]>") },
|
||||
"htmlSafe": func(html string) template.HTML {
|
||||
return template.HTML(html)
|
||||
},
|
||||
"pageIs": func(want, got string) bool {
|
||||
log.Printf("want: %s, got: %s", want, got)
|
||||
if want == got {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func getFuncMap() []template.FuncMap {
|
||||
return []template.FuncMap{
|
||||
map[string]interface{}{
|
||||
"ifIE": func() template.HTML { return template.HTML("<!--[if IE]>") },
|
||||
"endifIE": func() template.HTML { return template.HTML("<![endif]>") },
|
||||
"htmlSafe": func(html string) template.HTML {
|
||||
return template.HTML(html)
|
||||
},
|
||||
"pageIs": func(want, got string) bool {
|
||||
if want == got {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func initTemplates(f fs.FS) {
|
||||
// tmpls := tmpl
|
||||
log.Println(tmplFS == nil)
|
||||
|
||||
if f != nil || f != tmplFS {
|
||||
tmplFS = f
|
||||
}
|
||||
log.Println(tmplFS == nil)
|
||||
|
||||
// for _, funcs := range getFuncMap() {
|
||||
// // log.Println(funcs)
|
||||
// tmpls.Funcs(funcs)
|
||||
// }
|
||||
setFuncMap(tmpls)
|
||||
|
||||
// tmpls, err := tmpls.ParseFS(f, listAllTmpls()...)
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
|
||||
allTmpls := listAllTmpls()
|
||||
|
||||
// ensure this fails at compile time, if at all ("Must").
|
||||
tmpls = template.Must(tmpls.ParseFS(tmplFS, allTmpls...))
|
||||
makeTplMap(tmpls)
|
||||
|
||||
// tp := make(tplMap, len(allTmpls))
|
||||
// for _, v := range allTmpls {
|
||||
// tp[v] = tmpls.Lookup(v)
|
||||
// }
|
||||
//
|
||||
// templateMap = tp
|
||||
|
||||
// tmpl = tmpls
|
||||
}
|
||||
|
||||
func makeTplMap(tpl *template.Template) {
|
||||
allTmpls := listAllTmpls()
|
||||
var tp tplMap
|
||||
if templateMap == nil {
|
||||
tp = make(tplMap, len(allTmpls))
|
||||
} else {
|
||||
tp = templateMap
|
||||
}
|
||||
|
||||
for _, v := range allTmpls {
|
||||
tp[v] = tpl.Lookup(v)
|
||||
}
|
||||
|
||||
templateMap = tp
|
||||
}
|
||||
|
||||
func getTmpl(name string) *template.Template {
|
||||
liveMode := conf.LiveMode
|
||||
|
||||
if liveMode {
|
||||
// reload the requested template before returning it.
|
||||
// tmpls = template.Must(tmpls.ParseFS(tmplFS, name))
|
||||
// nuTmpls, err := tmpls.ParseFS(tmplFS, name)
|
||||
// nuTmpls, err := tmpls.ParseFS(tmplFS, name)
|
||||
|
||||
//if err != nil {
|
||||
// log.Printf("error refreshing tmpl %s, '%q'", name, err)
|
||||
//} else {
|
||||
// tmpls = nuTmpls
|
||||
// makeTplMap(tmpls)
|
||||
//}
|
||||
|
||||
// tpl := template.Must(template.New(name).ParseFS(tmplFS, name))
|
||||
// templateMap[name] = tpl
|
||||
// return tpl
|
||||
log.Println("re-reading tmpls")
|
||||
tpl := template.New("")
|
||||
setFuncMap(tpl)
|
||||
allTmpls := listAllTmpls()
|
||||
// ensure this fails at compile time, if at all ("Must").
|
||||
tmpls = template.Must(tpl.ParseFS(tmplFS, allTmpls...))
|
||||
// InitTemplates(tmplFS)
|
||||
}
|
||||
|
||||
return tmpls.Lookup(name)
|
||||
}
|
||||
|
||||
func Admin() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Invalid credentials")
|
||||
}
|
||||
}
|
||||
|
||||
// func Index(conf *config.Config) echo.HandlerFunc {
|
||||
func Index() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// tpl, err := template.New("index").ParseFS(templates, "index.tmpl")
|
||||
// tpl := template.New("index")
|
||||
// tpl := theTmpls.New("index.tmpl")
|
||||
|
||||
// tpl := tmpls.Lookup("index.tmpl")
|
||||
tpl := getTmpl("index.tmpl")
|
||||
// if conf.LiveMode {
|
||||
// // reload tmpls.
|
||||
// LoadTemplates(tmplFS)
|
||||
// }
|
||||
|
||||
// tpl = tpl.Funcs(template.FuncMap{
|
||||
// "pageIs": func(want, got string) bool {
|
||||
// if want == got {
|
||||
// return true
|
||||
// }
|
||||
// return false
|
||||
// },
|
||||
// })
|
||||
// log.Printf("%v", tpl)
|
||||
|
||||
// tpl := templateMap["index.tmpl"]
|
||||
|
||||
// secure := c.Request().URL.Scheme == "https"
|
||||
// secure := true
|
||||
csrf := c.Get("csrf").(string)
|
||||
// cookieCSRF := &http.Cookie{
|
||||
// Name: "_csrf",
|
||||
// Value: csrf,
|
||||
// // SameSite: http.SameSiteStrictMode,
|
||||
// SameSite: http.SameSiteLaxMode,
|
||||
// MaxAge: 3600,
|
||||
// Secure: secure,
|
||||
// HttpOnly: true,
|
||||
// }
|
||||
// c.SetCookie(cookieCSRF)
|
||||
|
||||
err := tpl.Execute(c.Response().Writer,
|
||||
// struct {
|
||||
// AppName string
|
||||
// AppVer string
|
||||
// Title string
|
||||
// CSRF string
|
||||
// DevelMode bool
|
||||
// }{
|
||||
// AppName: conf.AppName,
|
||||
// AppVer: appver,
|
||||
// Title: "Welcome!",
|
||||
// CSRF: csrf,
|
||||
// DevelMode: conf.DevelMode,
|
||||
// },
|
||||
page{
|
||||
AppName: conf.AppName,
|
||||
AppVer: appver,
|
||||
Title: "Welcome!",
|
||||
CSRF: csrf,
|
||||
DevelMode: conf.DevelMode,
|
||||
Current: "home",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("error when executing tmpl: '%q'", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func Signin() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
session, err := c.Cookie("session")
|
||||
if err != nil {
|
||||
if err == http.ErrNoCookie {
|
||||
log.Println("no session cookie found")
|
||||
}
|
||||
}
|
||||
if session != nil {
|
||||
log.Println("got session")
|
||||
// if err := session.Valid(); err == nil && session.Expires.After(time.Now()) {
|
||||
if err := session.Valid(); err == nil {
|
||||
c.Redirect(302, "/home")
|
||||
} else {
|
||||
log.Println("invalid (or expired) session")
|
||||
log.Println("error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
tpl := getTmpl("signin.tmpl")
|
||||
// secure := c.Request().URL.Scheme == "https"
|
||||
// secure := true
|
||||
// csrf := c.Get("csrf").(string)
|
||||
// cookieCSRF := &http.Cookie{
|
||||
// Name: "_csrf",
|
||||
// Value: csrf,
|
||||
// // SameSite: http.SameSiteStrictMode,
|
||||
// SameSite: http.SameSiteLaxMode,
|
||||
// MaxAge: 3600,
|
||||
// Secure: secure,
|
||||
// HttpOnly: true,
|
||||
// }
|
||||
// c.SetCookie(cookieCSRF)
|
||||
|
||||
err = tpl.Execute(c.Response().Writer,
|
||||
// struct {
|
||||
// AppName string
|
||||
// AppVer string
|
||||
// Title string
|
||||
// DevelMode bool
|
||||
// }{
|
||||
// AppName: conf.AppName,
|
||||
// AppVer: appver,
|
||||
// Title: "Sign in",
|
||||
// DevelMode: conf.DevelMode,
|
||||
// },
|
||||
page{
|
||||
AppName: conf.AppName,
|
||||
AppVer: appver,
|
||||
Title: "Sign in",
|
||||
DevelMode: conf.DevelMode,
|
||||
Current: "signin",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func SigninPost(client *ent.Client) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
ct := c.Request().Header.Get("Content-Type")
|
||||
fmt.Printf("signin(POST): content-type: %s\n", ct)
|
||||
|
||||
err := c.Request().ParseForm()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var username string
|
||||
var password string
|
||||
if uname := c.Request().FormValue("username"); uname != "" {
|
||||
username = uname
|
||||
log.Printf("authenticating user '%s' at /signin", username)
|
||||
} else {
|
||||
log.Printf("username was not set, returning to /signin")
|
||||
|
||||
c.Redirect(302, "/signin")
|
||||
|
||||
return nil
|
||||
}
|
||||
if passwd := c.Request().FormValue("password"); passwd != "" {
|
||||
password = passwd
|
||||
} else {
|
||||
log.Printf("password was not set, returning to /signin")
|
||||
|
||||
c.Redirect(302, "/signin")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// if usr := client.User.Query().
|
||||
// Where(
|
||||
// user.Username(username),
|
||||
// ); usr != nil {
|
||||
if usr, err := moduser.QueryUser(context.Background(), client, username); err == nil {
|
||||
log.Println(usr)
|
||||
if usr.Password != password {
|
||||
log.Println("wrong user credentials, redirecting to /signin")
|
||||
|
||||
c.Redirect(302, "/signin")
|
||||
}
|
||||
// if user.Password(password) {
|
||||
// c.Redirect(302, "/signin")
|
||||
// }
|
||||
|
||||
// if err != nil || p != password {
|
||||
// log.Println(echo.NewHTTPError(
|
||||
// http.StatusUnauthorized,
|
||||
// http.StatusText(http.StatusUnauthorized)+" "+err.Error(),
|
||||
// ))
|
||||
//
|
||||
// c.Redirect(302, "/signin")
|
||||
// return nil
|
||||
// }
|
||||
} else {
|
||||
// just log the error instead of returning it to the user and
|
||||
// redirect back to /signin.
|
||||
log.Println(echo.NewHTTPError(
|
||||
http.StatusUnauthorized,
|
||||
http.StatusText(http.StatusUnauthorized)+" "+err.Error(),
|
||||
))
|
||||
c.Redirect(302, "/signin")
|
||||
return nil
|
||||
}
|
||||
|
||||
secure := c.Request().URL.Scheme == "https"
|
||||
|
||||
cookieSession := &http.Cookie{
|
||||
Name: "session",
|
||||
Value: username,
|
||||
// SameSite: http.SameSiteStrictMode,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 3600,
|
||||
Secure: secure,
|
||||
HttpOnly: true,
|
||||
}
|
||||
c.SetCookie(cookieSession)
|
||||
|
||||
c.Redirect(301, "/home")
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func Signup() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
session, err := c.Cookie("session")
|
||||
if err != nil {
|
||||
if err == http.ErrNoCookie {
|
||||
log.Println("no session cookie found")
|
||||
}
|
||||
}
|
||||
if session != nil {
|
||||
log.Println("got session")
|
||||
// if err := session.Valid(); err == nil && session.Expires.After(time.Now()) {
|
||||
if err := session.Valid(); err == nil {
|
||||
c.Redirect(302, "/home")
|
||||
} else {
|
||||
log.Println("invalid (or expired) session")
|
||||
log.Println("error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
tpl := getTmpl("signup.tmpl")
|
||||
|
||||
csrf := c.Get("csrf").(string)
|
||||
|
||||
// secure := c.Request().URL.Scheme == "https"
|
||||
// cookieCSRF := &http.Cookie{
|
||||
// Name: "_csrf",
|
||||
// Value: csrf,
|
||||
// // SameSite: http.SameSiteStrictMode,
|
||||
// SameSite: http.SameSiteLaxMode,
|
||||
// MaxAge: 3600,
|
||||
// Secure: secure,
|
||||
// HttpOnly: true,
|
||||
// }
|
||||
// c.SetCookie(cookieCSRF)
|
||||
|
||||
err = tpl.Execute(c.Response().Writer,
|
||||
page{
|
||||
AppName: conf.AppName,
|
||||
AppVer: appver,
|
||||
Title: "Sign up",
|
||||
CSRF: csrf,
|
||||
DevelMode: conf.DevelMode,
|
||||
Current: "signup",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("error: %q", err)
|
||||
http.Error(c.Response().Writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func SignupPost(client *ent.Client) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// tpl := getTmpl("signup.tmpl", conf.LiveMode)
|
||||
|
||||
ct := c.Request().Header.Get("Content-Type")
|
||||
fmt.Printf("content-type: %s\n", ct)
|
||||
|
||||
err := c.Request().ParseForm()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var username string
|
||||
if uname := c.Request().FormValue("username"); uname != "" {
|
||||
username = uname
|
||||
if passwd := c.Request().FormValue("password"); passwd != "" {
|
||||
if u, err := moduser.CreateUser(context.Background(), client, username, passwd); err != nil {
|
||||
// TODO: don't return the error to the user, perhaps based
|
||||
// on the devel mode.
|
||||
return echo.NewHTTPError(
|
||||
http.StatusInternalServerError,
|
||||
http.StatusText(http.StatusInternalServerError)+" failed to create schema resources "+err.Error(),
|
||||
)
|
||||
} else {
|
||||
log.Printf("successfully registered user '%s': %#v", username, u)
|
||||
}
|
||||
} else {
|
||||
log.Println("password was not set, returning to /signup")
|
||||
}
|
||||
} else {
|
||||
log.Printf("username was not set, returning to /signup")
|
||||
|
||||
c.Redirect(302, "/signup")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
secure := c.Request().URL.Scheme == "https"
|
||||
// secure := true
|
||||
// csrf := c.Get("csrf").(string)
|
||||
|
||||
cookieSession := &http.Cookie{
|
||||
Name: "session",
|
||||
Value: username,
|
||||
// SameSite: http.SameSiteStrictMode,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 3600,
|
||||
Secure: secure,
|
||||
HttpOnly: true,
|
||||
}
|
||||
c.SetCookie(cookieSession)
|
||||
|
||||
// cookieCSRF := &http.Cookie{
|
||||
// Name: "_csrf",
|
||||
// Value: csrf,
|
||||
// // SameSite: http.SameSiteStrictMode,
|
||||
// SameSite: http.SameSiteLaxMode,
|
||||
// MaxAge: 3600,
|
||||
// Secure: secure,
|
||||
// HttpOnly: true,
|
||||
// }
|
||||
// c.SetCookie(cookieCSRF)
|
||||
|
||||
c.Redirect(301, "/home")
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func Home() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
var username string
|
||||
|
||||
tpl := getTmpl("home.tmpl")
|
||||
session, err := c.Cookie("session")
|
||||
if err != nil {
|
||||
if err == http.ErrNoCookie {
|
||||
// return err
|
||||
log.Printf("error no cookie: %q", err)
|
||||
http.Error(c.Response().Writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Println("error:", err)
|
||||
http.Error(c.Response().Writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
// fmt.Println("session cookie not found, redirecting to signin page")
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
if session != nil {
|
||||
log.Println("got session")
|
||||
// if err := session.Valid(); err == nil && session.Expires.After(time.Now()) {
|
||||
if err := session.Valid(); err == nil {
|
||||
username = session.Value
|
||||
} else {
|
||||
log.Println("invalid or expired session?")
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
|
||||
}
|
||||
}
|
||||
|
||||
// example denial.
|
||||
// if _, err := c.Cookie("aha"); err != nil {
|
||||
// log.Printf("error: %q", err)
|
||||
// return echo.NewHTTPError(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
|
||||
// }
|
||||
|
||||
err = tpl.Execute(c.Response().Writer,
|
||||
page{
|
||||
AppName: conf.AppName,
|
||||
AppVer: appver,
|
||||
Title: "Home",
|
||||
Name: username,
|
||||
DevelMode: conf.DevelMode,
|
||||
Current: "home",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
// return err
|
||||
log.Printf("error: %q", err)
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func Logout() echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if c.Request().Method == "POST" {
|
||||
session, err := c.Cookie("session")
|
||||
if err != nil {
|
||||
if errors.Is(err, http.ErrNoCookie) {
|
||||
fmt.Println("nobody to log out, redirecting to /signin")
|
||||
|
||||
c.Redirect(302, "/signin")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("error: %q", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var username string
|
||||
if err := session.Valid(); err == nil {
|
||||
username = session.Value
|
||||
}
|
||||
|
||||
log.Printf("logging out user '%s'", username)
|
||||
|
||||
secure := c.Request().URL.Scheme == "https"
|
||||
cookieSession := &http.Cookie{
|
||||
Name: "session",
|
||||
Value: "",
|
||||
// SameSite: http.SameSiteStrictMode,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
Secure: secure,
|
||||
HttpOnly: true,
|
||||
}
|
||||
c.SetCookie(cookieSession)
|
||||
}
|
||||
|
||||
tpl := getTmpl("logout.tmpl")
|
||||
|
||||
err := tpl.Execute(c.Response().Writer,
|
||||
struct {
|
||||
AppName string
|
||||
AppVer string
|
||||
Title string
|
||||
DevelMode bool
|
||||
}{
|
||||
AppName: conf.AppName,
|
||||
AppVer: appver,
|
||||
Title: "Logout",
|
||||
DevelMode: conf.DevelMode,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("error: %q", err)
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// experimental global redirect handler?
|
||||
// http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
|
||||
// loc, err := url.QueryUnescape(r.URL.Query().Get("loc"))
|
||||
// if err != nil {
|
||||
// http.Error(w, fmt.Sprintf("invalid redirect: %q", r.URL.Query().Get("loc")), http.StatusBadRequest)
|
||||
// return
|
||||
// }
|
||||
// http.Redirect(w, r, loc, http.StatusFound)
|
||||
// })
|
||||
|
17
handlers/icon.go
Normal file
17
handlers/icon.go
Normal file
@ -0,0 +1,17 @@
|
||||
package handlers
|
||||
|
||||
type Iconier interface {
|
||||
Img() string
|
||||
}
|
||||
|
||||
type Icon struct {
|
||||
img string
|
||||
}
|
||||
|
||||
func (i *Icon) Img() string {
|
||||
return i.img
|
||||
}
|
||||
|
||||
func NewIcon(data string) *Icon {
|
||||
return &Icon{img: data}
|
||||
}
|
11
handlers/page.go
Normal file
11
handlers/page.go
Normal file
@ -0,0 +1,11 @@
|
||||
package handlers
|
||||
|
||||
type page struct {
|
||||
AppName string
|
||||
AppVer string
|
||||
Title string
|
||||
Name string
|
||||
CSRF string
|
||||
DevelMode bool
|
||||
Current string
|
||||
}
|
1
handlers/pages.go
Normal file
1
handlers/pages.go
Normal file
@ -0,0 +1 @@
|
||||
package handlers
|
22
justfile
Normal file
22
justfile
Normal file
@ -0,0 +1,22 @@
|
||||
watch-tw:
|
||||
mkdir -pv static
|
||||
npx tailwindcss -i ./assets/input.css -o ./static/pcmt.css --watch
|
||||
|
||||
watch-brs:
|
||||
npx browser-sync start --config bs.js
|
||||
|
||||
tw:
|
||||
mkdir -p static
|
||||
npx tailwindcss -i ./assets/input.css -o ./static/pcmt.css --minify
|
||||
|
||||
build:
|
||||
go build -v -ldflags="-X main.version=$(git rev-parse --short HEAD)" .
|
||||
|
||||
run:
|
||||
./pcmt -devel
|
||||
|
||||
dev: build run
|
||||
|
||||
# generate code based on ent schemas.
|
||||
gen:
|
||||
go generate -v ./ent
|
25
modules/password/password.go
Normal file
25
modules/password/password.go
Normal file
@ -0,0 +1,25 @@
|
||||
package password
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
func GetHash(password string) ([]byte, error) {
|
||||
// NOTE: bcrypt will not operate on passwords longer than 72 characters.
|
||||
hash, err := bcrypt.GenerateFromPassword(
|
||||
[]byte(password), bcrypt.DefaultCost,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
func Compare(oldHash []byte, password string) bool {
|
||||
// NOTE: bcrypt will not operate on passwords longer than 72 characters.
|
||||
err := bcrypt.CompareHashAndPassword(oldHash, []byte(password))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
39
modules/user/user.go
Normal file
39
modules/user/user.go
Normal file
@ -0,0 +1,39 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
||||
)
|
||||
|
||||
// CreateUser adds a user entry to the database.
|
||||
func CreateUser(ctx context.Context, client *ent.Client, username, password string) (*ent.User, error) {
|
||||
u, err := client.User.
|
||||
Create().
|
||||
SetUsername(username).
|
||||
SetPassword(password).
|
||||
Save(ctx)
|
||||
// TODO: saving cleartext password, rework!
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed creating user: %w", err)
|
||||
}
|
||||
log.Println("user was created: ", u)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func QueryUser(ctx context.Context, client *ent.Client, username string) (*ent.User, error) {
|
||||
u, err := client.User.
|
||||
Query().
|
||||
Where(user.Username(username)).
|
||||
// `Only` fails if no user found,
|
||||
// or more than 1 user returned.
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed querying user: %w", err)
|
||||
}
|
||||
log.Println("user returned: ", u)
|
||||
return u, nil
|
||||
}
|
3046
package-lock.json
generated
Normal file
3046
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
12
package.json
Normal file
12
package.json
Normal file
@ -0,0 +1,12 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"browser-sync": "^2.29.1",
|
||||
"bs-html-injector": "^3.0.3",
|
||||
"tailwindcss": "^3.3.0"
|
||||
},
|
||||
"scripts": {
|
||||
"watch-tw": "npx tailwindcss -i ./assets/input.css -o ./static/pcmt.css --watch",
|
||||
"watch-brs": "npx browser-sync start --config bs-config.js",
|
||||
"tw": "npx tailwindcss -i ./assets/input.css -o ./static/pcmt.css --minify"
|
||||
}
|
||||
}
|
111
run.go
111
run.go
@ -3,41 +3,122 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
// ent pure go sqlite3 driver instead of "github.com/mattn/go-sqlite3".
|
||||
_ "github.com/xiaoqidun/entps"
|
||||
|
||||
"git.dotya.ml/mirre-mt/pcmt/app"
|
||||
"git.dotya.ml/mirre-mt/pcmt/config"
|
||||
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||||
)
|
||||
|
||||
const (
|
||||
banner = ` __
|
||||
____ _________ ___ / /_
|
||||
/ __ \/ ___/ __ ` + "`" + `__ \/ __/
|
||||
/ /_/ / /__/ / / / / / /_
|
||||
/ .___/\___/_/ /_/ /_/\__/ %s Password Compromise Monitoring Tool %s
|
||||
/_/`
|
||||
|
||||
licenseHeader = `pcmt - Password Compromise Monitoring Tool
|
||||
Copyright (C) git.dotya.ml/wanderer
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation version 3 of the License.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.`
|
||||
)
|
||||
|
||||
var (
|
||||
addr = flag.String("addr", ":3000", "TCP address:port to listen at")
|
||||
addr = flag.String("addr", ":3000", "TCP address:port to listen at")
|
||||
// compress = flag.Bool("compress", false, "Enable transparent response compression")
|
||||
configFlag = flag.String("config", "config.dhall", "Default path of the config file")
|
||||
devel = flag.Bool("devel", false, "Run the application in dev mode, connect to a local browser-sync instance for hot-reloading")
|
||||
// pages = map[string]string{
|
||||
// "/": "templates/index.tmpl",
|
||||
// }
|
||||
version = "dev"
|
||||
)
|
||||
|
||||
func run() error {
|
||||
printHeader()
|
||||
|
||||
flag.Parse()
|
||||
|
||||
// TODO: allow different configuration formats (toml, ni)
|
||||
// TODO: rename main.go to pcmt.go
|
||||
// TODO: add .golangci-lint
|
||||
// TODO: add flake.nix
|
||||
// TODO: connect to postgres
|
||||
// TODO: design user schemas, models.
|
||||
// TODO: SBOM: https://actuated.dev/blog/sbom-in-github-actions
|
||||
// TODO: SBOM: https://www.docker.com/blog/generate-sboms-with-buildkit/
|
||||
|
||||
conf, err := config.LoadConfig(*configFlag)
|
||||
if err != nil {
|
||||
log.Println("error loading config file", *configFlag)
|
||||
return err
|
||||
}
|
||||
|
||||
// for "github.com/xiaoqidun/entps".
|
||||
connstr := "file:ent?mode=memory&cache=shared&_fk=1"
|
||||
log.Printf("connecting to db at '%s'", connstr)
|
||||
db, err := ent.Open("sqlite3", connstr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open a connection to sqlite: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
log.Println("attempting to automatically migrate db schema")
|
||||
// Run the auto migration tool.
|
||||
if err = db.Schema.Create(context.Background()); err != nil {
|
||||
return fmt.Errorf("failed creating schema resources: %v", err)
|
||||
}
|
||||
|
||||
a := &app.App{}
|
||||
|
||||
err := a.Init()
|
||||
err = a.Init(version, conf, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e := a.E()
|
||||
logger := a.Logger()
|
||||
|
||||
a.StartupSettings()
|
||||
|
||||
_, err = config.LoadConfig(*configFlag)
|
||||
if err != nil {
|
||||
logger.Println("error loading config file", *configFlag)
|
||||
return err
|
||||
}
|
||||
a.PrintConfiguration()
|
||||
|
||||
a.SetupRoutes()
|
||||
|
||||
logger := a.Logger()
|
||||
|
||||
a.SetEchoSettings()
|
||||
|
||||
// a.SetConfig(conf)
|
||||
a.SetEmbeds(templates, assets)
|
||||
|
||||
if *devel {
|
||||
a.SetDevel()
|
||||
}
|
||||
|
||||
// // TODO: add check for prometheus config setting.
|
||||
// if true {
|
||||
// // import "github.com/labstack/echo-contrib/prometheus"
|
||||
// p := prometheus.NewPrometheus("echo", nil)
|
||||
// p.Use(e)
|
||||
// }
|
||||
|
||||
e := a.E()
|
||||
go func() {
|
||||
if err = e.Start(*addr); err != nil && err != http.ErrServerClosed {
|
||||
logger.Println("shutting down the server")
|
||||
@ -47,6 +128,8 @@ func run() error {
|
||||
quit := make(chan os.Signal, 1)
|
||||
|
||||
signal.Notify(quit, os.Interrupt)
|
||||
signal.Notify(quit, syscall.SIGTERM)
|
||||
signal.Notify(quit, syscall.SIGHUP)
|
||||
<-quit
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@ -61,3 +144,7 @@ func run() error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func printHeader() {
|
||||
fmt.Fprintf(os.Stderr, "%s\n\n%s\n\n", licenseHeader, banner)
|
||||
}
|
||||
|
3
settings.go
Normal file
3
settings.go
Normal file
@ -0,0 +1,3 @@
|
||||
package main
|
||||
|
||||
// func
|
9
tailwind.config.js
Normal file
9
tailwind.config.js
Normal file
@ -0,0 +1,9 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: ["./templates/**.{tmpl,html}"],
|
||||
/* darkMode: 'class', */
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
5
templates/500.tmpl
Normal file
5
templates/500.tmpl
Normal file
@ -0,0 +1,5 @@
|
||||
{{ template "head.tmpl" . }}
|
||||
<body>
|
||||
<div class="cover"><h1>Webservice currently unavailable <small>500</small></h1><p class="lead">An unexpected condition was encountered.<br />Our service team has been dispatched to bring it back online.</p></div>
|
||||
|
||||
{{ template "footer.tmpl" . }}
|
3
templates/admin-users.tmpl
Normal file
3
templates/admin-users.tmpl
Normal file
@ -0,0 +1,3 @@
|
||||
<h1>
|
||||
List of all users
|
||||
</h1>
|
18
templates/browsersync.tmpl
Normal file
18
templates/browsersync.tmpl
Normal file
@ -0,0 +1,18 @@
|
||||
<!-- [> browserSync <] -->
|
||||
<!-- <script async id="__bs_script__" src="http://localhost:3002/browser-sync/browser-sync-client.js?v=2.29.1" defer></script> -->
|
||||
<script defer id="__bs_script__">//<![CDATA[
|
||||
(function() {
|
||||
try {
|
||||
var script = document.createElement('script');
|
||||
if ('async') {
|
||||
script.async = true;
|
||||
}
|
||||
script.src = 'http://HOST:3002/browser-sync/browser-sync-client.js?v=2.29.0'.replace("HOST", location.hostname);
|
||||
if (document.body) {
|
||||
document.body.appendChild(script);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Browsersync: could not append script tag", e);
|
||||
}
|
||||
})()
|
||||
//]]></script>
|
22
templates/footer.tmpl
Normal file
22
templates/footer.tmpl
Normal file
@ -0,0 +1,22 @@
|
||||
<!-- footer anchored to the bottom https://stackoverflow.com/a/72232241 -->
|
||||
<footer class="items-center mx-6 m-4 sticky top-[100vh] shadow bg-white dark:bg-gray-900 border-2 border-slate-300 rounded-sm">
|
||||
<!-- alternatively -->
|
||||
<!-- <footer class="fixed bottom-0 left-0 w-full bg-gray-800 mx-auto rounded-sm"> -->
|
||||
<span class="block hover:shadow text-center text-sm px-6 py-2 text-pink-400 dark:bg-gray-900">
|
||||
powered by <code>pcmt</code> version <code>{{ .AppVer }}</code>
|
||||
·
|
||||
<a class="text-pink-500 hover:text-pink-600 hover:underline" href="https://git.dotya.ml/wanderer" target="_blank">© wanderer</a>
|
||||
·
|
||||
<a class="text-pink-500 hover:text-pink-600 hover:underline" href="https://www.gnu.org/licenses/agpl-3.0.en.html" target="_blank">AGPL-3.0-only</a>
|
||||
·
|
||||
<a class="text-pink-500 hover:text-pink-600 hover:underline" href="https://git.dotya.ml/mirre-mt/pcmt" target="_blank">sources</a>
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- inject browsersync script if running in devel mode -->
|
||||
{{- if .DevelMode -}}
|
||||
{{ template "browsersync.tmpl" }}
|
||||
{{- end }}
|
||||
</body>
|
||||
</html>
|
26
templates/head.tmpl
Normal file
26
templates/head.tmpl
Normal file
@ -0,0 +1,26 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
{{- if true -}}
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, height=device-height initial-scale=1.0, minimum-scale=1.0">
|
||||
{{ else }}
|
||||
{{htmlSafe "<!--[if IE 6]>"}}
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=Unicode">
|
||||
{{htmlSafe "<![endif]-->"}}
|
||||
{{ end -}}
|
||||
<title>{{if .Title}}{{ .Title }} -{{end}} {{if .AppName}}{{ .AppName }}{{end}}</title>
|
||||
{{- if .AppName -}}
|
||||
<meta property="og:title" content="{{ .AppName }}">
|
||||
<meta property="og:site_name" content="{{ .AppName }}">
|
||||
{{- end -}}
|
||||
<meta property="og:type" content="website">
|
||||
|
||||
<link rel="icon" href="/static/img/logo-pcmt.svg" type="image/svg+xml">
|
||||
<link href="/static/pcmt.css" rel="preload" as="style">
|
||||
<link href="/static/pcmt.css" rel="stylesheet">
|
||||
|
||||
{{- if .DevelMode -}}
|
||||
<!-- <link href="http://localhost:3002/browser-sync/browser-sync-client.js?v=2.29.1" rel="preload" as="script"> -->
|
||||
{{- end -}}
|
||||
</head>
|
22
templates/home.tmpl
Normal file
22
templates/home.tmpl
Normal file
@ -0,0 +1,22 @@
|
||||
{{ template "head.tmpl" . }}
|
||||
<body class="h-screen bg-white dark:bg-gray-900">
|
||||
{{ template "navbar.tmpl" . }}
|
||||
<main class="grow">
|
||||
<div class="place-items-center text-center">
|
||||
<h1 class="mt-20 text-2xl text-pink-400 font-bold">
|
||||
{{ if .Name -}}
|
||||
Welcome, <code>{{.Name}}</code>! TODO: find out whether user is an admin and show additional button redirecting to /admin/users, which lists all users, enables manipulating data sources, etc..
|
||||
<div class="mt-8 md:flex md:items-center">
|
||||
<form method="POST" class="w-full lg:max-w-xl" action="/logout">
|
||||
<button
|
||||
class="w-full px-6 py-3 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-500 rounded-lg md:w-1/2 hover:bg-blue-400 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-50"
|
||||
type="submit">Logout</button>
|
||||
</form>
|
||||
</div>
|
||||
{{- else }}
|
||||
Please log in.
|
||||
{{- end -}}
|
||||
</h1>
|
||||
</div>
|
||||
</main>
|
||||
{{ template "footer.tmpl" . }}
|
15
templates/index.tmpl
Normal file
15
templates/index.tmpl
Normal file
@ -0,0 +1,15 @@
|
||||
{{ template "head.tmpl" . }}
|
||||
<body class="h-screen bg-white dark:bg-gray-900">
|
||||
{{ template "navbar.tmpl" . }}
|
||||
<main class="grow">
|
||||
<div class="container mx-auto">
|
||||
<!-- <div class="container w-full p-8 items-center"> -->
|
||||
<img src="/static/img/logo-pcmt.svg" alt="pcmt logo" class="mx-auto"/>
|
||||
</div>
|
||||
<div class="container mx-auto text-center">
|
||||
<h1 class="p-2 mt-10 text-2xl font-bold text-purple-600 dark:text-purple-400">
|
||||
Welcome to <code>pcmt</code>, friend!
|
||||
</h1>
|
||||
</div>
|
||||
</main>
|
||||
{{ template "footer.tmpl" . }}
|
11
templates/logout.tmpl
Normal file
11
templates/logout.tmpl
Normal file
@ -0,0 +1,11 @@
|
||||
{{ template "head.tmpl" . }}
|
||||
<body class="h-screen bg-white dark:bg-gray-900">
|
||||
{{ template "navbar.tmpl" . }}
|
||||
<main class="grow">
|
||||
<div class="place-items-center text-center">
|
||||
<h1 class="mt-20 text-2xl text-pink-400 font-bold">
|
||||
You've been logged out.
|
||||
</h1>
|
||||
</div>
|
||||
</main>
|
||||
{{ template "footer.tmpl" . }}
|
48
templates/navbar.tmpl
Normal file
48
templates/navbar.tmpl
Normal file
@ -0,0 +1,48 @@
|
||||
<nav class="sticky top-3 z-20 backdrop-blur-sm border-gray-200 dark:border-gray-700 mx-auto md:mx-6">
|
||||
<div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-2">
|
||||
<a href="/" class="flex items-center">
|
||||
<img src="/static/img/logo-pcmt.svg" class="h-8 mr-3" alt="logo" />
|
||||
<span class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white">pcmt</span>
|
||||
</a>
|
||||
<div class="group/navbar">
|
||||
<button type="button" class="inline-flex items-center p-2 ml-2 text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" data-collapse-toggle="navbar">
|
||||
<span class="sr-only">Main menu</span>
|
||||
{{ template "svg-hamburger.tmpl" }}
|
||||
</button>
|
||||
<div class="hidden group-hover/navbar:block fixed z-50 right-[3.2rem] top-2 overflow-y-auto max-w-10 md:block md:w-auto" id="navbar">
|
||||
<ul class="flex flex-col items-center font-medium p-4 md:p-0 mt-2 border border-gray-100 rounded-lg bg-gray-50 md:flex-row md:space-x-8 md:mt-0 md:border-0 md:bg-white dark:bg-gray-800 md:dark:bg-gray-900 dark:border-gray-700">
|
||||
<li>
|
||||
{{ if pageIs .Current "home" }}
|
||||
<a href="/" class="block py-2 pl-3 pr-4 text-white bg-blue-500 rounded md:bg-transparent md:text-blue-700 md:p-0 md:dark:text-blue-500 dark:bg-blue-500 md:dark:bg-transparent" aria-current="page">
|
||||
{{ else }}
|
||||
<a href="/" class="block py-2 pl-3 pr-4 text-gray-900 rounded hover:bg-gray-300 md:hover:bg-transparent md:border-0 md:hover:text-blue-500 md:p-0 dark:text-white md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">
|
||||
{{ end }}
|
||||
Home
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#" class="block py-2 pl-3 pr-4 text-gray-900 rounded hover:bg-gray-300 md:hover:bg-transparent md:border-0 md:hover:text-blue-500 md:p-0 dark:text-white md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">About</a>
|
||||
</li>
|
||||
<li>
|
||||
{{ if pageIs .Current "signup" }}
|
||||
<a href="/signup" class="block py-2 pl-3 pr-4 text-white bg-blue-500 rounded md:bg-transparent md:text-blue-700 md:p-0 md:dark:text-blue-500 dark:bg-blue-500 md:dark:bg-transparent" aria-current="page">
|
||||
{{ else }}
|
||||
<a href="/signup" class="block py-2 pl-3 pr-4 text-gray-900 rounded hover:bg-gray-200 md:hover:bg-transparent md:border-0 md:hover:text-blue-500 md:p-0 dark:text-white md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">
|
||||
{{ end }}
|
||||
Register
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
{{ if pageIs .Current "signin" }}
|
||||
<a href="/signin" class="block py-2 pl-3 pr-4 text-white bg-blue-500 rounded md:bg-transparent md:text-blue-700 md:p-0 md:dark:text-blue-500 dark:bg-blue-500 md:dark:bg-transparent" aria-current="page">
|
||||
{{ else }}
|
||||
<a href="/signin" class="block py-2 pl-3 pr-4 text-gray-900 rounded hover:bg-gray-200 md:hover:bg-transparent md:border-0 md:hover:text-blue-500 md:p-0 dark:text-white md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">
|
||||
{{ end }}
|
||||
Sign in
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
65
templates/signin.tmpl
Normal file
65
templates/signin.tmpl
Normal file
@ -0,0 +1,65 @@
|
||||
{{ template "head.tmpl" . }}
|
||||
<body class="min-h-screen bg-white dark:bg-gray-900">
|
||||
{{ template "navbar.tmpl" . }}
|
||||
<main class="grow min-w-[300px]">
|
||||
<!-- <section class="bg-white dark:bg-gray-900"> -->
|
||||
<section>
|
||||
<div class="container mx-auto px-6 sm:px-0:py-0 md:py-16 lg:py-32">
|
||||
<div class="lg:flex">
|
||||
<div class="lg:w-1/2">
|
||||
<h3 class="mt-4 text-gray-600 dark:text-gray-300 md:text-lg">Welcome!</h3>
|
||||
<h1 class="mt-4 text-2xl font-medium text-gray-800 capitalize lg:text-3xl dark:text-white">
|
||||
Login to your account
|
||||
</h1>
|
||||
</div>
|
||||
<div class="mt-8 lg:w-1/2 lg:mt-0">
|
||||
<form method="post" class="w-full lg:max-w-xl">
|
||||
<!-- username field -->
|
||||
<div class="relative flex items-center">
|
||||
<span class="absolute">
|
||||
{{ template "svg-user.tmpl" }}
|
||||
</span>
|
||||
<input type="username" name="username" placeholder="Username" class="block w-full py-3 text-gray-700 bg-white border rounded-lg px-11 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40">
|
||||
</div>
|
||||
<!-- password field -->
|
||||
<div class="relative flex items-center mt-4">
|
||||
<span class="absolute">
|
||||
{{ template "svg-password.tmpl" }}
|
||||
</span>
|
||||
<input type="password" name="password" placeholder="Password" class="block w-full px-10 py-3 text-gray-700 bg-white border rounded-lg dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40">
|
||||
</div>
|
||||
|
||||
<div class="mt-8 md:flex md:items-center">
|
||||
<button class="w-full px-6 py-3 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-500 rounded-lg md:w-1/2 hover:bg-blue-400 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-50">
|
||||
Sign in
|
||||
</button>
|
||||
<a href="#" class="inline-block mt-4 text-center text-blue-500 md:mt-0 md:mx-6 lg:mx-auto hover:underline dark:text-blue-400">
|
||||
Forgot your password?
|
||||
</a>
|
||||
</div>
|
||||
<div class="mt-4 md:flex md:items-center">
|
||||
<span class="inline-block text-center mt-0 md:w-1/2 md:mt-0 text-gray-600 dark:text-gray-300 md:mx-0">
|
||||
Don't have an account yet?
|
||||
</span>
|
||||
<a href="/signup" class="inline-block mx-2 md:mx-6 lg:mx-auto text-center text-blue-600 md:mt-0 hover:underline dark:text-blue-400">
|
||||
Register
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-20">
|
||||
<a href="#" class="group relative inline-block text-blue-500 underline hover:text-red-500 duration-300">
|
||||
Link with top tooltip
|
||||
<!-- Tooltip text here -->
|
||||
<span
|
||||
class="absolute hidden group-hover:flex -left-5 -top-2 -translate-y-full w-48 px-2 py-1 bg-gray-700 rounded-lg text-center text-white text-sm after:content-[''] after:absolute after:left-1/2 after:top-[100%] after:-translate-x-1/2 after:border-8 after:border-x-transparent after:border-b-transparent after:border-t-gray-700">This
|
||||
is some extra useful information</span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
{{ template "footer.tmpl" . }}
|
54
templates/signup.tmpl
Normal file
54
templates/signup.tmpl
Normal file
@ -0,0 +1,54 @@
|
||||
{{ template "head.tmpl" . }}
|
||||
<body class="min-h-screen bg-white dark:bg-gray-900">
|
||||
{{ template "navbar.tmpl" . }}
|
||||
<main class="grow min-w-[300px]">
|
||||
<section class="bg-white dark:bg-gray-900">
|
||||
<div class="container mx-auto px-6 sm:px-0:py-0 md:py-16 lg:py-32">
|
||||
<div class="lg:flex">
|
||||
<div class="lg:w-1/2">
|
||||
<h3 class="mt-4 text-gray-600 dark:text-gray-300 md:text-lg">Welcome!</h3>
|
||||
<h1 class="mt-4 text-2xl font-medium text-gray-800 capitalize lg:text-3xl dark:text-white">
|
||||
Create a new account
|
||||
</h1>
|
||||
</div>
|
||||
<div class="mt-8 lg:w-1/2 lg:mt-0">
|
||||
<form method="post" class="w-full lg:max-w-xl">
|
||||
<input type="hidden" name="_csrf" value="{{- .CSRF -}}">
|
||||
<div class="relative flex items-center">
|
||||
<span class="absolute">
|
||||
{{ template "svg-user.tmpl" }}
|
||||
</span>
|
||||
<input name="username" type="username" placeholder="Username" class="block w-full py-3 text-gray-700 bg-white border rounded-lg px-11 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40">
|
||||
</div>
|
||||
<div class="relative flex items-center mt-4">
|
||||
<!-- <label class="block"> -->
|
||||
<span class="absolute">
|
||||
{{ template "svg-email.tmpl" }}
|
||||
</span>
|
||||
<input name="email" type="email" placeholder="Email address" class="peer block w-full px-10 py-3 text-gray-700 bg-white border rounded-lg dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40">
|
||||
<p class="mt-2 mx-4 hidden peer-invalid:block text-pink-600 text-sm">
|
||||
Please provide a valid email address.
|
||||
</p>
|
||||
<!-- </label> -->
|
||||
</div>
|
||||
<div class="relative flex items-center mt-4">
|
||||
<span class="absolute">
|
||||
{{ template "svg-password.tmpl" }}
|
||||
</span>
|
||||
<input name="password" type="password" placeholder="Password" class="block w-full px-10 py-3 text-gray-700 bg-white border rounded-lg dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600 focus:border-blue-400 dark:focus:border-blue-300 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40">
|
||||
</div>
|
||||
<div class="mt-8 md:flex md:items-center">
|
||||
<button class="w-full px-6 py-3 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-500 rounded-lg md:w-1/2 hover:bg-blue-400 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-50">
|
||||
Sign up
|
||||
</button>
|
||||
<a href="/signin" class="inline-block mt-4 text-center text-blue-500 md:mt-0 md:mx-6 lg:mx-auto hover:underline dark:text-blue-400">
|
||||
Already have an account?
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
{{ template "footer.tmpl" . }}
|
3
templates/svg-email.tmpl
Normal file
3
templates/svg-email.tmpl
Normal file
@ -0,0 +1,3 @@
|
||||
<svg alt="email icon" class="w-6 h-6 mx-3 text-gray-300 dark:text-gray-500 fill-none stroke-current stroke-2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
|
||||
</svg>
|
After Width: | Height: | Size: 301 B |
3
templates/svg-hamburger.tmpl
Normal file
3
templates/svg-hamburger.tmpl
Normal file
@ -0,0 +1,3 @@
|
||||
<svg class="w-6 h-6 fill-current" aria-hidden="true" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"></path>
|
||||
</svg>
|
After Width: | Height: | Size: 284 B |
3
templates/svg-password.tmpl
Normal file
3
templates/svg-password.tmpl
Normal file
@ -0,0 +1,3 @@
|
||||
<svg alt="password lock icon" class="w-6 h-6 mx-3 text-gray-300 dark:text-gray-500 fill-none stroke-current stroke-2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
After Width: | Height: | Size: 308 B |
3
templates/svg-user.tmpl
Normal file
3
templates/svg-user.tmpl
Normal file
@ -0,0 +1,3 @@
|
||||
<svg alt="user icon" class="w-6 h-6 mx-3 text-gray-300 dark:text-gray-500 fill-none stroke-current stroke-2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
|
||||
</svg>
|
After Width: | Height: | Size: 343 B |
Loading…
Reference in New Issue
Block a user