This commit is contained in:
xmdhs 2023-09-03 15:59:37 +08:00
parent 280b0ad839
commit 7f2e37ccc0
No known key found for this signature in database
GPG Key ID: E809D6D43DEFCC95
53 changed files with 10098 additions and 526 deletions

View File

@ -12,4 +12,5 @@ type Config struct {
}
Node int64
Epoch int64
Debug bool
}

637
db/ent/client.go Normal file
View File

@ -0,0 +1,637 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"github.com/xmdhs/authlib-skin/db/ent/migrate"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// 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
// Skin is the client for interacting with the Skin builders.
Skin *SkinClient
// User is the client for interacting with the User builders.
User *UserClient
// UserProfile is the client for interacting with the UserProfile builders.
UserProfile *UserProfileClient
}
// 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.Skin = NewSkinClient(c.config)
c.User = NewUserClient(c.config)
c.UserProfile = NewUserProfileClient(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,
Skin: NewSkinClient(cfg),
User: NewUserClient(cfg),
UserProfile: NewUserProfileClient(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,
Skin: NewSkinClient(cfg),
User: NewUserClient(cfg),
UserProfile: NewUserProfileClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Skin.
// 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.Skin.Use(hooks...)
c.User.Use(hooks...)
c.UserProfile.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.Skin.Intercept(interceptors...)
c.User.Intercept(interceptors...)
c.UserProfile.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *SkinMutation:
return c.Skin.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
case *UserProfileMutation:
return c.UserProfile.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// SkinClient is a client for the Skin schema.
type SkinClient struct {
config
}
// NewSkinClient returns a client for the Skin from the given config.
func NewSkinClient(c config) *SkinClient {
return &SkinClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `skin.Hooks(f(g(h())))`.
func (c *SkinClient) Use(hooks ...Hook) {
c.hooks.Skin = append(c.hooks.Skin, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `skin.Intercept(f(g(h())))`.
func (c *SkinClient) Intercept(interceptors ...Interceptor) {
c.inters.Skin = append(c.inters.Skin, interceptors...)
}
// Create returns a builder for creating a Skin entity.
func (c *SkinClient) Create() *SkinCreate {
mutation := newSkinMutation(c.config, OpCreate)
return &SkinCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Skin entities.
func (c *SkinClient) CreateBulk(builders ...*SkinCreate) *SkinCreateBulk {
return &SkinCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Skin.
func (c *SkinClient) Update() *SkinUpdate {
mutation := newSkinMutation(c.config, OpUpdate)
return &SkinUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *SkinClient) UpdateOne(s *Skin) *SkinUpdateOne {
mutation := newSkinMutation(c.config, OpUpdateOne, withSkin(s))
return &SkinUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *SkinClient) UpdateOneID(id int) *SkinUpdateOne {
mutation := newSkinMutation(c.config, OpUpdateOne, withSkinID(id))
return &SkinUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Skin.
func (c *SkinClient) Delete() *SkinDelete {
mutation := newSkinMutation(c.config, OpDelete)
return &SkinDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *SkinClient) DeleteOne(s *Skin) *SkinDeleteOne {
return c.DeleteOneID(s.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *SkinClient) DeleteOneID(id int) *SkinDeleteOne {
builder := c.Delete().Where(skin.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &SkinDeleteOne{builder}
}
// Query returns a query builder for Skin.
func (c *SkinClient) Query() *SkinQuery {
return &SkinQuery{
config: c.config,
ctx: &QueryContext{Type: TypeSkin},
inters: c.Interceptors(),
}
}
// Get returns a Skin entity by its id.
func (c *SkinClient) Get(ctx context.Context, id int) (*Skin, error) {
return c.Query().Where(skin.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *SkinClient) GetX(ctx context.Context, id int) *Skin {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUser queries the user edge of a Skin.
func (c *SkinClient) QueryUser(s *Skin) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := s.ID
step := sqlgraph.NewStep(
sqlgraph.From(skin.Table, skin.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, skin.UserTable, skin.UserColumn),
)
fromV = sqlgraph.Neighbors(s.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *SkinClient) Hooks() []Hook {
return c.hooks.Skin
}
// Interceptors returns the client interceptors.
func (c *SkinClient) Interceptors() []Interceptor {
return c.inters.Skin
}
func (c *SkinClient) mutate(ctx context.Context, m *SkinMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&SkinCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&SkinUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&SkinUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&SkinDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Skin mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
func (c *UserClient) Intercept(interceptors ...Interceptor) {
c.inters.User = append(c.inters.User, interceptors...)
}
// Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of User entities.
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
return &UserCreateBulk{config: c.config, builders: builders}
}
// 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 int) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
mutation := newUserMutation(c.config, OpDelete)
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(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 int) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserDeleteOne{builder}
}
// Query returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUser},
inters: c.Interceptors(),
}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QuerySkin queries the skin edge of a User.
func (c *UserClient) QuerySkin(u *User) *SkinQuery {
query := (&SkinClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := u.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(skin.Table, skin.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, user.SkinTable, user.SkinColumn),
)
fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryProfile queries the profile edge of a User.
func (c *UserClient) QueryProfile(u *User) *UserProfileQuery {
query := (&UserProfileClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := u.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(userprofile.Table, userprofile.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, user.ProfileTable, user.ProfileColumn),
)
fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
}
// Interceptors returns the client interceptors.
func (c *UserClient) Interceptors() []Interceptor {
return c.inters.User
}
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op())
}
}
// UserProfileClient is a client for the UserProfile schema.
type UserProfileClient struct {
config
}
// NewUserProfileClient returns a client for the UserProfile from the given config.
func NewUserProfileClient(c config) *UserProfileClient {
return &UserProfileClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `userprofile.Hooks(f(g(h())))`.
func (c *UserProfileClient) Use(hooks ...Hook) {
c.hooks.UserProfile = append(c.hooks.UserProfile, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `userprofile.Intercept(f(g(h())))`.
func (c *UserProfileClient) Intercept(interceptors ...Interceptor) {
c.inters.UserProfile = append(c.inters.UserProfile, interceptors...)
}
// Create returns a builder for creating a UserProfile entity.
func (c *UserProfileClient) Create() *UserProfileCreate {
mutation := newUserProfileMutation(c.config, OpCreate)
return &UserProfileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of UserProfile entities.
func (c *UserProfileClient) CreateBulk(builders ...*UserProfileCreate) *UserProfileCreateBulk {
return &UserProfileCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for UserProfile.
func (c *UserProfileClient) Update() *UserProfileUpdate {
mutation := newUserProfileMutation(c.config, OpUpdate)
return &UserProfileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserProfileClient) UpdateOne(up *UserProfile) *UserProfileUpdateOne {
mutation := newUserProfileMutation(c.config, OpUpdateOne, withUserProfile(up))
return &UserProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserProfileClient) UpdateOneID(id int) *UserProfileUpdateOne {
mutation := newUserProfileMutation(c.config, OpUpdateOne, withUserProfileID(id))
return &UserProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for UserProfile.
func (c *UserProfileClient) Delete() *UserProfileDelete {
mutation := newUserProfileMutation(c.config, OpDelete)
return &UserProfileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserProfileClient) DeleteOne(up *UserProfile) *UserProfileDeleteOne {
return c.DeleteOneID(up.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserProfileClient) DeleteOneID(id int) *UserProfileDeleteOne {
builder := c.Delete().Where(userprofile.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserProfileDeleteOne{builder}
}
// Query returns a query builder for UserProfile.
func (c *UserProfileClient) Query() *UserProfileQuery {
return &UserProfileQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUserProfile},
inters: c.Interceptors(),
}
}
// Get returns a UserProfile entity by its id.
func (c *UserProfileClient) Get(ctx context.Context, id int) (*UserProfile, error) {
return c.Query().Where(userprofile.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserProfileClient) GetX(ctx context.Context, id int) *UserProfile {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUser queries the user edge of a UserProfile.
func (c *UserProfileClient) QueryUser(up *UserProfile) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := up.ID
step := sqlgraph.NewStep(
sqlgraph.From(userprofile.Table, userprofile.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, userprofile.UserTable, userprofile.UserColumn),
)
fromV = sqlgraph.Neighbors(up.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserProfileClient) Hooks() []Hook {
return c.hooks.UserProfile
}
// Interceptors returns the client interceptors.
func (c *UserProfileClient) Interceptors() []Interceptor {
return c.inters.UserProfile
}
func (c *UserProfileClient) mutate(ctx context.Context, m *UserProfileMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserProfileCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserProfileUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserProfileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserProfileDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown UserProfile mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Skin, User, UserProfile []ent.Hook
}
inters struct {
Skin, User, UserProfile []ent.Interceptor
}
)

612
db/ent/ent.go Normal file
View File

@ -0,0 +1,612 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// columnChecker checks if the column exists in the given table.
func checkColumn(table, column string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
skin.Table: skin.ValidColumn,
user.Table: user.ValidColumn,
userprofile.Table: userprofile.ValidColumn,
})
})
return columnCheck(table, column)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

84
db/ent/enttest/enttest.go Normal file
View File

@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"github.com/xmdhs/authlib-skin/db/ent"
// required by schema hooks.
_ "github.com/xmdhs/authlib-skin/db/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"github.com/xmdhs/authlib-skin/db/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
db/ent/generate.go Normal file
View File

@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/lock ./schema

223
db/ent/hook/hook.go Normal file
View File

@ -0,0 +1,223 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"github.com/xmdhs/authlib-skin/db/ent"
)
// The SkinFunc type is an adapter to allow the use of ordinary
// function as Skin mutator.
type SkinFunc func(context.Context, *ent.SkinMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SkinFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SkinMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SkinMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
// The UserProfileFunc type is an adapter to allow the use of ordinary
// function as UserProfile mutator.
type UserProfileFunc func(context.Context, *ent.UserProfileMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserProfileFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserProfileMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserProfileMutation", 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
db/ent/migrate/migrate.go Normal file
View 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...)
}

87
db/ent/migrate/schema.go Normal file
View File

@ -0,0 +1,87 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// SkinsColumns holds the columns for the "skins" table.
SkinsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "skin_hash", Type: field.TypeString},
{Name: "type", Type: field.TypeUint8},
{Name: "variant", Type: field.TypeString},
{Name: "skin_user", Type: field.TypeInt},
}
// SkinsTable holds the schema information for the "skins" table.
SkinsTable = &schema.Table{
Name: "skins",
Columns: SkinsColumns,
PrimaryKey: []*schema.Column{SkinsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "skins_users_user",
Columns: []*schema.Column{SkinsColumns[4]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "email", Type: field.TypeString, Unique: true},
{Name: "password", Type: field.TypeString},
{Name: "salt", Type: field.TypeString},
{Name: "state", Type: field.TypeInt},
{Name: "reg_time", Type: field.TypeInt64},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// UserProfilesColumns holds the columns for the "user_profiles" table.
UserProfilesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString},
{Name: "uuid", Type: field.TypeString},
{Name: "user_profile", Type: field.TypeInt, Unique: true},
}
// UserProfilesTable holds the schema information for the "user_profiles" table.
UserProfilesTable = &schema.Table{
Name: "user_profiles",
Columns: UserProfilesColumns,
PrimaryKey: []*schema.Column{UserProfilesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_profiles_users_profile",
Columns: []*schema.Column{UserProfilesColumns[3]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
},
Indexes: []*schema.Index{
{
Name: "userprofile_name",
Unique: false,
Columns: []*schema.Column{UserProfilesColumns[1]},
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
SkinsTable,
UsersTable,
UserProfilesTable,
}
)
func init() {
SkinsTable.ForeignKeys[0].RefTable = UsersTable
UserProfilesTable.ForeignKeys[0].RefTable = UsersTable
}

1778
db/ent/mutation.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Skin is the predicate function for skin builders.
type Skin func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)
// UserProfile is the predicate function for userprofile builders.
type UserProfile func(*sql.Selector)

9
db/ent/runtime.go Normal file
View File

@ -0,0 +1,9 @@
// Code generated by ent, DO NOT EDIT.
package ent
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
}

View File

@ -0,0 +1,9 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in github.com/xmdhs/authlib-skin/db/ent/runtime.go
const (
Version = "(devel)" // Version of ent codegen.
)

28
db/ent/schema/skin.go Normal file
View File

@ -0,0 +1,28 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Skin holds the schema definition for the Skin entity.
type Skin struct {
ent.Schema
}
// Fields of the Skin.
func (Skin) Fields() []ent.Field {
return []ent.Field{
field.String("skin_hash"),
field.Uint8("type"),
field.String("variant"),
}
}
// Edges of the Skin.
func (Skin) Edges() []ent.Edge {
return []ent.Edge{
edge.To("user", User.Type).Unique().Required(),
}
}

32
db/ent/schema/user.go Normal file
View File

@ -0,0 +1,32 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("email").Unique(),
field.String("password"),
field.String("salt"),
field.Int("state"),
field.Int64("reg_time"),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.From("skin", Skin.Type).Ref("user").Annotations(entsql.OnDelete(entsql.Cascade)),
edge.To("profile", UserProfile.Type).Unique().Annotations(entsql.OnDelete(entsql.Cascade)),
}
}

View File

@ -0,0 +1,34 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// UserProfile holds the schema definition for the UserProfile entity.
type UserProfile struct {
ent.Schema
}
// Fields of the UserProfile.
func (UserProfile) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
field.String("uuid"),
}
}
// Edges of the UserProfile.
func (UserProfile) Edges() []ent.Edge {
return []ent.Edge{
edge.From("user", User.Type).Ref("profile").Required().Unique(),
}
}
func (UserProfile) Indexes() []ent.Index {
return []ent.Index{
index.Fields("name"),
}
}

166
db/ent/skin.go Normal file
View File

@ -0,0 +1,166 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
)
// Skin is the model entity for the Skin schema.
type Skin struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// SkinHash holds the value of the "skin_hash" field.
SkinHash string `json:"skin_hash,omitempty"`
// Type holds the value of the "type" field.
Type uint8 `json:"type,omitempty"`
// Variant holds the value of the "variant" field.
Variant string `json:"variant,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the SkinQuery when eager-loading is set.
Edges SkinEdges `json:"edges"`
skin_user *int
selectValues sql.SelectValues
}
// SkinEdges holds the relations/edges for other nodes in the graph.
type SkinEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e SkinEdges) UserOrErr() (*User, error) {
if e.loadedTypes[0] {
if e.User == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: user.Label}
}
return e.User, nil
}
return nil, &NotLoadedError{edge: "user"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Skin) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case skin.FieldID, skin.FieldType:
values[i] = new(sql.NullInt64)
case skin.FieldSkinHash, skin.FieldVariant:
values[i] = new(sql.NullString)
case skin.ForeignKeys[0]: // skin_user
values[i] = new(sql.NullInt64)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Skin fields.
func (s *Skin) 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 skin.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
s.ID = int(value.Int64)
case skin.FieldSkinHash:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field skin_hash", values[i])
} else if value.Valid {
s.SkinHash = value.String
}
case skin.FieldType:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
s.Type = uint8(value.Int64)
}
case skin.FieldVariant:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field variant", values[i])
} else if value.Valid {
s.Variant = value.String
}
case skin.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field skin_user", value)
} else if value.Valid {
s.skin_user = new(int)
*s.skin_user = int(value.Int64)
}
default:
s.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Skin.
// This includes values selected through modifiers, order, etc.
func (s *Skin) Value(name string) (ent.Value, error) {
return s.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the Skin entity.
func (s *Skin) QueryUser() *UserQuery {
return NewSkinClient(s.config).QueryUser(s)
}
// Update returns a builder for updating this Skin.
// Note that you need to call Skin.Unwrap() before calling this method if this Skin
// was returned from a transaction, and the transaction was committed or rolled back.
func (s *Skin) Update() *SkinUpdateOne {
return NewSkinClient(s.config).UpdateOne(s)
}
// Unwrap unwraps the Skin 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 (s *Skin) Unwrap() *Skin {
_tx, ok := s.config.driver.(*txDriver)
if !ok {
panic("ent: Skin is not a transactional entity")
}
s.config.driver = _tx.drv
return s
}
// String implements the fmt.Stringer.
func (s *Skin) String() string {
var builder strings.Builder
builder.WriteString("Skin(")
builder.WriteString(fmt.Sprintf("id=%v, ", s.ID))
builder.WriteString("skin_hash=")
builder.WriteString(s.SkinHash)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", s.Type))
builder.WriteString(", ")
builder.WriteString("variant=")
builder.WriteString(s.Variant)
builder.WriteByte(')')
return builder.String()
}
// Skins is a parsable slice of Skin.
type Skins []*Skin

98
db/ent/skin/skin.go Normal file
View File

@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package skin
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the skin type in the database.
Label = "skin"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldSkinHash holds the string denoting the skin_hash field in the database.
FieldSkinHash = "skin_hash"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldVariant holds the string denoting the variant field in the database.
FieldVariant = "variant"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// Table holds the table name of the skin in the database.
Table = "skins"
// UserTable is the table that holds the user relation/edge.
UserTable = "skins"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "skin_user"
)
// Columns holds all SQL columns for skin fields.
var Columns = []string{
FieldID,
FieldSkinHash,
FieldType,
FieldVariant,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "skins"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"skin_user",
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
// OrderOption defines the ordering options for the Skin queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// BySkinHash orders the results by the skin_hash field.
func BySkinHash(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSkinHash, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByVariant orders the results by the variant field.
func ByVariant(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVariant, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
}

294
db/ent/skin/where.go Normal file
View File

@ -0,0 +1,294 @@
// Code generated by ent, DO NOT EDIT.
package skin
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Skin {
return predicate.Skin(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Skin {
return predicate.Skin(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Skin {
return predicate.Skin(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Skin {
return predicate.Skin(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Skin {
return predicate.Skin(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Skin {
return predicate.Skin(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Skin {
return predicate.Skin(sql.FieldLTE(FieldID, id))
}
// SkinHash applies equality check predicate on the "skin_hash" field. It's identical to SkinHashEQ.
func SkinHash(v string) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldSkinHash, v))
}
// Type applies equality check predicate on the "type" field. It's identical to TypeEQ.
func Type(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldType, v))
}
// Variant applies equality check predicate on the "variant" field. It's identical to VariantEQ.
func Variant(v string) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldVariant, v))
}
// SkinHashEQ applies the EQ predicate on the "skin_hash" field.
func SkinHashEQ(v string) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldSkinHash, v))
}
// SkinHashNEQ applies the NEQ predicate on the "skin_hash" field.
func SkinHashNEQ(v string) predicate.Skin {
return predicate.Skin(sql.FieldNEQ(FieldSkinHash, v))
}
// SkinHashIn applies the In predicate on the "skin_hash" field.
func SkinHashIn(vs ...string) predicate.Skin {
return predicate.Skin(sql.FieldIn(FieldSkinHash, vs...))
}
// SkinHashNotIn applies the NotIn predicate on the "skin_hash" field.
func SkinHashNotIn(vs ...string) predicate.Skin {
return predicate.Skin(sql.FieldNotIn(FieldSkinHash, vs...))
}
// SkinHashGT applies the GT predicate on the "skin_hash" field.
func SkinHashGT(v string) predicate.Skin {
return predicate.Skin(sql.FieldGT(FieldSkinHash, v))
}
// SkinHashGTE applies the GTE predicate on the "skin_hash" field.
func SkinHashGTE(v string) predicate.Skin {
return predicate.Skin(sql.FieldGTE(FieldSkinHash, v))
}
// SkinHashLT applies the LT predicate on the "skin_hash" field.
func SkinHashLT(v string) predicate.Skin {
return predicate.Skin(sql.FieldLT(FieldSkinHash, v))
}
// SkinHashLTE applies the LTE predicate on the "skin_hash" field.
func SkinHashLTE(v string) predicate.Skin {
return predicate.Skin(sql.FieldLTE(FieldSkinHash, v))
}
// SkinHashContains applies the Contains predicate on the "skin_hash" field.
func SkinHashContains(v string) predicate.Skin {
return predicate.Skin(sql.FieldContains(FieldSkinHash, v))
}
// SkinHashHasPrefix applies the HasPrefix predicate on the "skin_hash" field.
func SkinHashHasPrefix(v string) predicate.Skin {
return predicate.Skin(sql.FieldHasPrefix(FieldSkinHash, v))
}
// SkinHashHasSuffix applies the HasSuffix predicate on the "skin_hash" field.
func SkinHashHasSuffix(v string) predicate.Skin {
return predicate.Skin(sql.FieldHasSuffix(FieldSkinHash, v))
}
// SkinHashEqualFold applies the EqualFold predicate on the "skin_hash" field.
func SkinHashEqualFold(v string) predicate.Skin {
return predicate.Skin(sql.FieldEqualFold(FieldSkinHash, v))
}
// SkinHashContainsFold applies the ContainsFold predicate on the "skin_hash" field.
func SkinHashContainsFold(v string) predicate.Skin {
return predicate.Skin(sql.FieldContainsFold(FieldSkinHash, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...uint8) predicate.Skin {
return predicate.Skin(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...uint8) predicate.Skin {
return predicate.Skin(sql.FieldNotIn(FieldType, vs...))
}
// TypeGT applies the GT predicate on the "type" field.
func TypeGT(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldGT(FieldType, v))
}
// TypeGTE applies the GTE predicate on the "type" field.
func TypeGTE(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldGTE(FieldType, v))
}
// TypeLT applies the LT predicate on the "type" field.
func TypeLT(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldLT(FieldType, v))
}
// TypeLTE applies the LTE predicate on the "type" field.
func TypeLTE(v uint8) predicate.Skin {
return predicate.Skin(sql.FieldLTE(FieldType, v))
}
// VariantEQ applies the EQ predicate on the "variant" field.
func VariantEQ(v string) predicate.Skin {
return predicate.Skin(sql.FieldEQ(FieldVariant, v))
}
// VariantNEQ applies the NEQ predicate on the "variant" field.
func VariantNEQ(v string) predicate.Skin {
return predicate.Skin(sql.FieldNEQ(FieldVariant, v))
}
// VariantIn applies the In predicate on the "variant" field.
func VariantIn(vs ...string) predicate.Skin {
return predicate.Skin(sql.FieldIn(FieldVariant, vs...))
}
// VariantNotIn applies the NotIn predicate on the "variant" field.
func VariantNotIn(vs ...string) predicate.Skin {
return predicate.Skin(sql.FieldNotIn(FieldVariant, vs...))
}
// VariantGT applies the GT predicate on the "variant" field.
func VariantGT(v string) predicate.Skin {
return predicate.Skin(sql.FieldGT(FieldVariant, v))
}
// VariantGTE applies the GTE predicate on the "variant" field.
func VariantGTE(v string) predicate.Skin {
return predicate.Skin(sql.FieldGTE(FieldVariant, v))
}
// VariantLT applies the LT predicate on the "variant" field.
func VariantLT(v string) predicate.Skin {
return predicate.Skin(sql.FieldLT(FieldVariant, v))
}
// VariantLTE applies the LTE predicate on the "variant" field.
func VariantLTE(v string) predicate.Skin {
return predicate.Skin(sql.FieldLTE(FieldVariant, v))
}
// VariantContains applies the Contains predicate on the "variant" field.
func VariantContains(v string) predicate.Skin {
return predicate.Skin(sql.FieldContains(FieldVariant, v))
}
// VariantHasPrefix applies the HasPrefix predicate on the "variant" field.
func VariantHasPrefix(v string) predicate.Skin {
return predicate.Skin(sql.FieldHasPrefix(FieldVariant, v))
}
// VariantHasSuffix applies the HasSuffix predicate on the "variant" field.
func VariantHasSuffix(v string) predicate.Skin {
return predicate.Skin(sql.FieldHasSuffix(FieldVariant, v))
}
// VariantEqualFold applies the EqualFold predicate on the "variant" field.
func VariantEqualFold(v string) predicate.Skin {
return predicate.Skin(sql.FieldEqualFold(FieldVariant, v))
}
// VariantContainsFold applies the ContainsFold predicate on the "variant" field.
func VariantContainsFold(v string) predicate.Skin {
return predicate.Skin(sql.FieldContainsFold(FieldVariant, v))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.Skin {
return predicate.Skin(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.Skin {
return predicate.Skin(func(s *sql.Selector) {
step := newUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Skin) predicate.Skin {
return predicate.Skin(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.Skin) predicate.Skin {
return predicate.Skin(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.Skin) predicate.Skin {
return predicate.Skin(func(s *sql.Selector) {
p(s.Not())
})
}

237
db/ent/skin_create.go Normal file
View File

@ -0,0 +1,237 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
)
// SkinCreate is the builder for creating a Skin entity.
type SkinCreate struct {
config
mutation *SkinMutation
hooks []Hook
}
// SetSkinHash sets the "skin_hash" field.
func (sc *SkinCreate) SetSkinHash(s string) *SkinCreate {
sc.mutation.SetSkinHash(s)
return sc
}
// SetType sets the "type" field.
func (sc *SkinCreate) SetType(u uint8) *SkinCreate {
sc.mutation.SetType(u)
return sc
}
// SetVariant sets the "variant" field.
func (sc *SkinCreate) SetVariant(s string) *SkinCreate {
sc.mutation.SetVariant(s)
return sc
}
// SetUserID sets the "user" edge to the User entity by ID.
func (sc *SkinCreate) SetUserID(id int) *SkinCreate {
sc.mutation.SetUserID(id)
return sc
}
// SetUser sets the "user" edge to the User entity.
func (sc *SkinCreate) SetUser(u *User) *SkinCreate {
return sc.SetUserID(u.ID)
}
// Mutation returns the SkinMutation object of the builder.
func (sc *SkinCreate) Mutation() *SkinMutation {
return sc.mutation
}
// Save creates the Skin in the database.
func (sc *SkinCreate) Save(ctx context.Context) (*Skin, error) {
return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (sc *SkinCreate) SaveX(ctx context.Context) *Skin {
v, err := sc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (sc *SkinCreate) Exec(ctx context.Context) error {
_, err := sc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (sc *SkinCreate) ExecX(ctx context.Context) {
if err := sc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (sc *SkinCreate) check() error {
if _, ok := sc.mutation.SkinHash(); !ok {
return &ValidationError{Name: "skin_hash", err: errors.New(`ent: missing required field "Skin.skin_hash"`)}
}
if _, ok := sc.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Skin.type"`)}
}
if _, ok := sc.mutation.Variant(); !ok {
return &ValidationError{Name: "variant", err: errors.New(`ent: missing required field "Skin.variant"`)}
}
if _, ok := sc.mutation.UserID(); !ok {
return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "Skin.user"`)}
}
return nil
}
func (sc *SkinCreate) sqlSave(ctx context.Context) (*Skin, error) {
if err := sc.check(); err != nil {
return nil, err
}
_node, _spec := sc.createSpec()
if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
sc.mutation.id = &_node.ID
sc.mutation.done = true
return _node, nil
}
func (sc *SkinCreate) createSpec() (*Skin, *sqlgraph.CreateSpec) {
var (
_node = &Skin{config: sc.config}
_spec = sqlgraph.NewCreateSpec(skin.Table, sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt))
)
if value, ok := sc.mutation.SkinHash(); ok {
_spec.SetField(skin.FieldSkinHash, field.TypeString, value)
_node.SkinHash = value
}
if value, ok := sc.mutation.GetType(); ok {
_spec.SetField(skin.FieldType, field.TypeUint8, value)
_node.Type = value
}
if value, ok := sc.mutation.Variant(); ok {
_spec.SetField(skin.FieldVariant, field.TypeString, value)
_node.Variant = value
}
if nodes := sc.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: skin.UserTable,
Columns: []string{skin.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.skin_user = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// SkinCreateBulk is the builder for creating many Skin entities in bulk.
type SkinCreateBulk struct {
config
builders []*SkinCreate
}
// Save creates the Skin entities in the database.
func (scb *SkinCreateBulk) Save(ctx context.Context) ([]*Skin, error) {
specs := make([]*sqlgraph.CreateSpec, len(scb.builders))
nodes := make([]*Skin, len(scb.builders))
mutators := make([]Mutator, len(scb.builders))
for i := range scb.builders {
func(i int, root context.Context) {
builder := scb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SkinMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, scb.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, scb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (scb *SkinCreateBulk) SaveX(ctx context.Context) []*Skin {
v, err := scb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (scb *SkinCreateBulk) Exec(ctx context.Context) error {
_, err := scb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (scb *SkinCreateBulk) ExecX(ctx context.Context) {
if err := scb.Exec(ctx); err != nil {
panic(err)
}
}

88
db/ent/skin_delete.go Normal file
View 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"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/skin"
)
// SkinDelete is the builder for deleting a Skin entity.
type SkinDelete struct {
config
hooks []Hook
mutation *SkinMutation
}
// Where appends a list predicates to the SkinDelete builder.
func (sd *SkinDelete) Where(ps ...predicate.Skin) *SkinDelete {
sd.mutation.Where(ps...)
return sd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (sd *SkinDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (sd *SkinDelete) ExecX(ctx context.Context) int {
n, err := sd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (sd *SkinDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(skin.Table, sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt))
if ps := sd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
sd.mutation.done = true
return affected, err
}
// SkinDeleteOne is the builder for deleting a single Skin entity.
type SkinDeleteOne struct {
sd *SkinDelete
}
// Where appends a list predicates to the SkinDelete builder.
func (sdo *SkinDeleteOne) Where(ps ...predicate.Skin) *SkinDeleteOne {
sdo.sd.mutation.Where(ps...)
return sdo
}
// Exec executes the deletion query.
func (sdo *SkinDeleteOne) Exec(ctx context.Context) error {
n, err := sdo.sd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{skin.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (sdo *SkinDeleteOne) ExecX(ctx context.Context) {
if err := sdo.Exec(ctx); err != nil {
panic(err)
}
}

650
db/ent/skin_query.go Normal file
View File

@ -0,0 +1,650 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
)
// SkinQuery is the builder for querying Skin entities.
type SkinQuery struct {
config
ctx *QueryContext
order []skin.OrderOption
inters []Interceptor
predicates []predicate.Skin
withUser *UserQuery
withFKs bool
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the SkinQuery builder.
func (sq *SkinQuery) Where(ps ...predicate.Skin) *SkinQuery {
sq.predicates = append(sq.predicates, ps...)
return sq
}
// Limit the number of records to be returned by this query.
func (sq *SkinQuery) Limit(limit int) *SkinQuery {
sq.ctx.Limit = &limit
return sq
}
// Offset to start from.
func (sq *SkinQuery) Offset(offset int) *SkinQuery {
sq.ctx.Offset = &offset
return sq
}
// 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 (sq *SkinQuery) Unique(unique bool) *SkinQuery {
sq.ctx.Unique = &unique
return sq
}
// Order specifies how the records should be ordered.
func (sq *SkinQuery) Order(o ...skin.OrderOption) *SkinQuery {
sq.order = append(sq.order, o...)
return sq
}
// QueryUser chains the current query on the "user" edge.
func (sq *SkinQuery) QueryUser() *UserQuery {
query := (&UserClient{config: sq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := sq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := sq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(skin.Table, skin.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, skin.UserTable, skin.UserColumn),
)
fromU = sqlgraph.SetNeighbors(sq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Skin entity from the query.
// Returns a *NotFoundError when no Skin was found.
func (sq *SkinQuery) First(ctx context.Context) (*Skin, error) {
nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{skin.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (sq *SkinQuery) FirstX(ctx context.Context) *Skin {
node, err := sq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Skin ID from the query.
// Returns a *NotFoundError when no Skin ID was found.
func (sq *SkinQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{skin.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (sq *SkinQuery) FirstIDX(ctx context.Context) int {
id, err := sq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Skin entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Skin entity is found.
// Returns a *NotFoundError when no Skin entities are found.
func (sq *SkinQuery) Only(ctx context.Context) (*Skin, error) {
nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{skin.Label}
default:
return nil, &NotSingularError{skin.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (sq *SkinQuery) OnlyX(ctx context.Context) *Skin {
node, err := sq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Skin ID in the query.
// Returns a *NotSingularError when more than one Skin ID is found.
// Returns a *NotFoundError when no entities are found.
func (sq *SkinQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{skin.Label}
default:
err = &NotSingularError{skin.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (sq *SkinQuery) OnlyIDX(ctx context.Context) int {
id, err := sq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Skins.
func (sq *SkinQuery) All(ctx context.Context) ([]*Skin, error) {
ctx = setContextOp(ctx, sq.ctx, "All")
if err := sq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Skin, *SkinQuery]()
return withInterceptors[[]*Skin](ctx, sq, qr, sq.inters)
}
// AllX is like All, but panics if an error occurs.
func (sq *SkinQuery) AllX(ctx context.Context) []*Skin {
nodes, err := sq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Skin IDs.
func (sq *SkinQuery) IDs(ctx context.Context) (ids []int, err error) {
if sq.ctx.Unique == nil && sq.path != nil {
sq.Unique(true)
}
ctx = setContextOp(ctx, sq.ctx, "IDs")
if err = sq.Select(skin.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (sq *SkinQuery) IDsX(ctx context.Context) []int {
ids, err := sq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (sq *SkinQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, sq.ctx, "Count")
if err := sq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, sq, querierCount[*SkinQuery](), sq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (sq *SkinQuery) CountX(ctx context.Context) int {
count, err := sq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (sq *SkinQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, sq.ctx, "Exist")
switch _, err := sq.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 (sq *SkinQuery) ExistX(ctx context.Context) bool {
exist, err := sq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the SkinQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (sq *SkinQuery) Clone() *SkinQuery {
if sq == nil {
return nil
}
return &SkinQuery{
config: sq.config,
ctx: sq.ctx.Clone(),
order: append([]skin.OrderOption{}, sq.order...),
inters: append([]Interceptor{}, sq.inters...),
predicates: append([]predicate.Skin{}, sq.predicates...),
withUser: sq.withUser.Clone(),
// clone intermediate query.
sql: sq.sql.Clone(),
path: sq.path,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (sq *SkinQuery) WithUser(opts ...func(*UserQuery)) *SkinQuery {
query := (&UserClient{config: sq.config}).Query()
for _, opt := range opts {
opt(query)
}
sq.withUser = query
return sq
}
// 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 {
// SkinHash string `json:"skin_hash,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Skin.Query().
// GroupBy(skin.FieldSkinHash).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (sq *SkinQuery) GroupBy(field string, fields ...string) *SkinGroupBy {
sq.ctx.Fields = append([]string{field}, fields...)
grbuild := &SkinGroupBy{build: sq}
grbuild.flds = &sq.ctx.Fields
grbuild.label = skin.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 {
// SkinHash string `json:"skin_hash,omitempty"`
// }
//
// client.Skin.Query().
// Select(skin.FieldSkinHash).
// Scan(ctx, &v)
func (sq *SkinQuery) Select(fields ...string) *SkinSelect {
sq.ctx.Fields = append(sq.ctx.Fields, fields...)
sbuild := &SkinSelect{SkinQuery: sq}
sbuild.label = skin.Label
sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a SkinSelect configured with the given aggregations.
func (sq *SkinQuery) Aggregate(fns ...AggregateFunc) *SkinSelect {
return sq.Select().Aggregate(fns...)
}
func (sq *SkinQuery) prepareQuery(ctx context.Context) error {
for _, inter := range sq.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, sq); err != nil {
return err
}
}
}
for _, f := range sq.ctx.Fields {
if !skin.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if sq.path != nil {
prev, err := sq.path(ctx)
if err != nil {
return err
}
sq.sql = prev
}
return nil
}
func (sq *SkinQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Skin, error) {
var (
nodes = []*Skin{}
withFKs = sq.withFKs
_spec = sq.querySpec()
loadedTypes = [1]bool{
sq.withUser != nil,
}
)
if sq.withUser != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, skin.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Skin).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Skin{config: sq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
if len(sq.modifiers) > 0 {
_spec.Modifiers = sq.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := sq.withUser; query != nil {
if err := sq.loadUser(ctx, query, nodes, nil,
func(n *Skin, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (sq *SkinQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Skin, init func(*Skin), assign func(*Skin, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Skin)
for i := range nodes {
if nodes[i].skin_user == nil {
continue
}
fk := *nodes[i].skin_user
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "skin_user" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (sq *SkinQuery) sqlCount(ctx context.Context) (int, error) {
_spec := sq.querySpec()
if len(sq.modifiers) > 0 {
_spec.Modifiers = sq.modifiers
}
_spec.Node.Columns = sq.ctx.Fields
if len(sq.ctx.Fields) > 0 {
_spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, sq.driver, _spec)
}
func (sq *SkinQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(skin.Table, skin.Columns, sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt))
_spec.From = sq.sql
if unique := sq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if sq.path != nil {
_spec.Unique = true
}
if fields := sq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, skin.FieldID)
for i := range fields {
if fields[i] != skin.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := sq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := sq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := sq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := sq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (sq *SkinQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(sq.driver.Dialect())
t1 := builder.Table(skin.Table)
columns := sq.ctx.Fields
if len(columns) == 0 {
columns = skin.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if sq.sql != nil {
selector = sq.sql
selector.Select(selector.Columns(columns...)...)
}
if sq.ctx.Unique != nil && *sq.ctx.Unique {
selector.Distinct()
}
for _, m := range sq.modifiers {
m(selector)
}
for _, p := range sq.predicates {
p(selector)
}
for _, p := range sq.order {
p(selector)
}
if offset := sq.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 := sq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (sq *SkinQuery) ForUpdate(opts ...sql.LockOption) *SkinQuery {
if sq.driver.Dialect() == dialect.Postgres {
sq.Unique(false)
}
sq.modifiers = append(sq.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return sq
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (sq *SkinQuery) ForShare(opts ...sql.LockOption) *SkinQuery {
if sq.driver.Dialect() == dialect.Postgres {
sq.Unique(false)
}
sq.modifiers = append(sq.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return sq
}
// SkinGroupBy is the group-by builder for Skin entities.
type SkinGroupBy struct {
selector
build *SkinQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (sgb *SkinGroupBy) Aggregate(fns ...AggregateFunc) *SkinGroupBy {
sgb.fns = append(sgb.fns, fns...)
return sgb
}
// Scan applies the selector query and scans the result into the given value.
func (sgb *SkinGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, sgb.build.ctx, "GroupBy")
if err := sgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*SkinQuery, *SkinGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v)
}
func (sgb *SkinGroupBy) sqlScan(ctx context.Context, root *SkinQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(sgb.fns))
for _, fn := range sgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns))
for _, f := range *sgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*sgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// SkinSelect is the builder for selecting fields of Skin entities.
type SkinSelect struct {
*SkinQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (ss *SkinSelect) Aggregate(fns ...AggregateFunc) *SkinSelect {
ss.fns = append(ss.fns, fns...)
return ss
}
// Scan applies the selector query and scans the result into the given value.
func (ss *SkinSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ss.ctx, "Select")
if err := ss.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*SkinQuery, *SkinSelect](ctx, ss.SkinQuery, ss, ss.inters, v)
}
func (ss *SkinSelect) sqlScan(ctx context.Context, root *SkinQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(ss.fns))
for _, fn := range ss.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*ss.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 := ss.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

364
db/ent/skin_update.go Normal file
View File

@ -0,0 +1,364 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
)
// SkinUpdate is the builder for updating Skin entities.
type SkinUpdate struct {
config
hooks []Hook
mutation *SkinMutation
}
// Where appends a list predicates to the SkinUpdate builder.
func (su *SkinUpdate) Where(ps ...predicate.Skin) *SkinUpdate {
su.mutation.Where(ps...)
return su
}
// SetSkinHash sets the "skin_hash" field.
func (su *SkinUpdate) SetSkinHash(s string) *SkinUpdate {
su.mutation.SetSkinHash(s)
return su
}
// SetType sets the "type" field.
func (su *SkinUpdate) SetType(u uint8) *SkinUpdate {
su.mutation.ResetType()
su.mutation.SetType(u)
return su
}
// AddType adds u to the "type" field.
func (su *SkinUpdate) AddType(u int8) *SkinUpdate {
su.mutation.AddType(u)
return su
}
// SetVariant sets the "variant" field.
func (su *SkinUpdate) SetVariant(s string) *SkinUpdate {
su.mutation.SetVariant(s)
return su
}
// SetUserID sets the "user" edge to the User entity by ID.
func (su *SkinUpdate) SetUserID(id int) *SkinUpdate {
su.mutation.SetUserID(id)
return su
}
// SetUser sets the "user" edge to the User entity.
func (su *SkinUpdate) SetUser(u *User) *SkinUpdate {
return su.SetUserID(u.ID)
}
// Mutation returns the SkinMutation object of the builder.
func (su *SkinUpdate) Mutation() *SkinMutation {
return su.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (su *SkinUpdate) ClearUser() *SkinUpdate {
su.mutation.ClearUser()
return su
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (su *SkinUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, su.sqlSave, su.mutation, su.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (su *SkinUpdate) SaveX(ctx context.Context) int {
affected, err := su.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (su *SkinUpdate) Exec(ctx context.Context) error {
_, err := su.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (su *SkinUpdate) ExecX(ctx context.Context) {
if err := su.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (su *SkinUpdate) check() error {
if _, ok := su.mutation.UserID(); su.mutation.UserCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Skin.user"`)
}
return nil
}
func (su *SkinUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := su.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(skin.Table, skin.Columns, sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt))
if ps := su.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := su.mutation.SkinHash(); ok {
_spec.SetField(skin.FieldSkinHash, field.TypeString, value)
}
if value, ok := su.mutation.GetType(); ok {
_spec.SetField(skin.FieldType, field.TypeUint8, value)
}
if value, ok := su.mutation.AddedType(); ok {
_spec.AddField(skin.FieldType, field.TypeUint8, value)
}
if value, ok := su.mutation.Variant(); ok {
_spec.SetField(skin.FieldVariant, field.TypeString, value)
}
if su.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: skin.UserTable,
Columns: []string{skin.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := su.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: skin.UserTable,
Columns: []string{skin.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{skin.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
su.mutation.done = true
return n, nil
}
// SkinUpdateOne is the builder for updating a single Skin entity.
type SkinUpdateOne struct {
config
fields []string
hooks []Hook
mutation *SkinMutation
}
// SetSkinHash sets the "skin_hash" field.
func (suo *SkinUpdateOne) SetSkinHash(s string) *SkinUpdateOne {
suo.mutation.SetSkinHash(s)
return suo
}
// SetType sets the "type" field.
func (suo *SkinUpdateOne) SetType(u uint8) *SkinUpdateOne {
suo.mutation.ResetType()
suo.mutation.SetType(u)
return suo
}
// AddType adds u to the "type" field.
func (suo *SkinUpdateOne) AddType(u int8) *SkinUpdateOne {
suo.mutation.AddType(u)
return suo
}
// SetVariant sets the "variant" field.
func (suo *SkinUpdateOne) SetVariant(s string) *SkinUpdateOne {
suo.mutation.SetVariant(s)
return suo
}
// SetUserID sets the "user" edge to the User entity by ID.
func (suo *SkinUpdateOne) SetUserID(id int) *SkinUpdateOne {
suo.mutation.SetUserID(id)
return suo
}
// SetUser sets the "user" edge to the User entity.
func (suo *SkinUpdateOne) SetUser(u *User) *SkinUpdateOne {
return suo.SetUserID(u.ID)
}
// Mutation returns the SkinMutation object of the builder.
func (suo *SkinUpdateOne) Mutation() *SkinMutation {
return suo.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (suo *SkinUpdateOne) ClearUser() *SkinUpdateOne {
suo.mutation.ClearUser()
return suo
}
// Where appends a list predicates to the SkinUpdate builder.
func (suo *SkinUpdateOne) Where(ps ...predicate.Skin) *SkinUpdateOne {
suo.mutation.Where(ps...)
return suo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (suo *SkinUpdateOne) Select(field string, fields ...string) *SkinUpdateOne {
suo.fields = append([]string{field}, fields...)
return suo
}
// Save executes the query and returns the updated Skin entity.
func (suo *SkinUpdateOne) Save(ctx context.Context) (*Skin, error) {
return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (suo *SkinUpdateOne) SaveX(ctx context.Context) *Skin {
node, err := suo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (suo *SkinUpdateOne) Exec(ctx context.Context) error {
_, err := suo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (suo *SkinUpdateOne) ExecX(ctx context.Context) {
if err := suo.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (suo *SkinUpdateOne) check() error {
if _, ok := suo.mutation.UserID(); suo.mutation.UserCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Skin.user"`)
}
return nil
}
func (suo *SkinUpdateOne) sqlSave(ctx context.Context) (_node *Skin, err error) {
if err := suo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(skin.Table, skin.Columns, sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt))
id, ok := suo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Skin.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := suo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, skin.FieldID)
for _, f := range fields {
if !skin.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != skin.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := suo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := suo.mutation.SkinHash(); ok {
_spec.SetField(skin.FieldSkinHash, field.TypeString, value)
}
if value, ok := suo.mutation.GetType(); ok {
_spec.SetField(skin.FieldType, field.TypeUint8, value)
}
if value, ok := suo.mutation.AddedType(); ok {
_spec.AddField(skin.FieldType, field.TypeUint8, value)
}
if value, ok := suo.mutation.Variant(); ok {
_spec.SetField(skin.FieldVariant, field.TypeString, value)
}
if suo.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: skin.UserTable,
Columns: []string{skin.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := suo.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: skin.UserTable,
Columns: []string{skin.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Skin{config: suo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{skin.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
suo.mutation.done = true
return _node, nil
}

216
db/ent/tx.go Normal file
View File

@ -0,0 +1,216 @@
// 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
// Skin is the client for interacting with the Skin builders.
Skin *SkinClient
// User is the client for interacting with the User builders.
User *UserClient
// UserProfile is the client for interacting with the UserProfile builders.
UserProfile *UserProfileClient
// 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.Skin = NewSkinClient(tx.config)
tx.User = NewUserClient(tx.config)
tx.UserProfile = NewUserProfileClient(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: Skin.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)

194
db/ent/user.go Normal file
View File

@ -0,0 +1,194 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// User is the model entity for the User schema.
type User struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Email holds the value of the "email" field.
Email string `json:"email,omitempty"`
// Password holds the value of the "password" field.
Password string `json:"password,omitempty"`
// Salt holds the value of the "salt" field.
Salt string `json:"salt,omitempty"`
// State holds the value of the "state" field.
State int `json:"state,omitempty"`
// RegTime holds the value of the "reg_time" field.
RegTime int64 `json:"reg_time,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// Skin holds the value of the skin edge.
Skin []*Skin `json:"skin,omitempty"`
// Profile holds the value of the profile edge.
Profile *UserProfile `json:"profile,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// SkinOrErr returns the Skin value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) SkinOrErr() ([]*Skin, error) {
if e.loadedTypes[0] {
return e.Skin, nil
}
return nil, &NotLoadedError{edge: "skin"}
}
// ProfileOrErr returns the Profile value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserEdges) ProfileOrErr() (*UserProfile, error) {
if e.loadedTypes[1] {
if e.Profile == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: userprofile.Label}
}
return e.Profile, nil
}
return nil, &NotLoadedError{edge: "profile"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldID, user.FieldState, user.FieldRegTime:
values[i] = new(sql.NullInt64)
case user.FieldEmail, user.FieldPassword, user.FieldSalt:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the 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:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
u.ID = int(value.Int64)
case user.FieldEmail:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field email", values[i])
} else if value.Valid {
u.Email = 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.FieldSalt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field salt", values[i])
} else if value.Valid {
u.Salt = value.String
}
case user.FieldState:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field state", values[i])
} else if value.Valid {
u.State = int(value.Int64)
}
case user.FieldRegTime:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field reg_time", values[i])
} else if value.Valid {
u.RegTime = value.Int64
}
default:
u.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the User.
// This includes values selected through modifiers, order, etc.
func (u *User) Value(name string) (ent.Value, error) {
return u.selectValues.Get(name)
}
// QuerySkin queries the "skin" edge of the User entity.
func (u *User) QuerySkin() *SkinQuery {
return NewUserClient(u.config).QuerySkin(u)
}
// QueryProfile queries the "profile" edge of the User entity.
func (u *User) QueryProfile() *UserProfileQuery {
return NewUserClient(u.config).QueryProfile(u)
}
// 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("email=")
builder.WriteString(u.Email)
builder.WriteString(", ")
builder.WriteString("password=")
builder.WriteString(u.Password)
builder.WriteString(", ")
builder.WriteString("salt=")
builder.WriteString(u.Salt)
builder.WriteString(", ")
builder.WriteString("state=")
builder.WriteString(fmt.Sprintf("%v", u.State))
builder.WriteString(", ")
builder.WriteString("reg_time=")
builder.WriteString(fmt.Sprintf("%v", u.RegTime))
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

133
db/ent/user/user.go Normal file
View File

@ -0,0 +1,133 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldEmail holds the string denoting the email field in the database.
FieldEmail = "email"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// FieldSalt holds the string denoting the salt field in the database.
FieldSalt = "salt"
// FieldState holds the string denoting the state field in the database.
FieldState = "state"
// FieldRegTime holds the string denoting the reg_time field in the database.
FieldRegTime = "reg_time"
// EdgeSkin holds the string denoting the skin edge name in mutations.
EdgeSkin = "skin"
// EdgeProfile holds the string denoting the profile edge name in mutations.
EdgeProfile = "profile"
// Table holds the table name of the user in the database.
Table = "users"
// SkinTable is the table that holds the skin relation/edge.
SkinTable = "skins"
// SkinInverseTable is the table name for the Skin entity.
// It exists in this package in order to avoid circular dependency with the "skin" package.
SkinInverseTable = "skins"
// SkinColumn is the table column denoting the skin relation/edge.
SkinColumn = "skin_user"
// ProfileTable is the table that holds the profile relation/edge.
ProfileTable = "user_profiles"
// ProfileInverseTable is the table name for the UserProfile entity.
// It exists in this package in order to avoid circular dependency with the "userprofile" package.
ProfileInverseTable = "user_profiles"
// ProfileColumn is the table column denoting the profile relation/edge.
ProfileColumn = "user_profile"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldEmail,
FieldPassword,
FieldSalt,
FieldState,
FieldRegTime,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// OrderOption defines the ordering options for the User queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByEmail orders the results by the email field.
func ByEmail(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEmail, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// BySalt orders the results by the salt field.
func BySalt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSalt, opts...).ToFunc()
}
// ByState orders the results by the state field.
func ByState(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldState, opts...).ToFunc()
}
// ByRegTime orders the results by the reg_time field.
func ByRegTime(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRegTime, opts...).ToFunc()
}
// BySkinCount orders the results by skin count.
func BySkinCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newSkinStep(), opts...)
}
}
// BySkin orders the results by skin terms.
func BySkin(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newSkinStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByProfileField orders the results by profile field.
func ByProfileField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newProfileStep(), sql.OrderByField(field, opts...))
}
}
func newSkinStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(SkinInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, SkinTable, SkinColumn),
)
}
func newProfileStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ProfileInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, ProfileTable, ProfileColumn),
)
}

432
db/ent/user/where.go Normal file
View File

@ -0,0 +1,432 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
func Email(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldEmail, v))
}
// 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))
}
// Salt applies equality check predicate on the "salt" field. It's identical to SaltEQ.
func Salt(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldSalt, v))
}
// State applies equality check predicate on the "state" field. It's identical to StateEQ.
func State(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldState, v))
}
// RegTime applies equality check predicate on the "reg_time" field. It's identical to RegTimeEQ.
func RegTime(v int64) predicate.User {
return predicate.User(sql.FieldEQ(FieldRegTime, v))
}
// EmailEQ applies the EQ predicate on the "email" field.
func EmailEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldEmail, v))
}
// EmailNEQ applies the NEQ predicate on the "email" field.
func EmailNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldEmail, v))
}
// EmailIn applies the In predicate on the "email" field.
func EmailIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldEmail, vs...))
}
// EmailNotIn applies the NotIn predicate on the "email" field.
func EmailNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldEmail, vs...))
}
// EmailGT applies the GT predicate on the "email" field.
func EmailGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldEmail, v))
}
// EmailGTE applies the GTE predicate on the "email" field.
func EmailGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldEmail, v))
}
// EmailLT applies the LT predicate on the "email" field.
func EmailLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldEmail, v))
}
// EmailLTE applies the LTE predicate on the "email" field.
func EmailLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldEmail, v))
}
// EmailContains applies the Contains predicate on the "email" field.
func EmailContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldEmail, v))
}
// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
func EmailHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldEmail, v))
}
// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
func EmailHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldEmail, v))
}
// EmailEqualFold applies the EqualFold predicate on the "email" field.
func EmailEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldEmail, v))
}
// EmailContainsFold applies the ContainsFold predicate on the "email" field.
func EmailContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldEmail, v))
}
// 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))
}
// SaltEQ applies the EQ predicate on the "salt" field.
func SaltEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldSalt, v))
}
// SaltNEQ applies the NEQ predicate on the "salt" field.
func SaltNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldSalt, v))
}
// SaltIn applies the In predicate on the "salt" field.
func SaltIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldSalt, vs...))
}
// SaltNotIn applies the NotIn predicate on the "salt" field.
func SaltNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldSalt, vs...))
}
// SaltGT applies the GT predicate on the "salt" field.
func SaltGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldSalt, v))
}
// SaltGTE applies the GTE predicate on the "salt" field.
func SaltGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldSalt, v))
}
// SaltLT applies the LT predicate on the "salt" field.
func SaltLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldSalt, v))
}
// SaltLTE applies the LTE predicate on the "salt" field.
func SaltLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldSalt, v))
}
// SaltContains applies the Contains predicate on the "salt" field.
func SaltContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldSalt, v))
}
// SaltHasPrefix applies the HasPrefix predicate on the "salt" field.
func SaltHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldSalt, v))
}
// SaltHasSuffix applies the HasSuffix predicate on the "salt" field.
func SaltHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldSalt, v))
}
// SaltEqualFold applies the EqualFold predicate on the "salt" field.
func SaltEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldSalt, v))
}
// SaltContainsFold applies the ContainsFold predicate on the "salt" field.
func SaltContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldSalt, v))
}
// StateEQ applies the EQ predicate on the "state" field.
func StateEQ(v int) predicate.User {
return predicate.User(sql.FieldEQ(FieldState, v))
}
// StateNEQ applies the NEQ predicate on the "state" field.
func StateNEQ(v int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldState, v))
}
// StateIn applies the In predicate on the "state" field.
func StateIn(vs ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldState, vs...))
}
// StateNotIn applies the NotIn predicate on the "state" field.
func StateNotIn(vs ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldState, vs...))
}
// StateGT applies the GT predicate on the "state" field.
func StateGT(v int) predicate.User {
return predicate.User(sql.FieldGT(FieldState, v))
}
// StateGTE applies the GTE predicate on the "state" field.
func StateGTE(v int) predicate.User {
return predicate.User(sql.FieldGTE(FieldState, v))
}
// StateLT applies the LT predicate on the "state" field.
func StateLT(v int) predicate.User {
return predicate.User(sql.FieldLT(FieldState, v))
}
// StateLTE applies the LTE predicate on the "state" field.
func StateLTE(v int) predicate.User {
return predicate.User(sql.FieldLTE(FieldState, v))
}
// RegTimeEQ applies the EQ predicate on the "reg_time" field.
func RegTimeEQ(v int64) predicate.User {
return predicate.User(sql.FieldEQ(FieldRegTime, v))
}
// RegTimeNEQ applies the NEQ predicate on the "reg_time" field.
func RegTimeNEQ(v int64) predicate.User {
return predicate.User(sql.FieldNEQ(FieldRegTime, v))
}
// RegTimeIn applies the In predicate on the "reg_time" field.
func RegTimeIn(vs ...int64) predicate.User {
return predicate.User(sql.FieldIn(FieldRegTime, vs...))
}
// RegTimeNotIn applies the NotIn predicate on the "reg_time" field.
func RegTimeNotIn(vs ...int64) predicate.User {
return predicate.User(sql.FieldNotIn(FieldRegTime, vs...))
}
// RegTimeGT applies the GT predicate on the "reg_time" field.
func RegTimeGT(v int64) predicate.User {
return predicate.User(sql.FieldGT(FieldRegTime, v))
}
// RegTimeGTE applies the GTE predicate on the "reg_time" field.
func RegTimeGTE(v int64) predicate.User {
return predicate.User(sql.FieldGTE(FieldRegTime, v))
}
// RegTimeLT applies the LT predicate on the "reg_time" field.
func RegTimeLT(v int64) predicate.User {
return predicate.User(sql.FieldLT(FieldRegTime, v))
}
// RegTimeLTE applies the LTE predicate on the "reg_time" field.
func RegTimeLTE(v int64) predicate.User {
return predicate.User(sql.FieldLTE(FieldRegTime, v))
}
// HasSkin applies the HasEdge predicate on the "skin" edge.
func HasSkin() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, SkinTable, SkinColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasSkinWith applies the HasEdge predicate on the "skin" edge with a given conditions (other predicates).
func HasSkinWith(preds ...predicate.Skin) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newSkinStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasProfile applies the HasEdge predicate on the "profile" edge.
func HasProfile() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, ProfileTable, ProfileColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasProfileWith applies the HasEdge predicate on the "profile" edge with a given conditions (other predicates).
func HasProfileWith(preds ...predicate.UserProfile) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newProfileStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(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())
})
}

299
db/ent/user_create.go Normal file
View File

@ -0,0 +1,299 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetEmail sets the "email" field.
func (uc *UserCreate) SetEmail(s string) *UserCreate {
uc.mutation.SetEmail(s)
return uc
}
// SetPassword sets the "password" field.
func (uc *UserCreate) SetPassword(s string) *UserCreate {
uc.mutation.SetPassword(s)
return uc
}
// SetSalt sets the "salt" field.
func (uc *UserCreate) SetSalt(s string) *UserCreate {
uc.mutation.SetSalt(s)
return uc
}
// SetState sets the "state" field.
func (uc *UserCreate) SetState(i int) *UserCreate {
uc.mutation.SetState(i)
return uc
}
// SetRegTime sets the "reg_time" field.
func (uc *UserCreate) SetRegTime(i int64) *UserCreate {
uc.mutation.SetRegTime(i)
return uc
}
// AddSkinIDs adds the "skin" edge to the Skin entity by IDs.
func (uc *UserCreate) AddSkinIDs(ids ...int) *UserCreate {
uc.mutation.AddSkinIDs(ids...)
return uc
}
// AddSkin adds the "skin" edges to the Skin entity.
func (uc *UserCreate) AddSkin(s ...*Skin) *UserCreate {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return uc.AddSkinIDs(ids...)
}
// SetProfileID sets the "profile" edge to the UserProfile entity by ID.
func (uc *UserCreate) SetProfileID(id int) *UserCreate {
uc.mutation.SetProfileID(id)
return uc
}
// SetNillableProfileID sets the "profile" edge to the UserProfile entity by ID if the given value is not nil.
func (uc *UserCreate) SetNillableProfileID(id *int) *UserCreate {
if id != nil {
uc = uc.SetProfileID(*id)
}
return uc
}
// SetProfile sets the "profile" edge to the UserProfile entity.
func (uc *UserCreate) SetProfile(u *UserProfile) *UserCreate {
return uc.SetProfileID(u.ID)
}
// 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) {
return withHooks(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)
}
}
// check runs all checks and user-defined validators on the builder.
func (uc *UserCreate) check() error {
if _, ok := uc.mutation.Email(); !ok {
return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "User.email"`)}
}
if _, ok := uc.mutation.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "User.password"`)}
}
if _, ok := uc.mutation.Salt(); !ok {
return &ValidationError{Name: "salt", err: errors.New(`ent: missing required field "User.salt"`)}
}
if _, ok := uc.mutation.State(); !ok {
return &ValidationError{Name: "state", err: errors.New(`ent: missing required field "User.state"`)}
}
if _, ok := uc.mutation.RegTime(); !ok {
return &ValidationError{Name: "reg_time", err: errors.New(`ent: missing required field "User.reg_time"`)}
}
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
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
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.TypeInt))
)
if value, ok := uc.mutation.Email(); ok {
_spec.SetField(user.FieldEmail, field.TypeString, value)
_node.Email = value
}
if value, ok := uc.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
_node.Password = value
}
if value, ok := uc.mutation.Salt(); ok {
_spec.SetField(user.FieldSalt, field.TypeString, value)
_node.Salt = value
}
if value, ok := uc.mutation.State(); ok {
_spec.SetField(user.FieldState, field.TypeInt, value)
_node.State = value
}
if value, ok := uc.mutation.RegTime(); ok {
_spec.SetField(user.FieldRegTime, field.TypeInt64, value)
_node.RegTime = value
}
if nodes := uc.mutation.SkinIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := uc.mutation.ProfileIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: user.ProfileTable,
Columns: []string{user.ProfileColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
config
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]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, 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
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, 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
db/ent/user_delete.go Normal file
View 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"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/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(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.TypeInt))
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)
}
}

714
db/ent/user_query.go Normal file
View File

@ -0,0 +1,714 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
ctx *QueryContext
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
withSkin *SkinQuery
withProfile *UserProfileQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the 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 ...user.OrderOption) *UserQuery {
uq.order = append(uq.order, o...)
return uq
}
// QuerySkin chains the current query on the "skin" edge.
func (uq *UserQuery) QuerySkin() *SkinQuery {
query := (&SkinClient{config: uq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := uq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := uq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(skin.Table, skin.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, user.SkinTable, user.SkinColumn),
)
fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryProfile chains the current query on the "profile" edge.
func (uq *UserQuery) QueryProfile() *UserProfileQuery {
query := (&UserProfileClient{config: uq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := uq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := uq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(userprofile.Table, userprofile.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, user.ProfileTable, user.ProfileColumn),
)
fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first User entity from the query.
// Returns a *NotFoundError when no User was found.
func (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 int, err error) {
var ids []int
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) int {
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 int, err error) {
var ids []int
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) int {
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 []int, 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) []int {
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([]user.OrderOption{}, uq.order...),
inters: append([]Interceptor{}, uq.inters...),
predicates: append([]predicate.User{}, uq.predicates...),
withSkin: uq.withSkin.Clone(),
withProfile: uq.withProfile.Clone(),
// clone intermediate query.
sql: uq.sql.Clone(),
path: uq.path,
}
}
// WithSkin tells the query-builder to eager-load the nodes that are connected to
// the "skin" edge. The optional arguments are used to configure the query builder of the edge.
func (uq *UserQuery) WithSkin(opts ...func(*SkinQuery)) *UserQuery {
query := (&SkinClient{config: uq.config}).Query()
for _, opt := range opts {
opt(query)
}
uq.withSkin = query
return uq
}
// WithProfile tells the query-builder to eager-load the nodes that are connected to
// the "profile" edge. The optional arguments are used to configure the query builder of the edge.
func (uq *UserQuery) WithProfile(opts ...func(*UserProfileQuery)) *UserQuery {
query := (&UserProfileClient{config: uq.config}).Query()
for _, opt := range opts {
opt(query)
}
uq.withProfile = query
return uq
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Email string `json:"email,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldEmail).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (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 {
// Email string `json:"email,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldEmail).
// 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()
loadedTypes = [2]bool{
uq.withSkin != nil,
uq.withProfile != nil,
}
)
_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)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
if len(uq.modifiers) > 0 {
_spec.Modifiers = uq.modifiers
}
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
}
if query := uq.withSkin; query != nil {
if err := uq.loadSkin(ctx, query, nodes,
func(n *User) { n.Edges.Skin = []*Skin{} },
func(n *User, e *Skin) { n.Edges.Skin = append(n.Edges.Skin, e) }); err != nil {
return nil, err
}
}
if query := uq.withProfile; query != nil {
if err := uq.loadProfile(ctx, query, nodes, nil,
func(n *User, e *UserProfile) { n.Edges.Profile = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (uq *UserQuery) loadSkin(ctx context.Context, query *SkinQuery, nodes []*User, init func(*User), assign func(*User, *Skin)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Skin(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.SkinColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.skin_user
if fk == nil {
return fmt.Errorf(`foreign-key "skin_user" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "skin_user" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (uq *UserQuery) loadProfile(ctx context.Context, query *UserProfileQuery, nodes []*User, init func(*User), assign func(*User, *UserProfile)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
}
query.withFKs = true
query.Where(predicate.UserProfile(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.ProfileColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_profile
if fk == nil {
return fmt.Errorf(`foreign-key "user_profile" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_profile" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := uq.querySpec()
if len(uq.modifiers) > 0 {
_spec.Modifiers = uq.modifiers
}
_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.TypeInt))
_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 _, m := range uq.modifiers {
m(selector)
}
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
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (uq *UserQuery) ForUpdate(opts ...sql.LockOption) *UserQuery {
if uq.driver.Dialect() == dialect.Postgres {
uq.Unique(false)
}
uq.modifiers = append(uq.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return uq
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (uq *UserQuery) ForShare(opts ...sql.LockOption) *UserQuery {
if uq.driver.Dialect() == dialect.Postgres {
uq.Unique(false)
}
uq.modifiers = append(uq.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return uq
}
// 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)
}

577
db/ent/user_update.go Normal file
View File

@ -0,0 +1,577 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/skin"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// 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
}
// SetEmail sets the "email" field.
func (uu *UserUpdate) SetEmail(s string) *UserUpdate {
uu.mutation.SetEmail(s)
return uu
}
// SetPassword sets the "password" field.
func (uu *UserUpdate) SetPassword(s string) *UserUpdate {
uu.mutation.SetPassword(s)
return uu
}
// SetSalt sets the "salt" field.
func (uu *UserUpdate) SetSalt(s string) *UserUpdate {
uu.mutation.SetSalt(s)
return uu
}
// SetState sets the "state" field.
func (uu *UserUpdate) SetState(i int) *UserUpdate {
uu.mutation.ResetState()
uu.mutation.SetState(i)
return uu
}
// AddState adds i to the "state" field.
func (uu *UserUpdate) AddState(i int) *UserUpdate {
uu.mutation.AddState(i)
return uu
}
// SetRegTime sets the "reg_time" field.
func (uu *UserUpdate) SetRegTime(i int64) *UserUpdate {
uu.mutation.ResetRegTime()
uu.mutation.SetRegTime(i)
return uu
}
// AddRegTime adds i to the "reg_time" field.
func (uu *UserUpdate) AddRegTime(i int64) *UserUpdate {
uu.mutation.AddRegTime(i)
return uu
}
// AddSkinIDs adds the "skin" edge to the Skin entity by IDs.
func (uu *UserUpdate) AddSkinIDs(ids ...int) *UserUpdate {
uu.mutation.AddSkinIDs(ids...)
return uu
}
// AddSkin adds the "skin" edges to the Skin entity.
func (uu *UserUpdate) AddSkin(s ...*Skin) *UserUpdate {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return uu.AddSkinIDs(ids...)
}
// SetProfileID sets the "profile" edge to the UserProfile entity by ID.
func (uu *UserUpdate) SetProfileID(id int) *UserUpdate {
uu.mutation.SetProfileID(id)
return uu
}
// SetNillableProfileID sets the "profile" edge to the UserProfile entity by ID if the given value is not nil.
func (uu *UserUpdate) SetNillableProfileID(id *int) *UserUpdate {
if id != nil {
uu = uu.SetProfileID(*id)
}
return uu
}
// SetProfile sets the "profile" edge to the UserProfile entity.
func (uu *UserUpdate) SetProfile(u *UserProfile) *UserUpdate {
return uu.SetProfileID(u.ID)
}
// Mutation returns the UserMutation object of the builder.
func (uu *UserUpdate) Mutation() *UserMutation {
return uu.mutation
}
// ClearSkin clears all "skin" edges to the Skin entity.
func (uu *UserUpdate) ClearSkin() *UserUpdate {
uu.mutation.ClearSkin()
return uu
}
// RemoveSkinIDs removes the "skin" edge to Skin entities by IDs.
func (uu *UserUpdate) RemoveSkinIDs(ids ...int) *UserUpdate {
uu.mutation.RemoveSkinIDs(ids...)
return uu
}
// RemoveSkin removes "skin" edges to Skin entities.
func (uu *UserUpdate) RemoveSkin(s ...*Skin) *UserUpdate {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return uu.RemoveSkinIDs(ids...)
}
// ClearProfile clears the "profile" edge to the UserProfile entity.
func (uu *UserUpdate) ClearProfile() *UserUpdate {
uu.mutation.ClearProfile()
return uu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
return withHooks(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)
}
}
func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
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.Email(); ok {
_spec.SetField(user.FieldEmail, field.TypeString, value)
}
if value, ok := uu.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
}
if value, ok := uu.mutation.Salt(); ok {
_spec.SetField(user.FieldSalt, field.TypeString, value)
}
if value, ok := uu.mutation.State(); ok {
_spec.SetField(user.FieldState, field.TypeInt, value)
}
if value, ok := uu.mutation.AddedState(); ok {
_spec.AddField(user.FieldState, field.TypeInt, value)
}
if value, ok := uu.mutation.RegTime(); ok {
_spec.SetField(user.FieldRegTime, field.TypeInt64, value)
}
if value, ok := uu.mutation.AddedRegTime(); ok {
_spec.AddField(user.FieldRegTime, field.TypeInt64, value)
}
if uu.mutation.SkinCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uu.mutation.RemovedSkinIDs(); len(nodes) > 0 && !uu.mutation.SkinCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uu.mutation.SkinIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if uu.mutation.ProfileCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: user.ProfileTable,
Columns: []string{user.ProfileColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uu.mutation.ProfileIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: user.ProfileTable,
Columns: []string{user.ProfileColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, 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
}
// SetEmail sets the "email" field.
func (uuo *UserUpdateOne) SetEmail(s string) *UserUpdateOne {
uuo.mutation.SetEmail(s)
return uuo
}
// SetPassword sets the "password" field.
func (uuo *UserUpdateOne) SetPassword(s string) *UserUpdateOne {
uuo.mutation.SetPassword(s)
return uuo
}
// SetSalt sets the "salt" field.
func (uuo *UserUpdateOne) SetSalt(s string) *UserUpdateOne {
uuo.mutation.SetSalt(s)
return uuo
}
// SetState sets the "state" field.
func (uuo *UserUpdateOne) SetState(i int) *UserUpdateOne {
uuo.mutation.ResetState()
uuo.mutation.SetState(i)
return uuo
}
// AddState adds i to the "state" field.
func (uuo *UserUpdateOne) AddState(i int) *UserUpdateOne {
uuo.mutation.AddState(i)
return uuo
}
// SetRegTime sets the "reg_time" field.
func (uuo *UserUpdateOne) SetRegTime(i int64) *UserUpdateOne {
uuo.mutation.ResetRegTime()
uuo.mutation.SetRegTime(i)
return uuo
}
// AddRegTime adds i to the "reg_time" field.
func (uuo *UserUpdateOne) AddRegTime(i int64) *UserUpdateOne {
uuo.mutation.AddRegTime(i)
return uuo
}
// AddSkinIDs adds the "skin" edge to the Skin entity by IDs.
func (uuo *UserUpdateOne) AddSkinIDs(ids ...int) *UserUpdateOne {
uuo.mutation.AddSkinIDs(ids...)
return uuo
}
// AddSkin adds the "skin" edges to the Skin entity.
func (uuo *UserUpdateOne) AddSkin(s ...*Skin) *UserUpdateOne {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return uuo.AddSkinIDs(ids...)
}
// SetProfileID sets the "profile" edge to the UserProfile entity by ID.
func (uuo *UserUpdateOne) SetProfileID(id int) *UserUpdateOne {
uuo.mutation.SetProfileID(id)
return uuo
}
// SetNillableProfileID sets the "profile" edge to the UserProfile entity by ID if the given value is not nil.
func (uuo *UserUpdateOne) SetNillableProfileID(id *int) *UserUpdateOne {
if id != nil {
uuo = uuo.SetProfileID(*id)
}
return uuo
}
// SetProfile sets the "profile" edge to the UserProfile entity.
func (uuo *UserUpdateOne) SetProfile(u *UserProfile) *UserUpdateOne {
return uuo.SetProfileID(u.ID)
}
// Mutation returns the UserMutation object of the builder.
func (uuo *UserUpdateOne) Mutation() *UserMutation {
return uuo.mutation
}
// ClearSkin clears all "skin" edges to the Skin entity.
func (uuo *UserUpdateOne) ClearSkin() *UserUpdateOne {
uuo.mutation.ClearSkin()
return uuo
}
// RemoveSkinIDs removes the "skin" edge to Skin entities by IDs.
func (uuo *UserUpdateOne) RemoveSkinIDs(ids ...int) *UserUpdateOne {
uuo.mutation.RemoveSkinIDs(ids...)
return uuo
}
// RemoveSkin removes "skin" edges to Skin entities.
func (uuo *UserUpdateOne) RemoveSkin(s ...*Skin) *UserUpdateOne {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return uuo.RemoveSkinIDs(ids...)
}
// ClearProfile clears the "profile" edge to the UserProfile entity.
func (uuo *UserUpdateOne) ClearProfile() *UserUpdateOne {
uuo.mutation.ClearProfile()
return uuo
}
// 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) {
return withHooks(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)
}
}
func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
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.Email(); ok {
_spec.SetField(user.FieldEmail, field.TypeString, value)
}
if value, ok := uuo.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
}
if value, ok := uuo.mutation.Salt(); ok {
_spec.SetField(user.FieldSalt, field.TypeString, value)
}
if value, ok := uuo.mutation.State(); ok {
_spec.SetField(user.FieldState, field.TypeInt, value)
}
if value, ok := uuo.mutation.AddedState(); ok {
_spec.AddField(user.FieldState, field.TypeInt, value)
}
if value, ok := uuo.mutation.RegTime(); ok {
_spec.SetField(user.FieldRegTime, field.TypeInt64, value)
}
if value, ok := uuo.mutation.AddedRegTime(); ok {
_spec.AddField(user.FieldRegTime, field.TypeInt64, value)
}
if uuo.mutation.SkinCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uuo.mutation.RemovedSkinIDs(); len(nodes) > 0 && !uuo.mutation.SkinCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uuo.mutation.SkinIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: user.SkinTable,
Columns: []string{user.SkinColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(skin.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if uuo.mutation.ProfileCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: user.ProfileTable,
Columns: []string{user.ProfileColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uuo.mutation.ProfileIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: user.ProfileTable,
Columns: []string{user.ProfileColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &User{config: 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
}

155
db/ent/userprofile.go Normal file
View File

@ -0,0 +1,155 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserProfile is the model entity for the UserProfile schema.
type UserProfile struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// UUID holds the value of the "uuid" field.
UUID string `json:"uuid,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserProfileQuery when eager-loading is set.
Edges UserProfileEdges `json:"edges"`
user_profile *int
selectValues sql.SelectValues
}
// UserProfileEdges holds the relations/edges for other nodes in the graph.
type UserProfileEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserProfileEdges) UserOrErr() (*User, error) {
if e.loadedTypes[0] {
if e.User == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: user.Label}
}
return e.User, nil
}
return nil, &NotLoadedError{edge: "user"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*UserProfile) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case userprofile.FieldID:
values[i] = new(sql.NullInt64)
case userprofile.FieldName, userprofile.FieldUUID:
values[i] = new(sql.NullString)
case userprofile.ForeignKeys[0]: // user_profile
values[i] = new(sql.NullInt64)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the UserProfile fields.
func (up *UserProfile) 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 userprofile.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
up.ID = int(value.Int64)
case userprofile.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
up.Name = value.String
}
case userprofile.FieldUUID:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field uuid", values[i])
} else if value.Valid {
up.UUID = value.String
}
case userprofile.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_profile", value)
} else if value.Valid {
up.user_profile = new(int)
*up.user_profile = int(value.Int64)
}
default:
up.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the UserProfile.
// This includes values selected through modifiers, order, etc.
func (up *UserProfile) Value(name string) (ent.Value, error) {
return up.selectValues.Get(name)
}
// QueryUser queries the "user" edge of the UserProfile entity.
func (up *UserProfile) QueryUser() *UserQuery {
return NewUserProfileClient(up.config).QueryUser(up)
}
// Update returns a builder for updating this UserProfile.
// Note that you need to call UserProfile.Unwrap() before calling this method if this UserProfile
// was returned from a transaction, and the transaction was committed or rolled back.
func (up *UserProfile) Update() *UserProfileUpdateOne {
return NewUserProfileClient(up.config).UpdateOne(up)
}
// Unwrap unwraps the UserProfile 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 (up *UserProfile) Unwrap() *UserProfile {
_tx, ok := up.config.driver.(*txDriver)
if !ok {
panic("ent: UserProfile is not a transactional entity")
}
up.config.driver = _tx.drv
return up
}
// String implements the fmt.Stringer.
func (up *UserProfile) String() string {
var builder strings.Builder
builder.WriteString("UserProfile(")
builder.WriteString(fmt.Sprintf("id=%v, ", up.ID))
builder.WriteString("name=")
builder.WriteString(up.Name)
builder.WriteString(", ")
builder.WriteString("uuid=")
builder.WriteString(up.UUID)
builder.WriteByte(')')
return builder.String()
}
// UserProfiles is a parsable slice of UserProfile.
type UserProfiles []*UserProfile

View File

@ -0,0 +1,90 @@
// Code generated by ent, DO NOT EDIT.
package userprofile
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the userprofile type in the database.
Label = "user_profile"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldUUID holds the string denoting the uuid field in the database.
FieldUUID = "uuid"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// Table holds the table name of the userprofile in the database.
Table = "user_profiles"
// UserTable is the table that holds the user relation/edge.
UserTable = "user_profiles"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_profile"
)
// Columns holds all SQL columns for userprofile fields.
var Columns = []string{
FieldID,
FieldName,
FieldUUID,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "user_profiles"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_profile",
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
// OrderOption defines the ordering options for the UserProfile queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByUUID orders the results by the uuid field.
func ByUUID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUUID, opts...).ToFunc()
}
// ByUserField orders the results by user field.
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, UserTable, UserColumn),
)
}

249
db/ent/userprofile/where.go Normal file
View File

@ -0,0 +1,249 @@
// Code generated by ent, DO NOT EDIT.
package userprofile
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.UserProfile {
return predicate.UserProfile(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEQ(FieldName, v))
}
// UUID applies equality check predicate on the "uuid" field. It's identical to UUIDEQ.
func UUID(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEQ(FieldUUID, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldContainsFold(FieldName, v))
}
// UUIDEQ applies the EQ predicate on the "uuid" field.
func UUIDEQ(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEQ(FieldUUID, v))
}
// UUIDNEQ applies the NEQ predicate on the "uuid" field.
func UUIDNEQ(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldNEQ(FieldUUID, v))
}
// UUIDIn applies the In predicate on the "uuid" field.
func UUIDIn(vs ...string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldIn(FieldUUID, vs...))
}
// UUIDNotIn applies the NotIn predicate on the "uuid" field.
func UUIDNotIn(vs ...string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldNotIn(FieldUUID, vs...))
}
// UUIDGT applies the GT predicate on the "uuid" field.
func UUIDGT(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldGT(FieldUUID, v))
}
// UUIDGTE applies the GTE predicate on the "uuid" field.
func UUIDGTE(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldGTE(FieldUUID, v))
}
// UUIDLT applies the LT predicate on the "uuid" field.
func UUIDLT(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldLT(FieldUUID, v))
}
// UUIDLTE applies the LTE predicate on the "uuid" field.
func UUIDLTE(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldLTE(FieldUUID, v))
}
// UUIDContains applies the Contains predicate on the "uuid" field.
func UUIDContains(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldContains(FieldUUID, v))
}
// UUIDHasPrefix applies the HasPrefix predicate on the "uuid" field.
func UUIDHasPrefix(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldHasPrefix(FieldUUID, v))
}
// UUIDHasSuffix applies the HasSuffix predicate on the "uuid" field.
func UUIDHasSuffix(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldHasSuffix(FieldUUID, v))
}
// UUIDEqualFold applies the EqualFold predicate on the "uuid" field.
func UUIDEqualFold(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldEqualFold(FieldUUID, v))
}
// UUIDContainsFold applies the ContainsFold predicate on the "uuid" field.
func UUIDContainsFold(v string) predicate.UserProfile {
return predicate.UserProfile(sql.FieldContainsFold(FieldUUID, v))
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.UserProfile {
return predicate.UserProfile(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.UserProfile {
return predicate.UserProfile(func(s *sql.Selector) {
step := newUserStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.UserProfile) predicate.UserProfile {
return predicate.UserProfile(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.UserProfile) predicate.UserProfile {
return predicate.UserProfile(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.UserProfile) predicate.UserProfile {
return predicate.UserProfile(func(s *sql.Selector) {
p(s.Not())
})
}

View File

@ -0,0 +1,224 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserProfileCreate is the builder for creating a UserProfile entity.
type UserProfileCreate struct {
config
mutation *UserProfileMutation
hooks []Hook
}
// SetName sets the "name" field.
func (upc *UserProfileCreate) SetName(s string) *UserProfileCreate {
upc.mutation.SetName(s)
return upc
}
// SetUUID sets the "uuid" field.
func (upc *UserProfileCreate) SetUUID(s string) *UserProfileCreate {
upc.mutation.SetUUID(s)
return upc
}
// SetUserID sets the "user" edge to the User entity by ID.
func (upc *UserProfileCreate) SetUserID(id int) *UserProfileCreate {
upc.mutation.SetUserID(id)
return upc
}
// SetUser sets the "user" edge to the User entity.
func (upc *UserProfileCreate) SetUser(u *User) *UserProfileCreate {
return upc.SetUserID(u.ID)
}
// Mutation returns the UserProfileMutation object of the builder.
func (upc *UserProfileCreate) Mutation() *UserProfileMutation {
return upc.mutation
}
// Save creates the UserProfile in the database.
func (upc *UserProfileCreate) Save(ctx context.Context) (*UserProfile, error) {
return withHooks(ctx, upc.sqlSave, upc.mutation, upc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (upc *UserProfileCreate) SaveX(ctx context.Context) *UserProfile {
v, err := upc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (upc *UserProfileCreate) Exec(ctx context.Context) error {
_, err := upc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (upc *UserProfileCreate) ExecX(ctx context.Context) {
if err := upc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (upc *UserProfileCreate) check() error {
if _, ok := upc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "UserProfile.name"`)}
}
if _, ok := upc.mutation.UUID(); !ok {
return &ValidationError{Name: "uuid", err: errors.New(`ent: missing required field "UserProfile.uuid"`)}
}
if _, ok := upc.mutation.UserID(); !ok {
return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserProfile.user"`)}
}
return nil
}
func (upc *UserProfileCreate) sqlSave(ctx context.Context) (*UserProfile, error) {
if err := upc.check(); err != nil {
return nil, err
}
_node, _spec := upc.createSpec()
if err := sqlgraph.CreateNode(ctx, upc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
upc.mutation.id = &_node.ID
upc.mutation.done = true
return _node, nil
}
func (upc *UserProfileCreate) createSpec() (*UserProfile, *sqlgraph.CreateSpec) {
var (
_node = &UserProfile{config: upc.config}
_spec = sqlgraph.NewCreateSpec(userprofile.Table, sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt))
)
if value, ok := upc.mutation.Name(); ok {
_spec.SetField(userprofile.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := upc.mutation.UUID(); ok {
_spec.SetField(userprofile.FieldUUID, field.TypeString, value)
_node.UUID = value
}
if nodes := upc.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: true,
Table: userprofile.UserTable,
Columns: []string{userprofile.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_profile = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserProfileCreateBulk is the builder for creating many UserProfile entities in bulk.
type UserProfileCreateBulk struct {
config
builders []*UserProfileCreate
}
// Save creates the UserProfile entities in the database.
func (upcb *UserProfileCreateBulk) Save(ctx context.Context) ([]*UserProfile, error) {
specs := make([]*sqlgraph.CreateSpec, len(upcb.builders))
nodes := make([]*UserProfile, len(upcb.builders))
mutators := make([]Mutator, len(upcb.builders))
for i := range upcb.builders {
func(i int, root context.Context) {
builder := upcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserProfileMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, upcb.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, upcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, upcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (upcb *UserProfileCreateBulk) SaveX(ctx context.Context) []*UserProfile {
v, err := upcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (upcb *UserProfileCreateBulk) Exec(ctx context.Context) error {
_, err := upcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (upcb *UserProfileCreateBulk) ExecX(ctx context.Context) {
if err := upcb.Exec(ctx); err != nil {
panic(err)
}
}

View 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"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserProfileDelete is the builder for deleting a UserProfile entity.
type UserProfileDelete struct {
config
hooks []Hook
mutation *UserProfileMutation
}
// Where appends a list predicates to the UserProfileDelete builder.
func (upd *UserProfileDelete) Where(ps ...predicate.UserProfile) *UserProfileDelete {
upd.mutation.Where(ps...)
return upd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (upd *UserProfileDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, upd.sqlExec, upd.mutation, upd.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (upd *UserProfileDelete) ExecX(ctx context.Context) int {
n, err := upd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (upd *UserProfileDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(userprofile.Table, sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt))
if ps := upd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, upd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
upd.mutation.done = true
return affected, err
}
// UserProfileDeleteOne is the builder for deleting a single UserProfile entity.
type UserProfileDeleteOne struct {
upd *UserProfileDelete
}
// Where appends a list predicates to the UserProfileDelete builder.
func (updo *UserProfileDeleteOne) Where(ps ...predicate.UserProfile) *UserProfileDeleteOne {
updo.upd.mutation.Where(ps...)
return updo
}
// Exec executes the deletion query.
func (updo *UserProfileDeleteOne) Exec(ctx context.Context) error {
n, err := updo.upd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{userprofile.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (updo *UserProfileDeleteOne) ExecX(ctx context.Context) {
if err := updo.Exec(ctx); err != nil {
panic(err)
}
}

650
db/ent/userprofile_query.go Normal file
View File

@ -0,0 +1,650 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserProfileQuery is the builder for querying UserProfile entities.
type UserProfileQuery struct {
config
ctx *QueryContext
order []userprofile.OrderOption
inters []Interceptor
predicates []predicate.UserProfile
withUser *UserQuery
withFKs bool
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserProfileQuery builder.
func (upq *UserProfileQuery) Where(ps ...predicate.UserProfile) *UserProfileQuery {
upq.predicates = append(upq.predicates, ps...)
return upq
}
// Limit the number of records to be returned by this query.
func (upq *UserProfileQuery) Limit(limit int) *UserProfileQuery {
upq.ctx.Limit = &limit
return upq
}
// Offset to start from.
func (upq *UserProfileQuery) Offset(offset int) *UserProfileQuery {
upq.ctx.Offset = &offset
return upq
}
// 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 (upq *UserProfileQuery) Unique(unique bool) *UserProfileQuery {
upq.ctx.Unique = &unique
return upq
}
// Order specifies how the records should be ordered.
func (upq *UserProfileQuery) Order(o ...userprofile.OrderOption) *UserProfileQuery {
upq.order = append(upq.order, o...)
return upq
}
// QueryUser chains the current query on the "user" edge.
func (upq *UserProfileQuery) QueryUser() *UserQuery {
query := (&UserClient{config: upq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := upq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := upq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(userprofile.Table, userprofile.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, userprofile.UserTable, userprofile.UserColumn),
)
fromU = sqlgraph.SetNeighbors(upq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first UserProfile entity from the query.
// Returns a *NotFoundError when no UserProfile was found.
func (upq *UserProfileQuery) First(ctx context.Context) (*UserProfile, error) {
nodes, err := upq.Limit(1).All(setContextOp(ctx, upq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{userprofile.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (upq *UserProfileQuery) FirstX(ctx context.Context) *UserProfile {
node, err := upq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first UserProfile ID from the query.
// Returns a *NotFoundError when no UserProfile ID was found.
func (upq *UserProfileQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = upq.Limit(1).IDs(setContextOp(ctx, upq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{userprofile.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (upq *UserProfileQuery) FirstIDX(ctx context.Context) int {
id, err := upq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single UserProfile entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one UserProfile entity is found.
// Returns a *NotFoundError when no UserProfile entities are found.
func (upq *UserProfileQuery) Only(ctx context.Context) (*UserProfile, error) {
nodes, err := upq.Limit(2).All(setContextOp(ctx, upq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{userprofile.Label}
default:
return nil, &NotSingularError{userprofile.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (upq *UserProfileQuery) OnlyX(ctx context.Context) *UserProfile {
node, err := upq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only UserProfile ID in the query.
// Returns a *NotSingularError when more than one UserProfile ID is found.
// Returns a *NotFoundError when no entities are found.
func (upq *UserProfileQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = upq.Limit(2).IDs(setContextOp(ctx, upq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{userprofile.Label}
default:
err = &NotSingularError{userprofile.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (upq *UserProfileQuery) OnlyIDX(ctx context.Context) int {
id, err := upq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of UserProfiles.
func (upq *UserProfileQuery) All(ctx context.Context) ([]*UserProfile, error) {
ctx = setContextOp(ctx, upq.ctx, "All")
if err := upq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*UserProfile, *UserProfileQuery]()
return withInterceptors[[]*UserProfile](ctx, upq, qr, upq.inters)
}
// AllX is like All, but panics if an error occurs.
func (upq *UserProfileQuery) AllX(ctx context.Context) []*UserProfile {
nodes, err := upq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of UserProfile IDs.
func (upq *UserProfileQuery) IDs(ctx context.Context) (ids []int, err error) {
if upq.ctx.Unique == nil && upq.path != nil {
upq.Unique(true)
}
ctx = setContextOp(ctx, upq.ctx, "IDs")
if err = upq.Select(userprofile.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (upq *UserProfileQuery) IDsX(ctx context.Context) []int {
ids, err := upq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (upq *UserProfileQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, upq.ctx, "Count")
if err := upq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, upq, querierCount[*UserProfileQuery](), upq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (upq *UserProfileQuery) CountX(ctx context.Context) int {
count, err := upq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (upq *UserProfileQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, upq.ctx, "Exist")
switch _, err := upq.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 (upq *UserProfileQuery) ExistX(ctx context.Context) bool {
exist, err := upq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserProfileQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (upq *UserProfileQuery) Clone() *UserProfileQuery {
if upq == nil {
return nil
}
return &UserProfileQuery{
config: upq.config,
ctx: upq.ctx.Clone(),
order: append([]userprofile.OrderOption{}, upq.order...),
inters: append([]Interceptor{}, upq.inters...),
predicates: append([]predicate.UserProfile{}, upq.predicates...),
withUser: upq.withUser.Clone(),
// clone intermediate query.
sql: upq.sql.Clone(),
path: upq.path,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (upq *UserProfileQuery) WithUser(opts ...func(*UserQuery)) *UserProfileQuery {
query := (&UserClient{config: upq.config}).Query()
for _, opt := range opts {
opt(query)
}
upq.withUser = query
return upq
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.UserProfile.Query().
// GroupBy(userprofile.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (upq *UserProfileQuery) GroupBy(field string, fields ...string) *UserProfileGroupBy {
upq.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserProfileGroupBy{build: upq}
grbuild.flds = &upq.ctx.Fields
grbuild.label = userprofile.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// }
//
// client.UserProfile.Query().
// Select(userprofile.FieldName).
// Scan(ctx, &v)
func (upq *UserProfileQuery) Select(fields ...string) *UserProfileSelect {
upq.ctx.Fields = append(upq.ctx.Fields, fields...)
sbuild := &UserProfileSelect{UserProfileQuery: upq}
sbuild.label = userprofile.Label
sbuild.flds, sbuild.scan = &upq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserProfileSelect configured with the given aggregations.
func (upq *UserProfileQuery) Aggregate(fns ...AggregateFunc) *UserProfileSelect {
return upq.Select().Aggregate(fns...)
}
func (upq *UserProfileQuery) prepareQuery(ctx context.Context) error {
for _, inter := range upq.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, upq); err != nil {
return err
}
}
}
for _, f := range upq.ctx.Fields {
if !userprofile.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if upq.path != nil {
prev, err := upq.path(ctx)
if err != nil {
return err
}
upq.sql = prev
}
return nil
}
func (upq *UserProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserProfile, error) {
var (
nodes = []*UserProfile{}
withFKs = upq.withFKs
_spec = upq.querySpec()
loadedTypes = [1]bool{
upq.withUser != nil,
}
)
if upq.withUser != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, userprofile.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*UserProfile).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &UserProfile{config: upq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
if len(upq.modifiers) > 0 {
_spec.Modifiers = upq.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, upq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := upq.withUser; query != nil {
if err := upq.loadUser(ctx, query, nodes, nil,
func(n *UserProfile, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (upq *UserProfileQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserProfile, init func(*UserProfile), assign func(*UserProfile, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*UserProfile)
for i := range nodes {
if nodes[i].user_profile == nil {
continue
}
fk := *nodes[i].user_profile
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_profile" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (upq *UserProfileQuery) sqlCount(ctx context.Context) (int, error) {
_spec := upq.querySpec()
if len(upq.modifiers) > 0 {
_spec.Modifiers = upq.modifiers
}
_spec.Node.Columns = upq.ctx.Fields
if len(upq.ctx.Fields) > 0 {
_spec.Unique = upq.ctx.Unique != nil && *upq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, upq.driver, _spec)
}
func (upq *UserProfileQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(userprofile.Table, userprofile.Columns, sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt))
_spec.From = upq.sql
if unique := upq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if upq.path != nil {
_spec.Unique = true
}
if fields := upq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, userprofile.FieldID)
for i := range fields {
if fields[i] != userprofile.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := upq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := upq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := upq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := upq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (upq *UserProfileQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(upq.driver.Dialect())
t1 := builder.Table(userprofile.Table)
columns := upq.ctx.Fields
if len(columns) == 0 {
columns = userprofile.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if upq.sql != nil {
selector = upq.sql
selector.Select(selector.Columns(columns...)...)
}
if upq.ctx.Unique != nil && *upq.ctx.Unique {
selector.Distinct()
}
for _, m := range upq.modifiers {
m(selector)
}
for _, p := range upq.predicates {
p(selector)
}
for _, p := range upq.order {
p(selector)
}
if offset := upq.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 := upq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (upq *UserProfileQuery) ForUpdate(opts ...sql.LockOption) *UserProfileQuery {
if upq.driver.Dialect() == dialect.Postgres {
upq.Unique(false)
}
upq.modifiers = append(upq.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return upq
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (upq *UserProfileQuery) ForShare(opts ...sql.LockOption) *UserProfileQuery {
if upq.driver.Dialect() == dialect.Postgres {
upq.Unique(false)
}
upq.modifiers = append(upq.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return upq
}
// UserProfileGroupBy is the group-by builder for UserProfile entities.
type UserProfileGroupBy struct {
selector
build *UserProfileQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (upgb *UserProfileGroupBy) Aggregate(fns ...AggregateFunc) *UserProfileGroupBy {
upgb.fns = append(upgb.fns, fns...)
return upgb
}
// Scan applies the selector query and scans the result into the given value.
func (upgb *UserProfileGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, upgb.build.ctx, "GroupBy")
if err := upgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UserProfileQuery, *UserProfileGroupBy](ctx, upgb.build, upgb, upgb.build.inters, v)
}
func (upgb *UserProfileGroupBy) sqlScan(ctx context.Context, root *UserProfileQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(upgb.fns))
for _, fn := range upgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*upgb.flds)+len(upgb.fns))
for _, f := range *upgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*upgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := upgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// UserProfileSelect is the builder for selecting fields of UserProfile entities.
type UserProfileSelect struct {
*UserProfileQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (ups *UserProfileSelect) Aggregate(fns ...AggregateFunc) *UserProfileSelect {
ups.fns = append(ups.fns, fns...)
return ups
}
// Scan applies the selector query and scans the result into the given value.
func (ups *UserProfileSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ups.ctx, "Select")
if err := ups.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UserProfileQuery, *UserProfileSelect](ctx, ups.UserProfileQuery, ups, ups.inters, v)
}
func (ups *UserProfileSelect) sqlScan(ctx context.Context, root *UserProfileQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(ups.fns))
for _, fn := range ups.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*ups.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 := ups.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@ -0,0 +1,326 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/xmdhs/authlib-skin/db/ent/predicate"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/db/ent/userprofile"
)
// UserProfileUpdate is the builder for updating UserProfile entities.
type UserProfileUpdate struct {
config
hooks []Hook
mutation *UserProfileMutation
}
// Where appends a list predicates to the UserProfileUpdate builder.
func (upu *UserProfileUpdate) Where(ps ...predicate.UserProfile) *UserProfileUpdate {
upu.mutation.Where(ps...)
return upu
}
// SetName sets the "name" field.
func (upu *UserProfileUpdate) SetName(s string) *UserProfileUpdate {
upu.mutation.SetName(s)
return upu
}
// SetUUID sets the "uuid" field.
func (upu *UserProfileUpdate) SetUUID(s string) *UserProfileUpdate {
upu.mutation.SetUUID(s)
return upu
}
// SetUserID sets the "user" edge to the User entity by ID.
func (upu *UserProfileUpdate) SetUserID(id int) *UserProfileUpdate {
upu.mutation.SetUserID(id)
return upu
}
// SetUser sets the "user" edge to the User entity.
func (upu *UserProfileUpdate) SetUser(u *User) *UserProfileUpdate {
return upu.SetUserID(u.ID)
}
// Mutation returns the UserProfileMutation object of the builder.
func (upu *UserProfileUpdate) Mutation() *UserProfileMutation {
return upu.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (upu *UserProfileUpdate) ClearUser() *UserProfileUpdate {
upu.mutation.ClearUser()
return upu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (upu *UserProfileUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, upu.sqlSave, upu.mutation, upu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (upu *UserProfileUpdate) SaveX(ctx context.Context) int {
affected, err := upu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (upu *UserProfileUpdate) Exec(ctx context.Context) error {
_, err := upu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (upu *UserProfileUpdate) ExecX(ctx context.Context) {
if err := upu.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (upu *UserProfileUpdate) check() error {
if _, ok := upu.mutation.UserID(); upu.mutation.UserCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "UserProfile.user"`)
}
return nil
}
func (upu *UserProfileUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := upu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(userprofile.Table, userprofile.Columns, sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt))
if ps := upu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := upu.mutation.Name(); ok {
_spec.SetField(userprofile.FieldName, field.TypeString, value)
}
if value, ok := upu.mutation.UUID(); ok {
_spec.SetField(userprofile.FieldUUID, field.TypeString, value)
}
if upu.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: true,
Table: userprofile.UserTable,
Columns: []string{userprofile.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := upu.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: true,
Table: userprofile.UserTable,
Columns: []string{userprofile.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, upu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{userprofile.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
upu.mutation.done = true
return n, nil
}
// UserProfileUpdateOne is the builder for updating a single UserProfile entity.
type UserProfileUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserProfileMutation
}
// SetName sets the "name" field.
func (upuo *UserProfileUpdateOne) SetName(s string) *UserProfileUpdateOne {
upuo.mutation.SetName(s)
return upuo
}
// SetUUID sets the "uuid" field.
func (upuo *UserProfileUpdateOne) SetUUID(s string) *UserProfileUpdateOne {
upuo.mutation.SetUUID(s)
return upuo
}
// SetUserID sets the "user" edge to the User entity by ID.
func (upuo *UserProfileUpdateOne) SetUserID(id int) *UserProfileUpdateOne {
upuo.mutation.SetUserID(id)
return upuo
}
// SetUser sets the "user" edge to the User entity.
func (upuo *UserProfileUpdateOne) SetUser(u *User) *UserProfileUpdateOne {
return upuo.SetUserID(u.ID)
}
// Mutation returns the UserProfileMutation object of the builder.
func (upuo *UserProfileUpdateOne) Mutation() *UserProfileMutation {
return upuo.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (upuo *UserProfileUpdateOne) ClearUser() *UserProfileUpdateOne {
upuo.mutation.ClearUser()
return upuo
}
// Where appends a list predicates to the UserProfileUpdate builder.
func (upuo *UserProfileUpdateOne) Where(ps ...predicate.UserProfile) *UserProfileUpdateOne {
upuo.mutation.Where(ps...)
return upuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (upuo *UserProfileUpdateOne) Select(field string, fields ...string) *UserProfileUpdateOne {
upuo.fields = append([]string{field}, fields...)
return upuo
}
// Save executes the query and returns the updated UserProfile entity.
func (upuo *UserProfileUpdateOne) Save(ctx context.Context) (*UserProfile, error) {
return withHooks(ctx, upuo.sqlSave, upuo.mutation, upuo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (upuo *UserProfileUpdateOne) SaveX(ctx context.Context) *UserProfile {
node, err := upuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (upuo *UserProfileUpdateOne) Exec(ctx context.Context) error {
_, err := upuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (upuo *UserProfileUpdateOne) ExecX(ctx context.Context) {
if err := upuo.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (upuo *UserProfileUpdateOne) check() error {
if _, ok := upuo.mutation.UserID(); upuo.mutation.UserCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "UserProfile.user"`)
}
return nil
}
func (upuo *UserProfileUpdateOne) sqlSave(ctx context.Context) (_node *UserProfile, err error) {
if err := upuo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(userprofile.Table, userprofile.Columns, sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt))
id, ok := upuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserProfile.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := upuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, userprofile.FieldID)
for _, f := range fields {
if !userprofile.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != userprofile.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := upuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := upuo.mutation.Name(); ok {
_spec.SetField(userprofile.FieldName, field.TypeString, value)
}
if value, ok := upuo.mutation.UUID(); ok {
_spec.SetField(userprofile.FieldUUID, field.TypeString, value)
}
if upuo.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: true,
Table: userprofile.UserTable,
Columns: []string{userprofile.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := upuo.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: true,
Table: userprofile.UserTable,
Columns: []string{userprofile.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &UserProfile{config: upuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, upuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{userprofile.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
upuo.mutation.done = true
return _node, nil
}

View File

@ -1,146 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
package mysql
import (
"context"
"database/sql"
"fmt"
)
type DBTX interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
func Prepare(ctx context.Context, db DBTX) (*Queries, error) {
q := Queries{db: db}
var err error
if q.createUserStmt, err = db.PrepareContext(ctx, createUser); err != nil {
return nil, fmt.Errorf("error preparing query CreateUser: %w", err)
}
if q.createUserProfileStmt, err = db.PrepareContext(ctx, createUserProfile); err != nil {
return nil, fmt.Errorf("error preparing query CreateUserProfile: %w", err)
}
if q.deleteUserStmt, err = db.PrepareContext(ctx, deleteUser); err != nil {
return nil, fmt.Errorf("error preparing query DeleteUser: %w", err)
}
if q.getUserStmt, err = db.PrepareContext(ctx, getUser); err != nil {
return nil, fmt.Errorf("error preparing query GetUser: %w", err)
}
if q.getUserByEmailStmt, err = db.PrepareContext(ctx, getUserByEmail); err != nil {
return nil, fmt.Errorf("error preparing query GetUserByEmail: %w", err)
}
if q.getUserProfileByNameStmt, err = db.PrepareContext(ctx, getUserProfileByName); err != nil {
return nil, fmt.Errorf("error preparing query GetUserProfileByName: %w", err)
}
if q.listUserStmt, err = db.PrepareContext(ctx, listUser); err != nil {
return nil, fmt.Errorf("error preparing query ListUser: %w", err)
}
return &q, nil
}
func (q *Queries) Close() error {
var err error
if q.createUserStmt != nil {
if cerr := q.createUserStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing createUserStmt: %w", cerr)
}
}
if q.createUserProfileStmt != nil {
if cerr := q.createUserProfileStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing createUserProfileStmt: %w", cerr)
}
}
if q.deleteUserStmt != nil {
if cerr := q.deleteUserStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing deleteUserStmt: %w", cerr)
}
}
if q.getUserStmt != nil {
if cerr := q.getUserStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing getUserStmt: %w", cerr)
}
}
if q.getUserByEmailStmt != nil {
if cerr := q.getUserByEmailStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing getUserByEmailStmt: %w", cerr)
}
}
if q.getUserProfileByNameStmt != nil {
if cerr := q.getUserProfileByNameStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing getUserProfileByNameStmt: %w", cerr)
}
}
if q.listUserStmt != nil {
if cerr := q.listUserStmt.Close(); cerr != nil {
err = fmt.Errorf("error closing listUserStmt: %w", cerr)
}
}
return err
}
func (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {
switch {
case stmt != nil && q.tx != nil:
return q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)
case stmt != nil:
return stmt.ExecContext(ctx, args...)
default:
return q.db.ExecContext(ctx, query, args...)
}
}
func (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {
switch {
case stmt != nil && q.tx != nil:
return q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)
case stmt != nil:
return stmt.QueryContext(ctx, args...)
default:
return q.db.QueryContext(ctx, query, args...)
}
}
func (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {
switch {
case stmt != nil && q.tx != nil:
return q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)
case stmt != nil:
return stmt.QueryRowContext(ctx, args...)
default:
return q.db.QueryRowContext(ctx, query, args...)
}
}
type Queries struct {
db DBTX
tx *sql.Tx
createUserStmt *sql.Stmt
createUserProfileStmt *sql.Stmt
deleteUserStmt *sql.Stmt
getUserStmt *sql.Stmt
getUserByEmailStmt *sql.Stmt
getUserProfileByNameStmt *sql.Stmt
listUserStmt *sql.Stmt
}
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
return &Queries{
db: tx,
tx: tx,
createUserStmt: q.createUserStmt,
createUserProfileStmt: q.createUserProfileStmt,
deleteUserStmt: q.deleteUserStmt,
getUserStmt: q.getUserStmt,
getUserByEmailStmt: q.getUserByEmailStmt,
getUserProfileByNameStmt: q.getUserProfileByNameStmt,
listUserStmt: q.listUserStmt,
}
}

View File

@ -1,38 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
package mysql
import ()
type Skin struct {
ID int64 `db:"id"`
UserID int64 `db:"user_id"`
SkinHash string `db:"skin_hash"`
Type string `db:"type"`
Variant string `db:"variant"`
}
type User struct {
ID int64 `db:"id"`
Email string `db:"email"`
Password string `db:"password"`
Salt string `db:"salt"`
State int32 `db:"state"`
RegTime int64 `db:"reg_time"`
}
type UserProfile struct {
UserID int64 `db:"user_id"`
Name string `db:"name"`
Uuid string `db:"uuid"`
}
type UserSkin struct {
UserID int64 `db:"user_id"`
SkinID int64 `db:"skin_id"`
}
type UserToken struct {
UserID int64 `db:"user_id"`
TokenID int32 `db:"token_id"`
}

View File

@ -1,20 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
package mysql
import (
"context"
"database/sql"
)
type Querier interface {
CreateUser(ctx context.Context, arg CreateUserParams) (sql.Result, error)
CreateUserProfile(ctx context.Context, arg CreateUserProfileParams) (sql.Result, error)
DeleteUser(ctx context.Context, id int64) error
GetUser(ctx context.Context, id int64) (User, error)
GetUserByEmail(ctx context.Context, email string) (User, error)
GetUserProfileByName(ctx context.Context, name string) (UserProfile, error)
ListUser(ctx context.Context) ([]User, error)
}
var _ Querier = (*Queries)(nil)

View File

@ -1,150 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// source: query.sql
package mysql
import (
"context"
"database/sql"
)
const createUser = `-- name: CreateUser :execresult
REPLACE INTO user ( id, email, password, salt, state, reg_time ) VALUES (?, ?, ?, ?, ?, ?)
`
type CreateUserParams struct {
ID int64 `db:"id"`
Email string `db:"email"`
Password string `db:"password"`
Salt string `db:"salt"`
State int32 `db:"state"`
RegTime int64 `db:"reg_time"`
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (sql.Result, error) {
return q.exec(ctx, q.createUserStmt, createUser,
arg.ID,
arg.Email,
arg.Password,
arg.Salt,
arg.State,
arg.RegTime,
)
}
const createUserProfile = `-- name: CreateUserProfile :execresult
REPLACE INTO ` + "`" + `user_profile` + "`" + ` (` + "`" + `user_id` + "`" + `, ` + "`" + `name` + "`" + `, ` + "`" + `uuid` + "`" + `) VALUES (?, ?, ?)
`
type CreateUserProfileParams struct {
UserID int64 `db:"user_id"`
Name string `db:"name"`
Uuid string `db:"uuid"`
}
func (q *Queries) CreateUserProfile(ctx context.Context, arg CreateUserProfileParams) (sql.Result, error) {
return q.exec(ctx, q.createUserProfileStmt, createUserProfile, arg.UserID, arg.Name, arg.Uuid)
}
const deleteUser = `-- name: DeleteUser :exec
DELETE
FROM user
WHERE id = ?
`
func (q *Queries) DeleteUser(ctx context.Context, id int64) error {
_, err := q.exec(ctx, q.deleteUserStmt, deleteUser, id)
return err
}
const getUser = `-- name: GetUser :one
SELECT id, email, password, salt, state, reg_time
FROM user
WHERE id = ?
LIMIT 1
`
func (q *Queries) GetUser(ctx context.Context, id int64) (User, error) {
row := q.queryRow(ctx, q.getUserStmt, getUser, id)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.Password,
&i.Salt,
&i.State,
&i.RegTime,
)
return i, err
}
const getUserByEmail = `-- name: GetUserByEmail :one
SELECT id, email, password, salt, state, reg_time
FROM user
WHERE email = ?
LIMIT 1
`
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
row := q.queryRow(ctx, q.getUserByEmailStmt, getUserByEmail, email)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.Password,
&i.Salt,
&i.State,
&i.RegTime,
)
return i, err
}
const getUserProfileByName = `-- name: GetUserProfileByName :one
SELECT user_id, name, uuid
FROM ` + "`" + `user_profile` + "`" + `
WHERE ` + "`" + `name` + "`" + ` = ?
LIMIT 1
`
func (q *Queries) GetUserProfileByName(ctx context.Context, name string) (UserProfile, error) {
row := q.queryRow(ctx, q.getUserProfileByNameStmt, getUserProfileByName, name)
var i UserProfile
err := row.Scan(&i.UserID, &i.Name, &i.Uuid)
return i, err
}
const listUser = `-- name: ListUser :many
SELECT id, email, password, salt, state, reg_time
FROM user
ORDER BY reg_time
`
func (q *Queries) ListUser(ctx context.Context) ([]User, error) {
rows, err := q.query(ctx, q.listUserStmt, listUser)
if err != nil {
return nil, err
}
defer rows.Close()
var items []User
for rows.Next() {
var i User
if err := rows.Scan(
&i.ID,
&i.Email,
&i.Password,
&i.Salt,
&i.State,
&i.RegTime,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@ -1,27 +0,0 @@
-- name: GetUser :one
SELECT *
FROM user
WHERE id = ?
LIMIT 1;
-- name: ListUser :many
SELECT *
FROM user
ORDER BY reg_time;
-- name: CreateUser :execresult
REPLACE INTO user ( id, email, password, salt, state, reg_time ) VALUES (?, ?, ?, ?, ?, ?);
-- name: DeleteUser :exec
DELETE
FROM user
WHERE id = ?;
-- name: CreateUserProfile :execresult
REPLACE INTO `user_profile` (`user_id`, `name`, `uuid`) VALUES (?, ?, ?);
-- name: GetUserByEmail :one
SELECT *
FROM user
WHERE email = ?
LIMIT 1 for update;
-- name: GetUserProfileByName :one
SELECT *
FROM `user_profile`
WHERE `name` = ?
LIMIT 1 for update;

View File

@ -1,36 +0,0 @@
CREATE TABLE IF NOT EXISTS `user` (
id BIGINT PRIMARY KEY,
email VARCHAR(20) NOT NULL,
password text NOT NULL,
salt text NOT NULL,
-- 二进制状态位,暂无作用
state INT NOT NULL,
reg_time BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS `skin` (
id BIGINT PRIMARY KEY,
-- 第一个上传的用户
user_id BIGINT NOT NULL,
skin_hash VARCHAR(50) NOT NULL,
`type` VARCHAR(10) NOT NULL,
variant VARCHAR(10) NOT NULL
);
CREATE TABLE IF NOT EXISTS `user_skin` (
user_id BIGINT PRIMARY KEY,
skin_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS `user_token` (
user_id BIGINT PRIMARY KEY,
token_id INT NOT NULL
);
CREATE TABLE IF NOT EXISTS `user_profile` (
user_id BIGINT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
uuid text NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS name_index ON user_profile (name);

View File

@ -1,37 +0,0 @@
//go:generate sqlc generate
package mysql
import (
"context"
"database/sql"
"fmt"
)
type QuerierWithTx interface {
Querier
Tx(ctx context.Context, f func(Querier) error) error
}
var _ QuerierWithTx = (*Queries)(nil)
func (q *Queries) Tx(ctx context.Context, f func(Querier) error) error {
db, ok := q.db.(*sql.DB)
if !ok {
return fmt.Errorf("not *sql.DB")
}
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return err
}
defer tx.Rollback()
nq := q.WithTx(tx)
err = f(nq)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}

View File

@ -1,12 +0,0 @@
version: 2
sql:
- engine: "mysql"
schema: "sql/schema.sql"
queries: "sql/query.sql"
gen:
go:
package: "mysql"
out: "."
emit_db_tags: true
emit_prepared_queries: true
emit_interface: true

12
go.mod
View File

@ -3,6 +3,7 @@ module github.com/xmdhs/authlib-skin
go 1.21.0
require (
entgo.io/ent v0.12.3
github.com/bwmarrin/snowflake v0.3.0
github.com/go-playground/validator/v10 v10.15.3
github.com/go-sql-driver/mysql v1.7.1
@ -13,11 +14,20 @@ require (
)
require (
ariga.io/atlas v0.10.2-0.20230427182402-87a07dfb83bf // indirect
github.com/agext/levenshtein v1.2.1 // indirect
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/hashicorp/hcl/v2 v2.13.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
github.com/zclconf/go-cty v1.8.0 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.8.0 // indirect
)

67
go.sum
View File

@ -1,3 +1,13 @@
ariga.io/atlas v0.10.2-0.20230427182402-87a07dfb83bf h1:Tq2DRB39ZHScIwWACjPKLv5oEErv7zv6PBb5RTz5CKA=
ariga.io/atlas v0.10.2-0.20230427182402-87a07dfb83bf/go.mod h1:+TR129FJZ5Lvzms6dvCeGWh1yR6hMvmXBhug4hrNIGk=
entgo.io/ent v0.12.3 h1:N5lO2EOrHpCH5HYfiMOCHYbo+oh5M8GjT0/cx5x6xkk=
entgo.io/ent v0.12.3/go.mod h1:AigGGx+tbrBBYHAzGOg8ND661E5cxx1Uiu5o/otJ6Yg=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
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/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -5,6 +15,8 @@ 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/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
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-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@ -15,18 +27,51 @@ github.com/go-playground/validator/v10 v10.15.3 h1:S+sSpunYjNPDuXkWbK+x+bA7iXiW2
github.com/go-playground/validator/v10 v10.15.3/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
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/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/wire v0.5.0 h1:I7ELFeVBr3yfPIcc8+MWvrjk+3VjbcSzoXm3JVa+jD8=
github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU=
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/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
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/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
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/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
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/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@ -34,20 +79,38 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
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/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.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/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.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.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.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.8.1-0.20230428195545-5283a0178901 h1:0wxTF6pSjIIhNt7mo9GvjDfzyCOiWhmICgtO/Ah948s=
golang.org/x/tools v0.8.1-0.20230428195545-5283a0178901/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -9,13 +9,13 @@ import (
"github.com/go-playground/validator/v10"
"github.com/julienschmidt/httprouter"
"github.com/xmdhs/authlib-skin/config"
"github.com/xmdhs/authlib-skin/db/mysql"
"github.com/xmdhs/authlib-skin/db/ent"
"github.com/xmdhs/authlib-skin/model"
"github.com/xmdhs/authlib-skin/service"
"github.com/xmdhs/authlib-skin/utils"
)
func Reg(l *slog.Logger, q mysql.QuerierWithTx, v *validator.Validate, snow *snowflake.Node, c config.Config) httprouter.Handle {
func Reg(l *slog.Logger, client *ent.Client, v *validator.Validate, snow *snowflake.Node, c config.Config) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
@ -25,7 +25,7 @@ func Reg(l *slog.Logger, q mysql.QuerierWithTx, v *validator.Validate, snow *sno
handleError(ctx, w, err.Error(), model.ErrInput, 400)
return
}
err = service.Reg(ctx, u, q, snow, c)
err = service.Reg(ctx, u, snow, c, client)
if err != nil {
if errors.Is(err, service.ErrExistUser) {
l.DebugContext(ctx, err.Error())

View File

@ -7,12 +7,13 @@ import (
"log/slog"
"os"
entsql "entgo.io/ent/dialect/sql"
"github.com/bwmarrin/snowflake"
"github.com/go-playground/validator/v10"
_ "github.com/go-sql-driver/mysql"
"github.com/google/wire"
"github.com/xmdhs/authlib-skin/config"
"github.com/xmdhs/authlib-skin/db/mysql"
"github.com/xmdhs/authlib-skin/db/ent"
)
func ProvideSlog(c config.Config) slog.Handler {
@ -49,12 +50,18 @@ func ProvideDB(c config.Config) (*sql.DB, func(), error) {
return db, func() { db.Close() }, nil
}
func ProvideQuerier(ctx context.Context, db *sql.DB) (mysql.QuerierWithTx, func(), error) {
q, err := mysql.Prepare(ctx, db)
if err != nil {
return nil, nil, fmt.Errorf("newQuerier: %w", err)
func ProvideEnt(ctx context.Context, db *sql.DB, c config.Config, sl *slog.Logger) (*ent.Client, func()) {
drv := entsql.OpenDB("mysql", db)
opts := []ent.Option{ent.Driver(drv), ent.Log(
func(a ...any) {
sl.Debug(fmt.Sprint(a))
},
)}
if c.Debug {
opts = append(opts, ent.Debug())
}
return q, func() { q.Close() }, nil
e := ent.NewClient(opts...)
return e, func() { e.Close() }
}
func ProvideValidate() *validator.Validate {
@ -70,4 +77,4 @@ func ProvideSnowflake(c config.Config) (*snowflake.Node, error) {
return n, nil
}
var Set = wire.NewSet(ProvideSlog, ProvideDB, ProvideQuerier, ProvideValidate, ProvideSnowflake)
var Set = wire.NewSet(ProvideSlog, ProvideDB, ProvideEnt, ProvideValidate, ProvideSnowflake)

View File

@ -8,17 +8,17 @@ import (
"github.com/go-playground/validator/v10"
"github.com/julienschmidt/httprouter"
"github.com/xmdhs/authlib-skin/config"
"github.com/xmdhs/authlib-skin/db/mysql"
"github.com/xmdhs/authlib-skin/db/ent"
"github.com/xmdhs/authlib-skin/handle"
)
func NewRoute(l *slog.Logger, q mysql.QuerierWithTx, v *validator.Validate, snow *snowflake.Node, c config.Config) (*httprouter.Router, error) {
func NewRoute(l *slog.Logger, client *ent.Client, v *validator.Validate, snow *snowflake.Node, c config.Config) (*httprouter.Router, error) {
r := httprouter.New()
err := newYggdrasil(r)
if err != nil {
return nil, fmt.Errorf("NewRoute: %w", err)
}
err = newSkinApi(r, l, q, v, snow, c)
err = newSkinApi(r, l, client, v, snow, c)
if err != nil {
return nil, fmt.Errorf("NewRoute: %w", err)
}
@ -30,7 +30,7 @@ func newYggdrasil(r *httprouter.Router) error {
return nil
}
func newSkinApi(r *httprouter.Router, l *slog.Logger, q mysql.QuerierWithTx, v *validator.Validate, snow *snowflake.Node, c config.Config) error {
r.PUT("/api/v1/user/reg", handle.Reg(l, q, v, snow, c))
func newSkinApi(r *httprouter.Router, l *slog.Logger, client *ent.Client, v *validator.Validate, snow *snowflake.Node, c config.Config) error {
r.PUT("/api/v1/user/reg", handle.Reg(l, client, v, snow, c))
return nil
}

View File

@ -26,11 +26,7 @@ func InitializeRoute(ctx context.Context, c config.Config) (*http.Server, func()
if err != nil {
return nil, nil, err
}
querierWithTx, cleanup2, err := ProvideQuerier(ctx, db)
if err != nil {
cleanup()
return nil, nil, err
}
client, cleanup2 := ProvideEnt(ctx, db, c, logger)
validate := ProvideValidate()
node, err := ProvideSnowflake(c)
if err != nil {
@ -38,7 +34,7 @@ func InitializeRoute(ctx context.Context, c config.Config) (*http.Server, func()
cleanup()
return nil, nil, err
}
router, err := route.NewRoute(logger, querierWithTx, validate, node, c)
router, err := route.NewRoute(logger, client, validate, node, c)
if err != nil {
cleanup2()
cleanup()

View File

@ -13,7 +13,8 @@ import (
"github.com/bwmarrin/snowflake"
"github.com/google/uuid"
"github.com/xmdhs/authlib-skin/config"
"github.com/xmdhs/authlib-skin/db/mysql"
"github.com/xmdhs/authlib-skin/db/ent"
"github.com/xmdhs/authlib-skin/db/ent/user"
"github.com/xmdhs/authlib-skin/model"
"github.com/xmdhs/authlib-skin/utils"
)
@ -23,30 +24,33 @@ var (
ErrExitsName = errors.New("用户名已存在")
)
func Reg(ctx context.Context, u model.User, q mysql.QuerierWithTx, snow *snowflake.Node,
c config.Config,
func Reg(ctx context.Context, u model.User, snow *snowflake.Node,
c config.Config, e *ent.Client,
) error {
ou, err := q.GetUserByEmail(ctx, u.Email)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
tx, err := e.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return fmt.Errorf("Reg: %w", err)
}
if ou.Email != "" {
defer tx.Rollback()
count, err := tx.User.Query().Where(user.EmailEQ(u.Email)).ForUpdate().Count(ctx)
if err != nil {
return fmt.Errorf("Reg: %w", err)
}
if count != 0 {
return fmt.Errorf("Reg: %w", ErrExistUser)
}
err = q.Tx(ctx, func(q mysql.Querier) error {
p, s := utils.Argon2ID(u.Password)
userID := snow.Generate().Int64()
_, err := q.CreateUser(ctx, mysql.CreateUserParams{
ID: userID,
Email: u.Email,
Password: p,
Salt: s,
State: 0,
RegTime: time.Now().Unix(),
})
du, err := e.User.Create().
SetEmail(u.Email).
SetPassword(p).
SetSalt(s).
SetRegTime(time.Now().Unix()).
SetState(0).Save(ctx)
if err != nil {
return err
return fmt.Errorf("Reg: %w", err)
}
var userUuid string
if c.OfflineUUID {
userUuid = uuidGen(u.Name)
@ -54,20 +58,18 @@ func Reg(ctx context.Context, u model.User, q mysql.QuerierWithTx, snow *snowfla
userUuid = strings.ReplaceAll(uuid.New().String(), "-", "")
}
_, err = q.CreateUserProfile(ctx, mysql.CreateUserProfileParams{
UserID: userID,
Name: u.Name,
Uuid: userUuid,
})
if err != nil {
return err
}
return nil
})
_, err = e.UserProfile.Create().
SetUser(du).
SetName(u.Name).
SetUUID(userUuid).
Save(ctx)
if err != nil {
return fmt.Errorf("Reg: %w", err)
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("Reg: %w", err)
}
return nil
}

View File

@ -0,0 +1,11 @@
package yggdrasil
import (
"context"
"github.com/xmdhs/authlib-skin/db/ent"
)
func Authenticate(cxt context.Context, client *ent.Client) {
}