Add dynamic admin panel for managing entities (#108)
This commit is contained in:
parent
60009df0bf
commit
1a6874fd82
47 changed files with 2173 additions and 320 deletions
97
ent/admin/extension.go
Normal file
97
ent/admin/extension.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package admin
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"strings"
|
||||
"text/template"
|
||||
"unicode"
|
||||
|
||||
"entgo.io/ent/entc"
|
||||
"entgo.io/ent/entc/gen"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
//go:embed templates
|
||||
templateDir embed.FS
|
||||
)
|
||||
|
||||
// Extension is the Ent extension that generates code to support the entity admin panel.
|
||||
type Extension struct {
|
||||
entc.DefaultExtension
|
||||
}
|
||||
|
||||
func (*Extension) Templates() []*gen.Template {
|
||||
return []*gen.Template{
|
||||
gen.MustParse(
|
||||
gen.NewTemplate("admin").
|
||||
Funcs(template.FuncMap{
|
||||
"fieldName": fieldName,
|
||||
"fieldLabel": FieldLabel,
|
||||
"fieldIsPointer": fieldIsPointer,
|
||||
}).
|
||||
ParseFS(templateDir, "templates/*tmpl"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// fieldName provides a struct field name from an entity field name (ie, user_id -> UserID).
|
||||
func fieldName(name string) string {
|
||||
if len(name) == 0 {
|
||||
return name
|
||||
}
|
||||
|
||||
parts := strings.Split(name, "_")
|
||||
for i := 0; i < len(parts); i++ {
|
||||
if parts[i] == "id" {
|
||||
parts[i] = "ID"
|
||||
} else {
|
||||
parts[i] = upperFirst(parts[i])
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
// FieldLabel provides a label for an entity field name (ie, user_id -> User ID).
|
||||
func FieldLabel(name string) string {
|
||||
if len(name) == 0 {
|
||||
return name
|
||||
}
|
||||
|
||||
parts := strings.Split(name, "_")
|
||||
for i := 0; i < len(parts); i++ {
|
||||
if parts[i] == "id" {
|
||||
parts[i] = "ID"
|
||||
}
|
||||
if i == 0 {
|
||||
parts[i] = upperFirst(parts[i])
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// fieldIsPointer determines if a given entity field should be a pointer on the struct.
|
||||
func fieldIsPointer(f *gen.Field) bool {
|
||||
switch {
|
||||
case f.Type.Type == field.TypeBool:
|
||||
return false
|
||||
case f.Optional,
|
||||
f.Default,
|
||||
f.Sensitive(),
|
||||
f.Nillable:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// upperFirst uppercases the first character of a given string.
|
||||
func upperFirst(s string) string {
|
||||
if len(s) == 0 {
|
||||
return s
|
||||
}
|
||||
out := []rune(s)
|
||||
out[0] = unicode.ToUpper(out[0])
|
||||
return string(out)
|
||||
}
|
||||
319
ent/admin/handler.go
Normal file
319
ent/admin/handler.go
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
// Code generated by ent, DO NOT EDIT.
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"github.com/mikestefanello/pagoda/ent"
|
||||
"github.com/mikestefanello/pagoda/ent/passwordtoken"
|
||||
"github.com/mikestefanello/pagoda/ent/user"
|
||||
)
|
||||
|
||||
const dateTimeFormat = "2006-01-02T15:04:05"
|
||||
const dateTimeFormatNoSeconds = "2006-01-02T15:04"
|
||||
|
||||
type Handler struct {
|
||||
client *ent.Client
|
||||
Config HandlerConfig
|
||||
}
|
||||
|
||||
func NewHandler(client *ent.Client, cfg HandlerConfig) *Handler {
|
||||
return &Handler{
|
||||
client: client,
|
||||
Config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Create(ctx echo.Context, entityType string) error {
|
||||
switch entityType {
|
||||
case "PasswordToken":
|
||||
return h.PasswordTokenCreate(ctx)
|
||||
case "User":
|
||||
return h.UserCreate(ctx)
|
||||
default:
|
||||
return fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Get(ctx echo.Context, entityType string, id int) (url.Values, error) {
|
||||
switch entityType {
|
||||
case "PasswordToken":
|
||||
return h.PasswordTokenGet(ctx, id)
|
||||
case "User":
|
||||
return h.UserGet(ctx, id)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(ctx echo.Context, entityType string, id int) error {
|
||||
switch entityType {
|
||||
case "PasswordToken":
|
||||
return h.PasswordTokenDelete(ctx, id)
|
||||
case "User":
|
||||
return h.UserDelete(ctx, id)
|
||||
default:
|
||||
return fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Update(ctx echo.Context, entityType string, id int) error {
|
||||
switch entityType {
|
||||
case "PasswordToken":
|
||||
return h.PasswordTokenUpdate(ctx, id)
|
||||
case "User":
|
||||
return h.UserUpdate(ctx, id)
|
||||
default:
|
||||
return fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) List(ctx echo.Context, entityType string) (*EntityList, error) {
|
||||
switch entityType {
|
||||
case "PasswordToken":
|
||||
return h.PasswordTokenList(ctx)
|
||||
case "User":
|
||||
return h.UserList(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) PasswordTokenCreate(ctx echo.Context) error {
|
||||
var payload PasswordToken
|
||||
if err := h.bind(ctx, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
op := h.client.PasswordToken.Create()
|
||||
if payload.Token != nil {
|
||||
op.SetToken(*payload.Token)
|
||||
}
|
||||
op.SetUserID(payload.UserID)
|
||||
if payload.CreatedAt != nil {
|
||||
op.SetCreatedAt(*payload.CreatedAt)
|
||||
}
|
||||
_, err := op.Save(ctx.Request().Context())
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) PasswordTokenUpdate(ctx echo.Context, id int) error {
|
||||
entity, err := h.client.PasswordToken.Get(ctx.Request().Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var payload PasswordToken
|
||||
if err = h.bind(ctx, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
op := entity.Update()
|
||||
if payload.Token != nil {
|
||||
op.SetToken(*payload.Token)
|
||||
}
|
||||
op.SetUserID(payload.UserID)
|
||||
if payload.CreatedAt == nil {
|
||||
var empty time.Time
|
||||
op.SetCreatedAt(empty)
|
||||
} else {
|
||||
op.SetCreatedAt(*payload.CreatedAt)
|
||||
}
|
||||
_, err = op.Save(ctx.Request().Context())
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) PasswordTokenDelete(ctx echo.Context, id int) error {
|
||||
return h.client.PasswordToken.DeleteOneID(id).
|
||||
Exec(ctx.Request().Context())
|
||||
}
|
||||
|
||||
func (h *Handler) PasswordTokenList(ctx echo.Context) (*EntityList, error) {
|
||||
page, offset := h.getPageAndOffset(ctx)
|
||||
res, err := h.client.PasswordToken.
|
||||
Query().
|
||||
Limit(h.Config.ItemsPerPage + 1).
|
||||
Offset(offset).
|
||||
Order(passwordtoken.ByID(sql.OrderDesc())).
|
||||
All(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := &EntityList{
|
||||
Columns: []string{
|
||||
"User ID",
|
||||
"Created at",
|
||||
},
|
||||
Entities: make([]EntityValues, 0, len(res)),
|
||||
Page: page,
|
||||
HasNextPage: len(res) > h.Config.ItemsPerPage,
|
||||
}
|
||||
|
||||
for i := 0; i <= len(res)-1; i++ {
|
||||
list.Entities = append(list.Entities, EntityValues{
|
||||
ID: res[i].ID,
|
||||
Values: []string{
|
||||
fmt.Sprint(res[i].UserID),
|
||||
res[i].CreatedAt.Format(h.Config.TimeFormat),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return list, err
|
||||
}
|
||||
|
||||
func (h *Handler) PasswordTokenGet(ctx echo.Context, id int) (url.Values, error) {
|
||||
entity, err := h.client.PasswordToken.Get(ctx.Request().Context(), id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := url.Values{}
|
||||
v.Set("user_id", fmt.Sprint(entity.UserID))
|
||||
v.Set("created_at", entity.CreatedAt.Format(dateTimeFormat))
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (h *Handler) UserCreate(ctx echo.Context) error {
|
||||
var payload User
|
||||
if err := h.bind(ctx, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
op := h.client.User.Create()
|
||||
op.SetName(payload.Name)
|
||||
op.SetEmail(payload.Email)
|
||||
if payload.Password != nil {
|
||||
op.SetPassword(*payload.Password)
|
||||
}
|
||||
op.SetVerified(payload.Verified)
|
||||
op.SetAdmin(payload.Admin)
|
||||
if payload.CreatedAt != nil {
|
||||
op.SetCreatedAt(*payload.CreatedAt)
|
||||
}
|
||||
_, err := op.Save(ctx.Request().Context())
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) UserUpdate(ctx echo.Context, id int) error {
|
||||
entity, err := h.client.User.Get(ctx.Request().Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var payload User
|
||||
if err = h.bind(ctx, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
op := entity.Update()
|
||||
op.SetName(payload.Name)
|
||||
op.SetEmail(payload.Email)
|
||||
if payload.Password != nil {
|
||||
op.SetPassword(*payload.Password)
|
||||
}
|
||||
op.SetVerified(payload.Verified)
|
||||
op.SetAdmin(payload.Admin)
|
||||
_, err = op.Save(ctx.Request().Context())
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) UserDelete(ctx echo.Context, id int) error {
|
||||
return h.client.User.DeleteOneID(id).
|
||||
Exec(ctx.Request().Context())
|
||||
}
|
||||
|
||||
func (h *Handler) UserList(ctx echo.Context) (*EntityList, error) {
|
||||
page, offset := h.getPageAndOffset(ctx)
|
||||
res, err := h.client.User.
|
||||
Query().
|
||||
Limit(h.Config.ItemsPerPage + 1).
|
||||
Offset(offset).
|
||||
Order(user.ByID(sql.OrderDesc())).
|
||||
All(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := &EntityList{
|
||||
Columns: []string{
|
||||
"Name",
|
||||
"Email",
|
||||
"Verified",
|
||||
"Admin",
|
||||
"Created at",
|
||||
},
|
||||
Entities: make([]EntityValues, 0, len(res)),
|
||||
Page: page,
|
||||
HasNextPage: len(res) > h.Config.ItemsPerPage,
|
||||
}
|
||||
|
||||
for i := 0; i <= len(res)-1; i++ {
|
||||
list.Entities = append(list.Entities, EntityValues{
|
||||
ID: res[i].ID,
|
||||
Values: []string{
|
||||
res[i].Name,
|
||||
res[i].Email,
|
||||
fmt.Sprint(res[i].Verified),
|
||||
fmt.Sprint(res[i].Admin),
|
||||
res[i].CreatedAt.Format(h.Config.TimeFormat),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return list, err
|
||||
}
|
||||
|
||||
func (h *Handler) UserGet(ctx echo.Context, id int) (url.Values, error) {
|
||||
entity, err := h.client.User.Get(ctx.Request().Context(), id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := url.Values{}
|
||||
v.Set("name", entity.Name)
|
||||
v.Set("email", entity.Email)
|
||||
v.Set("verified", fmt.Sprint(entity.Verified))
|
||||
v.Set("admin", fmt.Sprint(entity.Admin))
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (h *Handler) getPageAndOffset(ctx echo.Context) (int, int) {
|
||||
if page, err := strconv.Atoi(ctx.QueryParam(h.Config.PageQueryKey)); err == nil {
|
||||
if page > 1 {
|
||||
return page, (page - 1) * h.Config.ItemsPerPage
|
||||
}
|
||||
}
|
||||
return 1, 0
|
||||
}
|
||||
|
||||
func (h *Handler) bind(ctx echo.Context, entity any) error {
|
||||
// Echo requires some pre-processing of form values to avoid problems.
|
||||
for k, v := range ctx.Request().Form {
|
||||
// Remove empty field values so Echo's bind does not fail when trying to parse things like
|
||||
// times, etc.
|
||||
if len(v) == 1 && len(v[0]) == 0 {
|
||||
delete(ctx.Request().Form, k)
|
||||
continue
|
||||
}
|
||||
|
||||
// Echo expects datetime values to be in a certain format but that does not align with the datetime-local
|
||||
// HTML form element format, so we will attempt to convert it here.
|
||||
for _, format := range []string{dateTimeFormatNoSeconds, dateTimeFormat} {
|
||||
if t, err := time.Parse(format, v[0]); err == nil {
|
||||
ctx.Request().Form[k][0] = t.Format(time.RFC3339)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.Bind(entity)
|
||||
}
|
||||
262
ent/admin/templates/handler.tmpl
Normal file
262
ent/admin/templates/handler.tmpl
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
{{/* Tell Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
|
||||
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
|
||||
|
||||
{{ define "admin/handler" }}
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
{{- $pkg := base $.Config.Package }}
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"{{ $.Config.Package }}"
|
||||
{{- range $n := $.Nodes }}
|
||||
"{{ $.Config.Package }}/{{ $n.Package }}"
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
const dateTimeFormat = "2006-01-02T15:04:05"
|
||||
const dateTimeFormatNoSeconds = "2006-01-02T15:04"
|
||||
|
||||
type Handler struct {
|
||||
client *{{ $pkg }}.Client
|
||||
Config HandlerConfig
|
||||
}
|
||||
|
||||
func NewHandler(client *{{ $pkg }}.Client, cfg HandlerConfig) *Handler {
|
||||
return &Handler{
|
||||
client: client,
|
||||
Config: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Create(ctx echo.Context, entityType string) error {
|
||||
switch entityType {
|
||||
{{- range $n := $.Nodes }}
|
||||
case "{{ $n.Name }}":
|
||||
return h.{{ $n.Name }}Create(ctx)
|
||||
{{- end }}
|
||||
default:
|
||||
return fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Get(ctx echo.Context, entityType string, id int) (url.Values, error) {
|
||||
switch entityType {
|
||||
{{- range $n := $.Nodes }}
|
||||
case "{{ $n.Name }}":
|
||||
return h.{{ $n.Name }}Get(ctx, id)
|
||||
{{- end }}
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(ctx echo.Context, entityType string, id int) error {
|
||||
switch entityType {
|
||||
{{- range $n := $.Nodes }}
|
||||
case "{{ $n.Name }}":
|
||||
return h.{{ $n.Name }}Delete(ctx, id)
|
||||
{{- end }}
|
||||
default:
|
||||
return fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Update(ctx echo.Context, entityType string, id int) error {
|
||||
switch entityType {
|
||||
{{- range $n := $.Nodes }}
|
||||
case "{{ $n.Name }}":
|
||||
return h.{{ $n.Name }}Update(ctx, id)
|
||||
{{- end }}
|
||||
default:
|
||||
return fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) List(ctx echo.Context, entityType string) (*EntityList, error) {
|
||||
switch entityType {
|
||||
{{- range $n := $.Nodes }}
|
||||
case "{{ $n.Name }}":
|
||||
return h.{{ $n.Name }}List(ctx)
|
||||
{{- end }}
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported entity type: %s", entityType)
|
||||
}
|
||||
}
|
||||
|
||||
{{ range $n := $.Nodes }}
|
||||
func (h *Handler) {{ $n.Name }}Create(ctx echo.Context) error {
|
||||
var payload {{ $n.Name }}
|
||||
if err := h.bind(ctx, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
op := h.client.{{ $n.Name }}.Create()
|
||||
{{- range $f := $n.Fields }}
|
||||
{{- if (fieldIsPointer $f) }}
|
||||
if payload.{{ fieldName $f.Name }} != nil {
|
||||
op.Set{{ fieldName $f.Name }}(*payload.{{ fieldName $f.Name }})
|
||||
}
|
||||
{{- else }}
|
||||
op.Set{{ fieldName $f.Name }}(payload.{{ fieldName $f.Name }})
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
_, err := op.Save(ctx.Request().Context())
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) {{ $n.Name }}Update(ctx echo.Context, id int) error {
|
||||
entity, err := h.client.{{ $n.Name }}.Get(ctx.Request().Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var payload {{ $n.Name }}
|
||||
if err = h.bind(ctx, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
op := entity.Update()
|
||||
{{- range $f := $n.Fields }}
|
||||
{{- if not $f.Immutable }}
|
||||
{{- if $f.Sensitive }}
|
||||
if payload.{{ fieldName $f.Name }} != nil {
|
||||
op.Set{{ fieldName $f.Name }}(*payload.{{ fieldName $f.Name }})
|
||||
}
|
||||
{{- else if $f.Nillable }}
|
||||
op.SetNillable{{ fieldName $f.Name }}(payload.{{ fieldName $f.Name }})
|
||||
{{- else if $f.Optional }}
|
||||
if payload.{{ fieldName $f.Name }} == nil {
|
||||
op.Clear{{ fieldName $f.Name }}()
|
||||
} else {
|
||||
op.Set{{ fieldName $f.Name }}(*payload.{{ fieldName $f.Name }})
|
||||
}
|
||||
{{- else if (fieldIsPointer $f) }}
|
||||
if payload.{{ fieldName $f.Name }} == nil {
|
||||
var empty {{ $f.Type }}
|
||||
op.Set{{ fieldName $f.Name }}(empty)
|
||||
} else {
|
||||
op.Set{{ fieldName $f.Name }}(*payload.{{ fieldName $f.Name }})
|
||||
}
|
||||
{{- else }}
|
||||
op.Set{{ fieldName $f.Name }}(payload.{{ fieldName $f.Name }})
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
_, err = op.Save(ctx.Request().Context())
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) {{ $n.Name }}Delete(ctx echo.Context, id int) error {
|
||||
return h.client.{{ $n.Name }}.DeleteOneID(id).
|
||||
Exec(ctx.Request().Context())
|
||||
}
|
||||
|
||||
func (h *Handler) {{ $n.Name }}List(ctx echo.Context) (*EntityList, error) {
|
||||
page, offset := h.getPageAndOffset(ctx)
|
||||
res, err := h.client.{{ $n.Name }}.
|
||||
Query().
|
||||
Limit(h.Config.ItemsPerPage+1).
|
||||
Offset(offset).
|
||||
Order({{ $n.Package }}.ByID(sql.OrderDesc())).
|
||||
All(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := &EntityList{
|
||||
Columns: []string{
|
||||
{{- range $f := $n.Fields }}
|
||||
{{- if not $f.Sensitive }}
|
||||
"{{ fieldLabel $f.Name }}",
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
},
|
||||
Entities: make([]EntityValues, 0, len(res)),
|
||||
Page: page,
|
||||
HasNextPage: len(res) > h.Config.ItemsPerPage,
|
||||
}
|
||||
|
||||
for i := 0; i <= len(res)-1; i++ {
|
||||
list.Entities = append(list.Entities, EntityValues{
|
||||
ID: res[i].ID,
|
||||
Values: []string{
|
||||
{{- range $f := $n.Fields }}
|
||||
{{- if not $f.Sensitive }}
|
||||
{{- if eq $f.Type.String "string" }}
|
||||
res[i].{{ fieldName $f.Name }},
|
||||
{{- else if eq $f.Type.String "time.Time" }}
|
||||
res[i].{{ fieldName $f.Name }}.Format(h.Config.TimeFormat),
|
||||
{{- else }}
|
||||
fmt.Sprint(res[i].{{ fieldName $f.Name }}),
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return list, err
|
||||
}
|
||||
|
||||
func (h *Handler) {{ $n.Name }}Get(ctx echo.Context, id int) (url.Values, error) {
|
||||
entity, err := h.client.{{ $n.Name }}.Get(ctx.Request().Context(), id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := url.Values{}
|
||||
{{- range $f := $n.Fields }}
|
||||
{{- if and (not $f.Sensitive) (not $f.Immutable) }}
|
||||
{{- if eq $f.Type.String "string" }}
|
||||
v.Set("{{ $f.Name }}", entity.{{ fieldName $f.Name }})
|
||||
{{- else if eq $f.Type.String "time.Time" }}
|
||||
v.Set("{{ $f.Name }}", entity.{{ fieldName $f.Name }}.Format(dateTimeFormat))
|
||||
{{- else }}
|
||||
v.Set("{{ $f.Name }}", fmt.Sprint(entity.{{ fieldName $f.Name }}))
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
return v, err
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
func (h *Handler) getPageAndOffset(ctx echo.Context) (int, int) {
|
||||
if page, err := strconv.Atoi(ctx.QueryParam(h.Config.PageQueryKey)); err == nil {
|
||||
if page > 1 {
|
||||
return page, (page-1) * h.Config.ItemsPerPage
|
||||
}
|
||||
}
|
||||
return 1, 0
|
||||
}
|
||||
|
||||
func (h *Handler) bind(ctx echo.Context, entity any) error {
|
||||
// Echo requires some pre-processing of form values to avoid problems.
|
||||
for k, v := range ctx.Request().Form {
|
||||
// Remove empty field values so Echo's bind does not fail when trying to parse things like
|
||||
// times, etc.
|
||||
if len(v) == 1 && len(v[0]) == 0 {
|
||||
delete(ctx.Request().Form, k)
|
||||
continue
|
||||
}
|
||||
|
||||
// Echo expects datetime values to be in a certain format but that does not align with the datetime-local
|
||||
// HTML form element format, so we will attempt to convert it here.
|
||||
for _, format := range []string{dateTimeFormatNoSeconds, dateTimeFormat} {
|
||||
if t, err := time.Parse(format, v[0]); err == nil {
|
||||
ctx.Request().Form[k][0] = t.Format(time.RFC3339)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.Bind(entity)
|
||||
}
|
||||
|
||||
{{ end }}
|
||||
42
ent/admin/templates/types.tmpl
Normal file
42
ent/admin/templates/types.tmpl
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
{{/* Tell Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
|
||||
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
|
||||
|
||||
{{ define "admin/types" }}
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
package admin
|
||||
|
||||
{{- range $n := $.Nodes }}
|
||||
type {{ $n.Name }} struct {
|
||||
{{- range $f := $n.Fields }}
|
||||
{{ fieldName $f.Name }} {{ if (fieldIsPointer $f) }}*{{ end }}{{ $f.Type }} `form:"{{ $f.Name }}"`
|
||||
{{- end }}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
type EntityList struct {
|
||||
Columns []string
|
||||
Entities []EntityValues
|
||||
Page int
|
||||
HasNextPage bool
|
||||
}
|
||||
|
||||
type EntityValues struct {
|
||||
ID int
|
||||
Values []string
|
||||
}
|
||||
|
||||
type HandlerConfig struct {
|
||||
ItemsPerPage int
|
||||
PageQueryKey string
|
||||
TimeFormat string
|
||||
}
|
||||
|
||||
func GetEntityTypeNames() []string {
|
||||
return []string{
|
||||
{{- range $n := $.Nodes }}
|
||||
"{{ $n.Name }}",
|
||||
{{- end }}
|
||||
}
|
||||
}
|
||||
|
||||
{{ end }}
|
||||
44
ent/admin/types.go
Normal file
44
ent/admin/types.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// Code generated by ent, DO NOT EDIT.
|
||||
package admin
|
||||
|
||||
import "time"
|
||||
|
||||
type PasswordToken struct {
|
||||
Token *string `form:"token"`
|
||||
UserID int `form:"user_id"`
|
||||
CreatedAt *time.Time `form:"created_at"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
Name string `form:"name"`
|
||||
Email string `form:"email"`
|
||||
Password *string `form:"password"`
|
||||
Verified bool `form:"verified"`
|
||||
Admin bool `form:"admin"`
|
||||
CreatedAt *time.Time `form:"created_at"`
|
||||
}
|
||||
|
||||
type EntityList struct {
|
||||
Columns []string
|
||||
Entities []EntityValues
|
||||
Page int
|
||||
HasNextPage bool
|
||||
}
|
||||
|
||||
type EntityValues struct {
|
||||
ID int
|
||||
Values []string
|
||||
}
|
||||
|
||||
type HandlerConfig struct {
|
||||
ItemsPerPage int
|
||||
PageQueryKey string
|
||||
TimeFormat string
|
||||
}
|
||||
|
||||
func GetEntityTypeNames() []string {
|
||||
return []string{
|
||||
"PasswordToken",
|
||||
"User",
|
||||
}
|
||||
}
|
||||
|
|
@ -333,7 +333,8 @@ func (c *PasswordTokenClient) QueryUser(pt *PasswordToken) *UserQuery {
|
|||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *PasswordTokenClient) Hooks() []Hook {
|
||||
return c.hooks.PasswordToken
|
||||
hooks := c.hooks.PasswordToken
|
||||
return append(hooks[:len(hooks):len(hooks)], passwordtoken.Hooks[:]...)
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
|
|
|
|||
22
ent/entc.go
Normal file
22
ent/entc.go
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
//go:build ignore
|
||||
// +build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"entgo.io/ent/entc"
|
||||
"entgo.io/ent/entc/gen"
|
||||
"github.com/mikestefanello/pagoda/ent/admin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
err := entc.Generate("./schema",
|
||||
&gen.Config{},
|
||||
entc.Extensions(&admin.Extension{}),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal("running ent codegen:", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
package ent
|
||||
|
||||
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema
|
||||
//go:generate go run -mod=mod entc.go
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ var (
|
|||
// PasswordTokensColumns holds the columns for the "password_tokens" table.
|
||||
PasswordTokensColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "hash", Type: field.TypeString},
|
||||
{Name: "token", Type: field.TypeString},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "password_token_user", Type: field.TypeInt},
|
||||
{Name: "user_id", Type: field.TypeInt},
|
||||
}
|
||||
// PasswordTokensTable holds the schema information for the "password_tokens" table.
|
||||
PasswordTokensTable = &schema.Table{
|
||||
|
|
@ -36,6 +36,7 @@ var (
|
|||
{Name: "email", Type: field.TypeString, Unique: true},
|
||||
{Name: "password", Type: field.TypeString},
|
||||
{Name: "verified", Type: field.TypeBool, Default: false},
|
||||
{Name: "admin", Type: field.TypeBool, Default: false},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
|
|
|
|||
182
ent/mutation.go
182
ent/mutation.go
|
|
@ -35,7 +35,7 @@ type PasswordTokenMutation struct {
|
|||
op Op
|
||||
typ string
|
||||
id *int
|
||||
hash *string
|
||||
token *string
|
||||
created_at *time.Time
|
||||
clearedFields map[string]struct{}
|
||||
user *int
|
||||
|
|
@ -143,40 +143,76 @@ func (m *PasswordTokenMutation) IDs(ctx context.Context) ([]int, error) {
|
|||
}
|
||||
}
|
||||
|
||||
// SetHash sets the "hash" field.
|
||||
func (m *PasswordTokenMutation) SetHash(s string) {
|
||||
m.hash = &s
|
||||
// SetToken sets the "token" field.
|
||||
func (m *PasswordTokenMutation) SetToken(s string) {
|
||||
m.token = &s
|
||||
}
|
||||
|
||||
// Hash returns the value of the "hash" field in the mutation.
|
||||
func (m *PasswordTokenMutation) Hash() (r string, exists bool) {
|
||||
v := m.hash
|
||||
// Token returns the value of the "token" field in the mutation.
|
||||
func (m *PasswordTokenMutation) Token() (r string, exists bool) {
|
||||
v := m.token
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldHash returns the old "hash" field's value of the PasswordToken entity.
|
||||
// OldToken returns the old "token" field's value of the PasswordToken entity.
|
||||
// If the PasswordToken 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 *PasswordTokenMutation) OldHash(ctx context.Context) (v string, err error) {
|
||||
func (m *PasswordTokenMutation) OldToken(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldHash is only allowed on UpdateOne operations")
|
||||
return v, errors.New("OldToken is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldHash requires an ID field in the mutation")
|
||||
return v, errors.New("OldToken requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldHash: %w", err)
|
||||
return v, fmt.Errorf("querying old value for OldToken: %w", err)
|
||||
}
|
||||
return oldValue.Hash, nil
|
||||
return oldValue.Token, nil
|
||||
}
|
||||
|
||||
// ResetHash resets all changes to the "hash" field.
|
||||
func (m *PasswordTokenMutation) ResetHash() {
|
||||
m.hash = nil
|
||||
// ResetToken resets all changes to the "token" field.
|
||||
func (m *PasswordTokenMutation) ResetToken() {
|
||||
m.token = nil
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (m *PasswordTokenMutation) SetUserID(i int) {
|
||||
m.user = &i
|
||||
}
|
||||
|
||||
// UserID returns the value of the "user_id" field in the mutation.
|
||||
func (m *PasswordTokenMutation) UserID() (r int, exists bool) {
|
||||
v := m.user
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldUserID returns the old "user_id" field's value of the PasswordToken entity.
|
||||
// If the PasswordToken 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 *PasswordTokenMutation) OldUserID(ctx context.Context) (v int, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldUserID is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldUserID requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldUserID: %w", err)
|
||||
}
|
||||
return oldValue.UserID, nil
|
||||
}
|
||||
|
||||
// ResetUserID resets all changes to the "user_id" field.
|
||||
func (m *PasswordTokenMutation) ResetUserID() {
|
||||
m.user = nil
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
|
|
@ -215,14 +251,10 @@ func (m *PasswordTokenMutation) ResetCreatedAt() {
|
|||
m.created_at = nil
|
||||
}
|
||||
|
||||
// SetUserID sets the "user" edge to the User entity by id.
|
||||
func (m *PasswordTokenMutation) SetUserID(id int) {
|
||||
m.user = &id
|
||||
}
|
||||
|
||||
// ClearUser clears the "user" edge to the User entity.
|
||||
func (m *PasswordTokenMutation) ClearUser() {
|
||||
m.cleareduser = true
|
||||
m.clearedFields[passwordtoken.FieldUserID] = struct{}{}
|
||||
}
|
||||
|
||||
// UserCleared reports if the "user" edge to the User entity was cleared.
|
||||
|
|
@ -230,14 +262,6 @@ func (m *PasswordTokenMutation) UserCleared() bool {
|
|||
return m.cleareduser
|
||||
}
|
||||
|
||||
// UserID returns the "user" edge ID in the mutation.
|
||||
func (m *PasswordTokenMutation) UserID() (id int, exists bool) {
|
||||
if m.user != nil {
|
||||
return *m.user, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// UserIDs returns the "user" edge IDs in the mutation.
|
||||
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
|
||||
// UserID instead. It exists only for internal usage by the builders.
|
||||
|
|
@ -288,9 +312,12 @@ func (m *PasswordTokenMutation) Type() string {
|
|||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *PasswordTokenMutation) Fields() []string {
|
||||
fields := make([]string, 0, 2)
|
||||
if m.hash != nil {
|
||||
fields = append(fields, passwordtoken.FieldHash)
|
||||
fields := make([]string, 0, 3)
|
||||
if m.token != nil {
|
||||
fields = append(fields, passwordtoken.FieldToken)
|
||||
}
|
||||
if m.user != nil {
|
||||
fields = append(fields, passwordtoken.FieldUserID)
|
||||
}
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, passwordtoken.FieldCreatedAt)
|
||||
|
|
@ -303,8 +330,10 @@ func (m *PasswordTokenMutation) Fields() []string {
|
|||
// schema.
|
||||
func (m *PasswordTokenMutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case passwordtoken.FieldHash:
|
||||
return m.Hash()
|
||||
case passwordtoken.FieldToken:
|
||||
return m.Token()
|
||||
case passwordtoken.FieldUserID:
|
||||
return m.UserID()
|
||||
case passwordtoken.FieldCreatedAt:
|
||||
return m.CreatedAt()
|
||||
}
|
||||
|
|
@ -316,8 +345,10 @@ func (m *PasswordTokenMutation) Field(name string) (ent.Value, bool) {
|
|||
// database failed.
|
||||
func (m *PasswordTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
switch name {
|
||||
case passwordtoken.FieldHash:
|
||||
return m.OldHash(ctx)
|
||||
case passwordtoken.FieldToken:
|
||||
return m.OldToken(ctx)
|
||||
case passwordtoken.FieldUserID:
|
||||
return m.OldUserID(ctx)
|
||||
case passwordtoken.FieldCreatedAt:
|
||||
return m.OldCreatedAt(ctx)
|
||||
}
|
||||
|
|
@ -329,12 +360,19 @@ func (m *PasswordTokenMutation) OldField(ctx context.Context, name string) (ent.
|
|||
// type.
|
||||
func (m *PasswordTokenMutation) SetField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case passwordtoken.FieldHash:
|
||||
case passwordtoken.FieldToken:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetHash(v)
|
||||
m.SetToken(v)
|
||||
return nil
|
||||
case passwordtoken.FieldUserID:
|
||||
v, ok := value.(int)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetUserID(v)
|
||||
return nil
|
||||
case passwordtoken.FieldCreatedAt:
|
||||
v, ok := value.(time.Time)
|
||||
|
|
@ -350,13 +388,16 @@ func (m *PasswordTokenMutation) SetField(name string, value ent.Value) error {
|
|||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *PasswordTokenMutation) AddedFields() []string {
|
||||
return nil
|
||||
var fields []string
|
||||
return fields
|
||||
}
|
||||
|
||||
// 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 *PasswordTokenMutation) AddedField(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
|
|
@ -392,8 +433,11 @@ func (m *PasswordTokenMutation) ClearField(name string) error {
|
|||
// It returns an error if the field is not defined in the schema.
|
||||
func (m *PasswordTokenMutation) ResetField(name string) error {
|
||||
switch name {
|
||||
case passwordtoken.FieldHash:
|
||||
m.ResetHash()
|
||||
case passwordtoken.FieldToken:
|
||||
m.ResetToken()
|
||||
return nil
|
||||
case passwordtoken.FieldUserID:
|
||||
m.ResetUserID()
|
||||
return nil
|
||||
case passwordtoken.FieldCreatedAt:
|
||||
m.ResetCreatedAt()
|
||||
|
|
@ -486,6 +530,7 @@ type UserMutation struct {
|
|||
email *string
|
||||
password *string
|
||||
verified *bool
|
||||
admin *bool
|
||||
created_at *time.Time
|
||||
clearedFields map[string]struct{}
|
||||
owner map[int]struct{}
|
||||
|
|
@ -738,6 +783,42 @@ func (m *UserMutation) ResetVerified() {
|
|||
m.verified = nil
|
||||
}
|
||||
|
||||
// SetAdmin sets the "admin" field.
|
||||
func (m *UserMutation) SetAdmin(b bool) {
|
||||
m.admin = &b
|
||||
}
|
||||
|
||||
// Admin returns the value of the "admin" field in the mutation.
|
||||
func (m *UserMutation) Admin() (r bool, exists bool) {
|
||||
v := m.admin
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldAdmin returns the old "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) OldAdmin(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldAdmin is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldAdmin requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldAdmin: %w", err)
|
||||
}
|
||||
return oldValue.Admin, nil
|
||||
}
|
||||
|
||||
// ResetAdmin resets all changes to the "admin" field.
|
||||
func (m *UserMutation) ResetAdmin() {
|
||||
m.admin = nil
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (m *UserMutation) SetCreatedAt(t time.Time) {
|
||||
m.created_at = &t
|
||||
|
|
@ -862,7 +943,7 @@ func (m *UserMutation) Type() string {
|
|||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *UserMutation) Fields() []string {
|
||||
fields := make([]string, 0, 5)
|
||||
fields := make([]string, 0, 6)
|
||||
if m.name != nil {
|
||||
fields = append(fields, user.FieldName)
|
||||
}
|
||||
|
|
@ -875,6 +956,9 @@ func (m *UserMutation) Fields() []string {
|
|||
if m.verified != nil {
|
||||
fields = append(fields, user.FieldVerified)
|
||||
}
|
||||
if m.admin != nil {
|
||||
fields = append(fields, user.FieldAdmin)
|
||||
}
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, user.FieldCreatedAt)
|
||||
}
|
||||
|
|
@ -894,6 +978,8 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) {
|
|||
return m.Password()
|
||||
case user.FieldVerified:
|
||||
return m.Verified()
|
||||
case user.FieldAdmin:
|
||||
return m.Admin()
|
||||
case user.FieldCreatedAt:
|
||||
return m.CreatedAt()
|
||||
}
|
||||
|
|
@ -913,6 +999,8 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er
|
|||
return m.OldPassword(ctx)
|
||||
case user.FieldVerified:
|
||||
return m.OldVerified(ctx)
|
||||
case user.FieldAdmin:
|
||||
return m.OldAdmin(ctx)
|
||||
case user.FieldCreatedAt:
|
||||
return m.OldCreatedAt(ctx)
|
||||
}
|
||||
|
|
@ -952,6 +1040,13 @@ func (m *UserMutation) SetField(name string, value ent.Value) error {
|
|||
}
|
||||
m.SetVerified(v)
|
||||
return nil
|
||||
case user.FieldAdmin:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetAdmin(v)
|
||||
return nil
|
||||
case user.FieldCreatedAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
|
|
@ -1020,6 +1115,9 @@ func (m *UserMutation) ResetField(name string) error {
|
|||
case user.FieldVerified:
|
||||
m.ResetVerified()
|
||||
return nil
|
||||
case user.FieldAdmin:
|
||||
m.ResetAdmin()
|
||||
return nil
|
||||
case user.FieldCreatedAt:
|
||||
m.ResetCreatedAt()
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -18,15 +18,16 @@ type PasswordToken struct {
|
|||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// Hash holds the value of the "hash" field.
|
||||
Hash string `json:"-"`
|
||||
// Token holds the value of the "token" field.
|
||||
Token string `json:"-"`
|
||||
// UserID holds the value of the "user_id" field.
|
||||
UserID int `json:"user_id,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the PasswordTokenQuery when eager-loading is set.
|
||||
Edges PasswordTokenEdges `json:"edges"`
|
||||
password_token_user *int
|
||||
selectValues sql.SelectValues
|
||||
Edges PasswordTokenEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// PasswordTokenEdges holds the relations/edges for other nodes in the graph.
|
||||
|
|
@ -54,14 +55,12 @@ func (*PasswordToken) scanValues(columns []string) ([]any, error) {
|
|||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case passwordtoken.FieldID:
|
||||
case passwordtoken.FieldID, passwordtoken.FieldUserID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case passwordtoken.FieldHash:
|
||||
case passwordtoken.FieldToken:
|
||||
values[i] = new(sql.NullString)
|
||||
case passwordtoken.FieldCreatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
case passwordtoken.ForeignKeys[0]: // password_token_user
|
||||
values[i] = new(sql.NullInt64)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
|
|
@ -83,11 +82,17 @@ func (pt *PasswordToken) assignValues(columns []string, values []any) error {
|
|||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
pt.ID = int(value.Int64)
|
||||
case passwordtoken.FieldHash:
|
||||
case passwordtoken.FieldToken:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field hash", values[i])
|
||||
return fmt.Errorf("unexpected type %T for field token", values[i])
|
||||
} else if value.Valid {
|
||||
pt.Hash = value.String
|
||||
pt.Token = value.String
|
||||
}
|
||||
case passwordtoken.FieldUserID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_id", values[i])
|
||||
} else if value.Valid {
|
||||
pt.UserID = int(value.Int64)
|
||||
}
|
||||
case passwordtoken.FieldCreatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
|
|
@ -95,13 +100,6 @@ func (pt *PasswordToken) assignValues(columns []string, values []any) error {
|
|||
} else if value.Valid {
|
||||
pt.CreatedAt = value.Time
|
||||
}
|
||||
case passwordtoken.ForeignKeys[0]:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for edge-field password_token_user", value)
|
||||
} else if value.Valid {
|
||||
pt.password_token_user = new(int)
|
||||
*pt.password_token_user = int(value.Int64)
|
||||
}
|
||||
default:
|
||||
pt.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
|
|
@ -143,7 +141,10 @@ func (pt *PasswordToken) String() string {
|
|||
var builder strings.Builder
|
||||
builder.WriteString("PasswordToken(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", pt.ID))
|
||||
builder.WriteString("hash=<sensitive>")
|
||||
builder.WriteString("token=<sensitive>")
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("user_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", pt.UserID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(pt.CreatedAt.Format(time.ANSIC))
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ package passwordtoken
|
|||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
|
@ -14,8 +15,10 @@ const (
|
|||
Label = "password_token"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldHash holds the string denoting the hash field in the database.
|
||||
FieldHash = "hash"
|
||||
// FieldToken holds the string denoting the token field in the database.
|
||||
FieldToken = "token"
|
||||
// FieldUserID holds the string denoting the user_id field in the database.
|
||||
FieldUserID = "user_id"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// EdgeUser holds the string denoting the user edge name in mutations.
|
||||
|
|
@ -28,22 +31,17 @@ const (
|
|||
// It exists in this package in order to avoid circular dependency with the "user" package.
|
||||
UserInverseTable = "users"
|
||||
// UserColumn is the table column denoting the user relation/edge.
|
||||
UserColumn = "password_token_user"
|
||||
UserColumn = "user_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for passwordtoken fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldHash,
|
||||
FieldToken,
|
||||
FieldUserID,
|
||||
FieldCreatedAt,
|
||||
}
|
||||
|
||||
// ForeignKeys holds the SQL foreign-keys that are owned by the "password_tokens"
|
||||
// table and are not defined as standalone fields in the schema.
|
||||
var ForeignKeys = []string{
|
||||
"password_token_user",
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
|
|
@ -51,17 +49,18 @@ func ValidColumn(column string) bool {
|
|||
return true
|
||||
}
|
||||
}
|
||||
for i := range ForeignKeys {
|
||||
if column == ForeignKeys[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Note that the variables below are initialized by the runtime
|
||||
// package on the initialization of the application. Therefore,
|
||||
// it should be imported in the main as follows:
|
||||
//
|
||||
// import _ "github.com/mikestefanello/pagoda/ent/runtime"
|
||||
var (
|
||||
// HashValidator is a validator for the "hash" field. It is called by the builders before save.
|
||||
HashValidator func(string) error
|
||||
Hooks [1]ent.Hook
|
||||
// TokenValidator is a validator for the "token" field. It is called by the builders before save.
|
||||
TokenValidator func(string) error
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
)
|
||||
|
|
@ -74,9 +73,14 @@ func ByID(opts ...sql.OrderTermOption) OrderOption {
|
|||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByHash orders the results by the hash field.
|
||||
func ByHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldHash, opts...).ToFunc()
|
||||
// ByToken orders the results by the token field.
|
||||
func ByToken(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldToken, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserID orders the results by the user_id field.
|
||||
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
|
|
|
|||
|
|
@ -55,9 +55,14 @@ func IDLTE(id int) predicate.PasswordToken {
|
|||
return predicate.PasswordToken(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// Hash applies equality check predicate on the "hash" field. It's identical to HashEQ.
|
||||
func Hash(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEQ(FieldHash, v))
|
||||
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
|
||||
func Token(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEQ(FieldToken, v))
|
||||
}
|
||||
|
||||
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
|
||||
func UserID(v int) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
|
|
@ -65,69 +70,89 @@ func CreatedAt(v time.Time) predicate.PasswordToken {
|
|||
return predicate.PasswordToken(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// HashEQ applies the EQ predicate on the "hash" field.
|
||||
func HashEQ(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEQ(FieldHash, v))
|
||||
// TokenEQ applies the EQ predicate on the "token" field.
|
||||
func TokenEQ(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEQ(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashNEQ applies the NEQ predicate on the "hash" field.
|
||||
func HashNEQ(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldNEQ(FieldHash, v))
|
||||
// TokenNEQ applies the NEQ predicate on the "token" field.
|
||||
func TokenNEQ(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldNEQ(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashIn applies the In predicate on the "hash" field.
|
||||
func HashIn(vs ...string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldIn(FieldHash, vs...))
|
||||
// TokenIn applies the In predicate on the "token" field.
|
||||
func TokenIn(vs ...string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldIn(FieldToken, vs...))
|
||||
}
|
||||
|
||||
// HashNotIn applies the NotIn predicate on the "hash" field.
|
||||
func HashNotIn(vs ...string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldNotIn(FieldHash, vs...))
|
||||
// TokenNotIn applies the NotIn predicate on the "token" field.
|
||||
func TokenNotIn(vs ...string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldNotIn(FieldToken, vs...))
|
||||
}
|
||||
|
||||
// HashGT applies the GT predicate on the "hash" field.
|
||||
func HashGT(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldGT(FieldHash, v))
|
||||
// TokenGT applies the GT predicate on the "token" field.
|
||||
func TokenGT(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldGT(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashGTE applies the GTE predicate on the "hash" field.
|
||||
func HashGTE(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldGTE(FieldHash, v))
|
||||
// TokenGTE applies the GTE predicate on the "token" field.
|
||||
func TokenGTE(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldGTE(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashLT applies the LT predicate on the "hash" field.
|
||||
func HashLT(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldLT(FieldHash, v))
|
||||
// TokenLT applies the LT predicate on the "token" field.
|
||||
func TokenLT(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldLT(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashLTE applies the LTE predicate on the "hash" field.
|
||||
func HashLTE(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldLTE(FieldHash, v))
|
||||
// TokenLTE applies the LTE predicate on the "token" field.
|
||||
func TokenLTE(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldLTE(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashContains applies the Contains predicate on the "hash" field.
|
||||
func HashContains(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldContains(FieldHash, v))
|
||||
// TokenContains applies the Contains predicate on the "token" field.
|
||||
func TokenContains(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldContains(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashHasPrefix applies the HasPrefix predicate on the "hash" field.
|
||||
func HashHasPrefix(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldHasPrefix(FieldHash, v))
|
||||
// TokenHasPrefix applies the HasPrefix predicate on the "token" field.
|
||||
func TokenHasPrefix(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldHasPrefix(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashHasSuffix applies the HasSuffix predicate on the "hash" field.
|
||||
func HashHasSuffix(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldHasSuffix(FieldHash, v))
|
||||
// TokenHasSuffix applies the HasSuffix predicate on the "token" field.
|
||||
func TokenHasSuffix(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldHasSuffix(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashEqualFold applies the EqualFold predicate on the "hash" field.
|
||||
func HashEqualFold(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEqualFold(FieldHash, v))
|
||||
// TokenEqualFold applies the EqualFold predicate on the "token" field.
|
||||
func TokenEqualFold(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEqualFold(FieldToken, v))
|
||||
}
|
||||
|
||||
// HashContainsFold applies the ContainsFold predicate on the "hash" field.
|
||||
func HashContainsFold(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldContainsFold(FieldHash, v))
|
||||
// TokenContainsFold applies the ContainsFold predicate on the "token" field.
|
||||
func TokenContainsFold(v string) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldContainsFold(FieldToken, v))
|
||||
}
|
||||
|
||||
// UserIDEQ applies the EQ predicate on the "user_id" field.
|
||||
func UserIDEQ(v int) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
|
||||
func UserIDNEQ(v int) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldNEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDIn applies the In predicate on the "user_id" field.
|
||||
func UserIDIn(vs ...int) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
|
||||
func UserIDNotIn(vs ...int) predicate.PasswordToken {
|
||||
return predicate.PasswordToken(sql.FieldNotIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
|
|
|
|||
|
|
@ -21,9 +21,15 @@ type PasswordTokenCreate struct {
|
|||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetHash sets the "hash" field.
|
||||
func (ptc *PasswordTokenCreate) SetHash(s string) *PasswordTokenCreate {
|
||||
ptc.mutation.SetHash(s)
|
||||
// SetToken sets the "token" field.
|
||||
func (ptc *PasswordTokenCreate) SetToken(s string) *PasswordTokenCreate {
|
||||
ptc.mutation.SetToken(s)
|
||||
return ptc
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (ptc *PasswordTokenCreate) SetUserID(i int) *PasswordTokenCreate {
|
||||
ptc.mutation.SetUserID(i)
|
||||
return ptc
|
||||
}
|
||||
|
||||
|
|
@ -41,12 +47,6 @@ func (ptc *PasswordTokenCreate) SetNillableCreatedAt(t *time.Time) *PasswordToke
|
|||
return ptc
|
||||
}
|
||||
|
||||
// SetUserID sets the "user" edge to the User entity by ID.
|
||||
func (ptc *PasswordTokenCreate) SetUserID(id int) *PasswordTokenCreate {
|
||||
ptc.mutation.SetUserID(id)
|
||||
return ptc
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (ptc *PasswordTokenCreate) SetUser(u *User) *PasswordTokenCreate {
|
||||
return ptc.SetUserID(u.ID)
|
||||
|
|
@ -59,7 +59,9 @@ func (ptc *PasswordTokenCreate) Mutation() *PasswordTokenMutation {
|
|||
|
||||
// Save creates the PasswordToken in the database.
|
||||
func (ptc *PasswordTokenCreate) Save(ctx context.Context) (*PasswordToken, error) {
|
||||
ptc.defaults()
|
||||
if err := ptc.defaults(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return withHooks(ctx, ptc.sqlSave, ptc.mutation, ptc.hooks)
|
||||
}
|
||||
|
||||
|
|
@ -86,23 +88,30 @@ func (ptc *PasswordTokenCreate) ExecX(ctx context.Context) {
|
|||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (ptc *PasswordTokenCreate) defaults() {
|
||||
func (ptc *PasswordTokenCreate) defaults() error {
|
||||
if _, ok := ptc.mutation.CreatedAt(); !ok {
|
||||
if passwordtoken.DefaultCreatedAt == nil {
|
||||
return fmt.Errorf("ent: uninitialized passwordtoken.DefaultCreatedAt (forgotten import ent/runtime?)")
|
||||
}
|
||||
v := passwordtoken.DefaultCreatedAt()
|
||||
ptc.mutation.SetCreatedAt(v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (ptc *PasswordTokenCreate) check() error {
|
||||
if _, ok := ptc.mutation.Hash(); !ok {
|
||||
return &ValidationError{Name: "hash", err: errors.New(`ent: missing required field "PasswordToken.hash"`)}
|
||||
if _, ok := ptc.mutation.Token(); !ok {
|
||||
return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "PasswordToken.token"`)}
|
||||
}
|
||||
if v, ok := ptc.mutation.Hash(); ok {
|
||||
if err := passwordtoken.HashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "hash", err: fmt.Errorf(`ent: validator failed for field "PasswordToken.hash": %w`, err)}
|
||||
if v, ok := ptc.mutation.Token(); ok {
|
||||
if err := passwordtoken.TokenValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "PasswordToken.token": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := ptc.mutation.UserID(); !ok {
|
||||
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "PasswordToken.user_id"`)}
|
||||
}
|
||||
if _, ok := ptc.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "PasswordToken.created_at"`)}
|
||||
}
|
||||
|
|
@ -135,9 +144,9 @@ func (ptc *PasswordTokenCreate) createSpec() (*PasswordToken, *sqlgraph.CreateSp
|
|||
_node = &PasswordToken{config: ptc.config}
|
||||
_spec = sqlgraph.NewCreateSpec(passwordtoken.Table, sqlgraph.NewFieldSpec(passwordtoken.FieldID, field.TypeInt))
|
||||
)
|
||||
if value, ok := ptc.mutation.Hash(); ok {
|
||||
_spec.SetField(passwordtoken.FieldHash, field.TypeString, value)
|
||||
_node.Hash = value
|
||||
if value, ok := ptc.mutation.Token(); ok {
|
||||
_spec.SetField(passwordtoken.FieldToken, field.TypeString, value)
|
||||
_node.Token = value
|
||||
}
|
||||
if value, ok := ptc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(passwordtoken.FieldCreatedAt, field.TypeTime, value)
|
||||
|
|
@ -157,7 +166,7 @@ func (ptc *PasswordTokenCreate) createSpec() (*PasswordToken, *sqlgraph.CreateSp
|
|||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.password_token_user = &nodes[0]
|
||||
_node.UserID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@ type PasswordTokenQuery struct {
|
|||
inters []Interceptor
|
||||
predicates []predicate.PasswordToken
|
||||
withUser *UserQuery
|
||||
withFKs bool
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
|
|
@ -299,12 +298,12 @@ func (ptq *PasswordTokenQuery) WithUser(opts ...func(*UserQuery)) *PasswordToken
|
|||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Hash string `json:"hash,omitempty"`
|
||||
// Token string `json:"token,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.PasswordToken.Query().
|
||||
// GroupBy(passwordtoken.FieldHash).
|
||||
// GroupBy(passwordtoken.FieldToken).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (ptq *PasswordTokenQuery) GroupBy(field string, fields ...string) *PasswordTokenGroupBy {
|
||||
|
|
@ -322,11 +321,11 @@ func (ptq *PasswordTokenQuery) GroupBy(field string, fields ...string) *Password
|
|||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Hash string `json:"hash,omitempty"`
|
||||
// Token string `json:"token,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.PasswordToken.Query().
|
||||
// Select(passwordtoken.FieldHash).
|
||||
// Select(passwordtoken.FieldToken).
|
||||
// Scan(ctx, &v)
|
||||
func (ptq *PasswordTokenQuery) Select(fields ...string) *PasswordTokenSelect {
|
||||
ptq.ctx.Fields = append(ptq.ctx.Fields, fields...)
|
||||
|
|
@ -370,18 +369,11 @@ func (ptq *PasswordTokenQuery) prepareQuery(ctx context.Context) error {
|
|||
func (ptq *PasswordTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PasswordToken, error) {
|
||||
var (
|
||||
nodes = []*PasswordToken{}
|
||||
withFKs = ptq.withFKs
|
||||
_spec = ptq.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
ptq.withUser != nil,
|
||||
}
|
||||
)
|
||||
if ptq.withUser != nil {
|
||||
withFKs = true
|
||||
}
|
||||
if withFKs {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, passwordtoken.ForeignKeys...)
|
||||
}
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*PasswordToken).scanValues(nil, columns)
|
||||
}
|
||||
|
|
@ -413,10 +405,7 @@ func (ptq *PasswordTokenQuery) loadUser(ctx context.Context, query *UserQuery, n
|
|||
ids := make([]int, 0, len(nodes))
|
||||
nodeids := make(map[int][]*PasswordToken)
|
||||
for i := range nodes {
|
||||
if nodes[i].password_token_user == nil {
|
||||
continue
|
||||
}
|
||||
fk := *nodes[i].password_token_user
|
||||
fk := nodes[i].UserID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
|
|
@ -433,7 +422,7 @@ func (ptq *PasswordTokenQuery) loadUser(ctx context.Context, query *UserQuery, n
|
|||
for _, n := range neighbors {
|
||||
nodes, ok := nodeids[n.ID]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected foreign-key "password_token_user" returned %v`, n.ID)
|
||||
return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
|
|
@ -467,6 +456,9 @@ func (ptq *PasswordTokenQuery) querySpec() *sqlgraph.QuerySpec {
|
|||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if ptq.withUser != nil {
|
||||
_spec.Node.AddColumnOnce(passwordtoken.FieldUserID)
|
||||
}
|
||||
}
|
||||
if ps := ptq.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
|
|
|
|||
|
|
@ -29,16 +29,30 @@ func (ptu *PasswordTokenUpdate) Where(ps ...predicate.PasswordToken) *PasswordTo
|
|||
return ptu
|
||||
}
|
||||
|
||||
// SetHash sets the "hash" field.
|
||||
func (ptu *PasswordTokenUpdate) SetHash(s string) *PasswordTokenUpdate {
|
||||
ptu.mutation.SetHash(s)
|
||||
// SetToken sets the "token" field.
|
||||
func (ptu *PasswordTokenUpdate) SetToken(s string) *PasswordTokenUpdate {
|
||||
ptu.mutation.SetToken(s)
|
||||
return ptu
|
||||
}
|
||||
|
||||
// SetNillableHash sets the "hash" field if the given value is not nil.
|
||||
func (ptu *PasswordTokenUpdate) SetNillableHash(s *string) *PasswordTokenUpdate {
|
||||
// SetNillableToken sets the "token" field if the given value is not nil.
|
||||
func (ptu *PasswordTokenUpdate) SetNillableToken(s *string) *PasswordTokenUpdate {
|
||||
if s != nil {
|
||||
ptu.SetHash(*s)
|
||||
ptu.SetToken(*s)
|
||||
}
|
||||
return ptu
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (ptu *PasswordTokenUpdate) SetUserID(i int) *PasswordTokenUpdate {
|
||||
ptu.mutation.SetUserID(i)
|
||||
return ptu
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (ptu *PasswordTokenUpdate) SetNillableUserID(i *int) *PasswordTokenUpdate {
|
||||
if i != nil {
|
||||
ptu.SetUserID(*i)
|
||||
}
|
||||
return ptu
|
||||
}
|
||||
|
|
@ -57,12 +71,6 @@ func (ptu *PasswordTokenUpdate) SetNillableCreatedAt(t *time.Time) *PasswordToke
|
|||
return ptu
|
||||
}
|
||||
|
||||
// SetUserID sets the "user" edge to the User entity by ID.
|
||||
func (ptu *PasswordTokenUpdate) SetUserID(id int) *PasswordTokenUpdate {
|
||||
ptu.mutation.SetUserID(id)
|
||||
return ptu
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (ptu *PasswordTokenUpdate) SetUser(u *User) *PasswordTokenUpdate {
|
||||
return ptu.SetUserID(u.ID)
|
||||
|
|
@ -108,9 +116,9 @@ func (ptu *PasswordTokenUpdate) ExecX(ctx context.Context) {
|
|||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (ptu *PasswordTokenUpdate) check() error {
|
||||
if v, ok := ptu.mutation.Hash(); ok {
|
||||
if err := passwordtoken.HashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "hash", err: fmt.Errorf(`ent: validator failed for field "PasswordToken.hash": %w`, err)}
|
||||
if v, ok := ptu.mutation.Token(); ok {
|
||||
if err := passwordtoken.TokenValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "PasswordToken.token": %w`, err)}
|
||||
}
|
||||
}
|
||||
if ptu.mutation.UserCleared() && len(ptu.mutation.UserIDs()) > 0 {
|
||||
|
|
@ -131,8 +139,8 @@ func (ptu *PasswordTokenUpdate) sqlSave(ctx context.Context) (n int, err error)
|
|||
}
|
||||
}
|
||||
}
|
||||
if value, ok := ptu.mutation.Hash(); ok {
|
||||
_spec.SetField(passwordtoken.FieldHash, field.TypeString, value)
|
||||
if value, ok := ptu.mutation.Token(); ok {
|
||||
_spec.SetField(passwordtoken.FieldToken, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ptu.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(passwordtoken.FieldCreatedAt, field.TypeTime, value)
|
||||
|
|
@ -186,16 +194,30 @@ type PasswordTokenUpdateOne struct {
|
|||
mutation *PasswordTokenMutation
|
||||
}
|
||||
|
||||
// SetHash sets the "hash" field.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetHash(s string) *PasswordTokenUpdateOne {
|
||||
ptuo.mutation.SetHash(s)
|
||||
// SetToken sets the "token" field.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetToken(s string) *PasswordTokenUpdateOne {
|
||||
ptuo.mutation.SetToken(s)
|
||||
return ptuo
|
||||
}
|
||||
|
||||
// SetNillableHash sets the "hash" field if the given value is not nil.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetNillableHash(s *string) *PasswordTokenUpdateOne {
|
||||
// SetNillableToken sets the "token" field if the given value is not nil.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetNillableToken(s *string) *PasswordTokenUpdateOne {
|
||||
if s != nil {
|
||||
ptuo.SetHash(*s)
|
||||
ptuo.SetToken(*s)
|
||||
}
|
||||
return ptuo
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetUserID(i int) *PasswordTokenUpdateOne {
|
||||
ptuo.mutation.SetUserID(i)
|
||||
return ptuo
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetNillableUserID(i *int) *PasswordTokenUpdateOne {
|
||||
if i != nil {
|
||||
ptuo.SetUserID(*i)
|
||||
}
|
||||
return ptuo
|
||||
}
|
||||
|
|
@ -214,12 +236,6 @@ func (ptuo *PasswordTokenUpdateOne) SetNillableCreatedAt(t *time.Time) *Password
|
|||
return ptuo
|
||||
}
|
||||
|
||||
// SetUserID sets the "user" edge to the User entity by ID.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetUserID(id int) *PasswordTokenUpdateOne {
|
||||
ptuo.mutation.SetUserID(id)
|
||||
return ptuo
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (ptuo *PasswordTokenUpdateOne) SetUser(u *User) *PasswordTokenUpdateOne {
|
||||
return ptuo.SetUserID(u.ID)
|
||||
|
|
@ -278,9 +294,9 @@ func (ptuo *PasswordTokenUpdateOne) ExecX(ctx context.Context) {
|
|||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (ptuo *PasswordTokenUpdateOne) check() error {
|
||||
if v, ok := ptuo.mutation.Hash(); ok {
|
||||
if err := passwordtoken.HashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "hash", err: fmt.Errorf(`ent: validator failed for field "PasswordToken.hash": %w`, err)}
|
||||
if v, ok := ptuo.mutation.Token(); ok {
|
||||
if err := passwordtoken.TokenValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "PasswordToken.token": %w`, err)}
|
||||
}
|
||||
}
|
||||
if ptuo.mutation.UserCleared() && len(ptuo.mutation.UserIDs()) > 0 {
|
||||
|
|
@ -318,8 +334,8 @@ func (ptuo *PasswordTokenUpdateOne) sqlSave(ctx context.Context) (_node *Passwor
|
|||
}
|
||||
}
|
||||
}
|
||||
if value, ok := ptuo.mutation.Hash(); ok {
|
||||
_spec.SetField(passwordtoken.FieldHash, field.TypeString, value)
|
||||
if value, ok := ptuo.mutation.Token(); ok {
|
||||
_spec.SetField(passwordtoken.FieldToken, field.TypeString, value)
|
||||
}
|
||||
if value, ok := ptuo.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(passwordtoken.FieldCreatedAt, field.TypeTime, value)
|
||||
|
|
|
|||
|
|
@ -14,14 +14,16 @@ import (
|
|||
// (default values, validators, hooks and policies) and stitches it
|
||||
// to their package variables.
|
||||
func init() {
|
||||
passwordtokenHooks := schema.PasswordToken{}.Hooks()
|
||||
passwordtoken.Hooks[0] = passwordtokenHooks[0]
|
||||
passwordtokenFields := schema.PasswordToken{}.Fields()
|
||||
_ = passwordtokenFields
|
||||
// passwordtokenDescHash is the schema descriptor for hash field.
|
||||
passwordtokenDescHash := passwordtokenFields[0].Descriptor()
|
||||
// passwordtoken.HashValidator is a validator for the "hash" field. It is called by the builders before save.
|
||||
passwordtoken.HashValidator = passwordtokenDescHash.Validators[0].(func(string) error)
|
||||
// passwordtokenDescToken is the schema descriptor for token field.
|
||||
passwordtokenDescToken := passwordtokenFields[0].Descriptor()
|
||||
// passwordtoken.TokenValidator is a validator for the "token" field. It is called by the builders before save.
|
||||
passwordtoken.TokenValidator = passwordtokenDescToken.Validators[0].(func(string) error)
|
||||
// passwordtokenDescCreatedAt is the schema descriptor for created_at field.
|
||||
passwordtokenDescCreatedAt := passwordtokenFields[1].Descriptor()
|
||||
passwordtokenDescCreatedAt := passwordtokenFields[2].Descriptor()
|
||||
// passwordtoken.DefaultCreatedAt holds the default value on creation for the created_at field.
|
||||
passwordtoken.DefaultCreatedAt = passwordtokenDescCreatedAt.Default.(func() time.Time)
|
||||
userHooks := schema.User{}.Hooks()
|
||||
|
|
@ -35,7 +37,21 @@ func init() {
|
|||
// userDescEmail is the schema descriptor for email field.
|
||||
userDescEmail := userFields[1].Descriptor()
|
||||
// user.EmailValidator is a validator for the "email" field. It is called by the builders before save.
|
||||
user.EmailValidator = userDescEmail.Validators[0].(func(string) error)
|
||||
user.EmailValidator = func() func(string) error {
|
||||
validators := userDescEmail.Validators
|
||||
fns := [...]func(string) error{
|
||||
validators[0].(func(string) error),
|
||||
validators[1].(func(string) error),
|
||||
}
|
||||
return func(email string) error {
|
||||
for _, fn := range fns {
|
||||
if err := fn(email); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}()
|
||||
// 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.
|
||||
|
|
@ -44,13 +60,17 @@ func init() {
|
|||
userDescVerified := userFields[3].Descriptor()
|
||||
// user.DefaultVerified holds the default value on creation for the verified field.
|
||||
user.DefaultVerified = userDescVerified.Default.(bool)
|
||||
// userDescAdmin is the schema descriptor for admin field.
|
||||
userDescAdmin := userFields[4].Descriptor()
|
||||
// user.DefaultAdmin holds the default value on creation for the admin field.
|
||||
user.DefaultAdmin = userDescAdmin.Default.(bool)
|
||||
// userDescCreatedAt is the schema descriptor for created_at field.
|
||||
userDescCreatedAt := userFields[4].Descriptor()
|
||||
userDescCreatedAt := userFields[5].Descriptor()
|
||||
// user.DefaultCreatedAt holds the default value on creation for the created_at field.
|
||||
user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
|
||||
}
|
||||
|
||||
const (
|
||||
Version = "v0.14.2" // Version of ent codegen.
|
||||
Sum = "h1:ywld/j2Rx4EmnIKs8eZ29cbFA1zpB+DA9TLL5l3rlq0=" // Sum of ent codegen.
|
||||
Version = "v0.14.4" // Version of ent codegen.
|
||||
Sum = "h1:/DhDraSLXIkBhyiVoJeSshr4ZYi7femzhj6/TckzZuI=" // Sum of ent codegen.
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
package schema
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
ge "github.com/mikestefanello/pagoda/ent"
|
||||
"github.com/mikestefanello/pagoda/ent/hook"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// PasswordToken holds the schema definition for the PasswordToken entity.
|
||||
|
|
@ -16,9 +20,10 @@ type PasswordToken struct {
|
|||
// Fields of the PasswordToken.
|
||||
func (PasswordToken) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("hash").
|
||||
field.String("token").
|
||||
Sensitive().
|
||||
NotEmpty(),
|
||||
field.Int("user_id"),
|
||||
field.Time("created_at").
|
||||
Default(time.Now),
|
||||
}
|
||||
|
|
@ -28,7 +33,30 @@ func (PasswordToken) Fields() []ent.Field {
|
|||
func (PasswordToken) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("user", User.Type).
|
||||
Field("user_id").
|
||||
Required().
|
||||
Unique(),
|
||||
}
|
||||
}
|
||||
|
||||
// Hooks of the PasswordToken.
|
||||
func (PasswordToken) Hooks() []ent.Hook {
|
||||
return []ent.Hook{
|
||||
hook.On(
|
||||
func(next ent.Mutator) ent.Mutator {
|
||||
return hook.PasswordTokenFunc(func(ctx context.Context, m *ge.PasswordTokenMutation) (ent.Value, error) {
|
||||
if v, exists := m.Token(); exists {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(v), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m.SetToken(string(hash))
|
||||
}
|
||||
return next.Mutate(ctx, m)
|
||||
})
|
||||
},
|
||||
// Limit the hook only for these operations.
|
||||
ent.OpCreate|ent.OpUpdate|ent.OpUpdateOne,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,13 @@ package schema
|
|||
|
||||
import (
|
||||
"context"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
ge "github.com/mikestefanello/pagoda/ent"
|
||||
"github.com/mikestefanello/pagoda/ent/hook"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
|
|
@ -25,12 +27,18 @@ func (User) Fields() []ent.Field {
|
|||
NotEmpty(),
|
||||
field.String("email").
|
||||
NotEmpty().
|
||||
Unique(),
|
||||
Unique().
|
||||
Validate(func(s string) error {
|
||||
_, err := mail.ParseAddress(s)
|
||||
return err
|
||||
}),
|
||||
field.String("password").
|
||||
Sensitive().
|
||||
NotEmpty(),
|
||||
field.Bool("verified").
|
||||
Default(false),
|
||||
field.Bool("admin").
|
||||
Default(false),
|
||||
field.Time("created_at").
|
||||
Default(time.Now).
|
||||
Immutable(),
|
||||
|
|
@ -54,6 +62,14 @@ func (User) Hooks() []ent.Hook {
|
|||
if v, exists := m.Email(); exists {
|
||||
m.SetEmail(strings.ToLower(v))
|
||||
}
|
||||
|
||||
if v, exists := m.Password(); exists {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(v), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m.SetPassword(string(hash))
|
||||
}
|
||||
return next.Mutate(ctx, m)
|
||||
})
|
||||
},
|
||||
|
|
|
|||
13
ent/user.go
13
ent/user.go
|
|
@ -25,6 +25,8 @@ type User struct {
|
|||
Password string `json:"-"`
|
||||
// Verified holds the value of the "verified" field.
|
||||
Verified bool `json:"verified,omitempty"`
|
||||
// Admin holds the value of the "admin" field.
|
||||
Admin bool `json:"admin,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
|
|
@ -56,7 +58,7 @@ func (*User) scanValues(columns []string) ([]any, error) {
|
|||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case user.FieldVerified:
|
||||
case user.FieldVerified, user.FieldAdmin:
|
||||
values[i] = new(sql.NullBool)
|
||||
case user.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
|
|
@ -109,6 +111,12 @@ func (u *User) assignValues(columns []string, values []any) error {
|
|||
} else if value.Valid {
|
||||
u.Verified = value.Bool
|
||||
}
|
||||
case user.FieldAdmin:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field admin", values[i])
|
||||
} else if value.Valid {
|
||||
u.Admin = 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])
|
||||
|
|
@ -167,6 +175,9 @@ func (u *User) String() string {
|
|||
builder.WriteString("verified=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Verified))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("admin=")
|
||||
builder.WriteString(fmt.Sprintf("%v", u.Admin))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ const (
|
|||
FieldPassword = "password"
|
||||
// FieldVerified holds the string denoting the verified field in the database.
|
||||
FieldVerified = "verified"
|
||||
// FieldAdmin holds the string denoting the admin field in the database.
|
||||
FieldAdmin = "admin"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// EdgeOwner holds the string denoting the owner edge name in mutations.
|
||||
|
|
@ -35,7 +37,7 @@ const (
|
|||
// It exists in this package in order to avoid circular dependency with the "passwordtoken" package.
|
||||
OwnerInverseTable = "password_tokens"
|
||||
// OwnerColumn is the table column denoting the owner relation/edge.
|
||||
OwnerColumn = "password_token_user"
|
||||
OwnerColumn = "user_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for user fields.
|
||||
|
|
@ -45,6 +47,7 @@ var Columns = []string{
|
|||
FieldEmail,
|
||||
FieldPassword,
|
||||
FieldVerified,
|
||||
FieldAdmin,
|
||||
FieldCreatedAt,
|
||||
}
|
||||
|
||||
|
|
@ -73,6 +76,8 @@ var (
|
|||
PasswordValidator func(string) error
|
||||
// DefaultVerified holds the default value on creation for the "verified" field.
|
||||
DefaultVerified bool
|
||||
// DefaultAdmin holds the default value on creation for the "admin" field.
|
||||
DefaultAdmin bool
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
)
|
||||
|
|
@ -105,6 +110,11 @@ func ByVerified(opts ...sql.OrderTermOption) OrderOption {
|
|||
return sql.OrderByField(FieldVerified, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAdmin orders the results by the admin field.
|
||||
func ByAdmin(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAdmin, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
|
|
|
|||
|
|
@ -75,6 +75,11 @@ func Verified(v bool) predicate.User {
|
|||
return predicate.User(sql.FieldEQ(FieldVerified, v))
|
||||
}
|
||||
|
||||
// Admin applies equality check predicate on the "admin" field. It's identical to AdminEQ.
|
||||
func Admin(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldAdmin, 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))
|
||||
|
|
@ -285,6 +290,16 @@ func VerifiedNEQ(v bool) predicate.User {
|
|||
return predicate.User(sql.FieldNEQ(FieldVerified, v))
|
||||
}
|
||||
|
||||
// AdminEQ applies the EQ predicate on the "admin" field.
|
||||
func AdminEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldAdmin, v))
|
||||
}
|
||||
|
||||
// AdminNEQ applies the NEQ predicate on the "admin" field.
|
||||
func AdminNEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldAdmin, 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))
|
||||
|
|
|
|||
|
|
@ -53,6 +53,20 @@ func (uc *UserCreate) SetNillableVerified(b *bool) *UserCreate {
|
|||
return uc
|
||||
}
|
||||
|
||||
// SetAdmin sets the "admin" field.
|
||||
func (uc *UserCreate) SetAdmin(b bool) *UserCreate {
|
||||
uc.mutation.SetAdmin(b)
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetNillableAdmin sets the "admin" field if the given value is not nil.
|
||||
func (uc *UserCreate) SetNillableAdmin(b *bool) *UserCreate {
|
||||
if b != nil {
|
||||
uc.SetAdmin(*b)
|
||||
}
|
||||
return uc
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (uc *UserCreate) SetCreatedAt(t time.Time) *UserCreate {
|
||||
uc.mutation.SetCreatedAt(t)
|
||||
|
|
@ -123,6 +137,10 @@ func (uc *UserCreate) defaults() error {
|
|||
v := user.DefaultVerified
|
||||
uc.mutation.SetVerified(v)
|
||||
}
|
||||
if _, ok := uc.mutation.Admin(); !ok {
|
||||
v := user.DefaultAdmin
|
||||
uc.mutation.SetAdmin(v)
|
||||
}
|
||||
if _, ok := uc.mutation.CreatedAt(); !ok {
|
||||
if user.DefaultCreatedAt == nil {
|
||||
return fmt.Errorf("ent: uninitialized user.DefaultCreatedAt (forgotten import ent/runtime?)")
|
||||
|
|
@ -162,6 +180,9 @@ func (uc *UserCreate) check() error {
|
|||
if _, ok := uc.mutation.Verified(); !ok {
|
||||
return &ValidationError{Name: "verified", err: errors.New(`ent: missing required field "User.verified"`)}
|
||||
}
|
||||
if _, ok := uc.mutation.Admin(); !ok {
|
||||
return &ValidationError{Name: "admin", err: errors.New(`ent: missing required field "User.admin"`)}
|
||||
}
|
||||
if _, ok := uc.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "User.created_at"`)}
|
||||
}
|
||||
|
|
@ -207,6 +228,10 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
|
|||
_spec.SetField(user.FieldVerified, field.TypeBool, value)
|
||||
_node.Verified = value
|
||||
}
|
||||
if value, ok := uc.mutation.Admin(); ok {
|
||||
_spec.SetField(user.FieldAdmin, field.TypeBool, value)
|
||||
_node.Admin = value
|
||||
}
|
||||
if value, ok := uc.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
|
|
|
|||
|
|
@ -413,7 +413,9 @@ func (uq *UserQuery) loadOwner(ctx context.Context, query *PasswordTokenQuery, n
|
|||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
query.withFKs = true
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(passwordtoken.FieldUserID)
|
||||
}
|
||||
query.Where(predicate.PasswordToken(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(user.OwnerColumn), fks...))
|
||||
}))
|
||||
|
|
@ -422,13 +424,10 @@ func (uq *UserQuery) loadOwner(ctx context.Context, query *PasswordTokenQuery, n
|
|||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.password_token_user
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "password_token_user" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
fk := n.UserID
|
||||
node, ok := nodeids[fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "password_token_user" returned %v for node %v`, *fk, n.ID)
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,6 +84,20 @@ func (uu *UserUpdate) SetNillableVerified(b *bool) *UserUpdate {
|
|||
return uu
|
||||
}
|
||||
|
||||
// SetAdmin sets the "admin" field.
|
||||
func (uu *UserUpdate) SetAdmin(b bool) *UserUpdate {
|
||||
uu.mutation.SetAdmin(b)
|
||||
return uu
|
||||
}
|
||||
|
||||
// SetNillableAdmin sets the "admin" field if the given value is not nil.
|
||||
func (uu *UserUpdate) SetNillableAdmin(b *bool) *UserUpdate {
|
||||
if b != nil {
|
||||
uu.SetAdmin(*b)
|
||||
}
|
||||
return uu
|
||||
}
|
||||
|
||||
// AddOwnerIDs adds the "owner" edge to the PasswordToken entity by IDs.
|
||||
func (uu *UserUpdate) AddOwnerIDs(ids ...int) *UserUpdate {
|
||||
uu.mutation.AddOwnerIDs(ids...)
|
||||
|
|
@ -196,6 +210,9 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
|
|||
if value, ok := uu.mutation.Verified(); ok {
|
||||
_spec.SetField(user.FieldVerified, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := uu.mutation.Admin(); ok {
|
||||
_spec.SetField(user.FieldAdmin, field.TypeBool, value)
|
||||
}
|
||||
if uu.mutation.OwnerCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
|
|
@ -317,6 +334,20 @@ func (uuo *UserUpdateOne) SetNillableVerified(b *bool) *UserUpdateOne {
|
|||
return uuo
|
||||
}
|
||||
|
||||
// SetAdmin sets the "admin" field.
|
||||
func (uuo *UserUpdateOne) SetAdmin(b bool) *UserUpdateOne {
|
||||
uuo.mutation.SetAdmin(b)
|
||||
return uuo
|
||||
}
|
||||
|
||||
// SetNillableAdmin sets the "admin" field if the given value is not nil.
|
||||
func (uuo *UserUpdateOne) SetNillableAdmin(b *bool) *UserUpdateOne {
|
||||
if b != nil {
|
||||
uuo.SetAdmin(*b)
|
||||
}
|
||||
return uuo
|
||||
}
|
||||
|
||||
// AddOwnerIDs adds the "owner" edge to the PasswordToken entity by IDs.
|
||||
func (uuo *UserUpdateOne) AddOwnerIDs(ids ...int) *UserUpdateOne {
|
||||
uuo.mutation.AddOwnerIDs(ids...)
|
||||
|
|
@ -459,6 +490,9 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
|
|||
if value, ok := uuo.mutation.Verified(); ok {
|
||||
_spec.SetField(user.FieldVerified, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := uuo.mutation.Admin(); ok {
|
||||
_spec.SetField(user.FieldAdmin, field.TypeBool, value)
|
||||
}
|
||||
if uuo.mutation.OwnerCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue