diff --git a/backend/consts/user.go b/backend/consts/user.go index 33b9618..03a8f89 100644 --- a/backend/consts/user.go +++ b/backend/consts/user.go @@ -11,3 +11,16 @@ const ( const ( SessionName = "monkeycode_session" ) + +type UserPlatform string + +const ( + UserPlatformEmail UserPlatform = "email" + UserPlatformDingTalk UserPlatform = "dingtalk" +) + +type OAuthKind string + +const ( + OAuthKindSignUpOrIn OAuthKind = "signup_or_in" +) diff --git a/backend/db/client.go b/backend/db/client.go index 6e3451e..49ca7d4 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -29,6 +29,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" stdsql "database/sql" @@ -65,6 +66,8 @@ type Client struct { TaskRecord *TaskRecordClient // User is the client for interacting with the User builders. User *UserClient + // UserIdentity is the client for interacting with the UserIdentity builders. + UserIdentity *UserIdentityClient // UserLoginHistory is the client for interacting with the UserLoginHistory builders. UserLoginHistory *UserLoginHistoryClient } @@ -91,6 +94,7 @@ func (c *Client) init() { c.Task = NewTaskClient(c.config) c.TaskRecord = NewTaskRecordClient(c.config) c.User = NewUserClient(c.config) + c.UserIdentity = NewUserIdentityClient(c.config) c.UserLoginHistory = NewUserLoginHistoryClient(c.config) } @@ -197,6 +201,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Task: NewTaskClient(cfg), TaskRecord: NewTaskRecordClient(cfg), User: NewUserClient(cfg), + UserIdentity: NewUserIdentityClient(cfg), UserLoginHistory: NewUserLoginHistoryClient(cfg), }, nil } @@ -230,6 +235,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Task: NewTaskClient(cfg), TaskRecord: NewTaskRecordClient(cfg), User: NewUserClient(cfg), + UserIdentity: NewUserIdentityClient(cfg), UserLoginHistory: NewUserLoginHistoryClient(cfg), }, nil } @@ -262,7 +268,7 @@ func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ c.Admin, c.AdminLoginHistory, c.ApiKey, c.BillingPlan, c.BillingQuota, c.BillingRecord, c.BillingUsage, c.InviteCode, c.Model, c.Setting, c.Task, - c.TaskRecord, c.User, c.UserLoginHistory, + c.TaskRecord, c.User, c.UserIdentity, c.UserLoginHistory, } { n.Use(hooks...) } @@ -274,7 +280,7 @@ func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ c.Admin, c.AdminLoginHistory, c.ApiKey, c.BillingPlan, c.BillingQuota, c.BillingRecord, c.BillingUsage, c.InviteCode, c.Model, c.Setting, c.Task, - c.TaskRecord, c.User, c.UserLoginHistory, + c.TaskRecord, c.User, c.UserIdentity, c.UserLoginHistory, } { n.Intercept(interceptors...) } @@ -309,6 +315,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.TaskRecord.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) + case *UserIdentityMutation: + return c.UserIdentity.mutate(ctx, m) case *UserLoginHistoryMutation: return c.UserLoginHistory.mutate(ctx, m) default: @@ -2200,6 +2208,22 @@ func (c *UserClient) QueryTasks(u *User) *TaskQuery { return query } +// QueryIdentities queries the identities edge of a User. +func (c *UserClient) QueryIdentities(u *User) *UserIdentityQuery { + query := (&UserIdentityClient{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(useridentity.Table, useridentity.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.IdentitiesTable, user.IdentitiesColumn), + ) + 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 @@ -2225,6 +2249,155 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) } } +// UserIdentityClient is a client for the UserIdentity schema. +type UserIdentityClient struct { + config +} + +// NewUserIdentityClient returns a client for the UserIdentity from the given config. +func NewUserIdentityClient(c config) *UserIdentityClient { + return &UserIdentityClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `useridentity.Hooks(f(g(h())))`. +func (c *UserIdentityClient) Use(hooks ...Hook) { + c.hooks.UserIdentity = append(c.hooks.UserIdentity, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `useridentity.Intercept(f(g(h())))`. +func (c *UserIdentityClient) Intercept(interceptors ...Interceptor) { + c.inters.UserIdentity = append(c.inters.UserIdentity, interceptors...) +} + +// Create returns a builder for creating a UserIdentity entity. +func (c *UserIdentityClient) Create() *UserIdentityCreate { + mutation := newUserIdentityMutation(c.config, OpCreate) + return &UserIdentityCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserIdentity entities. +func (c *UserIdentityClient) CreateBulk(builders ...*UserIdentityCreate) *UserIdentityCreateBulk { + return &UserIdentityCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *UserIdentityClient) MapCreateBulk(slice any, setFunc func(*UserIdentityCreate, int)) *UserIdentityCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserIdentityCreateBulk{err: fmt.Errorf("calling to UserIdentityClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserIdentityCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserIdentityCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserIdentity. +func (c *UserIdentityClient) Update() *UserIdentityUpdate { + mutation := newUserIdentityMutation(c.config, OpUpdate) + return &UserIdentityUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserIdentityClient) UpdateOne(ui *UserIdentity) *UserIdentityUpdateOne { + mutation := newUserIdentityMutation(c.config, OpUpdateOne, withUserIdentity(ui)) + return &UserIdentityUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserIdentityClient) UpdateOneID(id uuid.UUID) *UserIdentityUpdateOne { + mutation := newUserIdentityMutation(c.config, OpUpdateOne, withUserIdentityID(id)) + return &UserIdentityUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserIdentity. +func (c *UserIdentityClient) Delete() *UserIdentityDelete { + mutation := newUserIdentityMutation(c.config, OpDelete) + return &UserIdentityDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserIdentityClient) DeleteOne(ui *UserIdentity) *UserIdentityDeleteOne { + return c.DeleteOneID(ui.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserIdentityClient) DeleteOneID(id uuid.UUID) *UserIdentityDeleteOne { + builder := c.Delete().Where(useridentity.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserIdentityDeleteOne{builder} +} + +// Query returns a query builder for UserIdentity. +func (c *UserIdentityClient) Query() *UserIdentityQuery { + return &UserIdentityQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserIdentity}, + inters: c.Interceptors(), + } +} + +// Get returns a UserIdentity entity by its id. +func (c *UserIdentityClient) Get(ctx context.Context, id uuid.UUID) (*UserIdentity, error) { + return c.Query().Where(useridentity.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserIdentityClient) GetX(ctx context.Context, id uuid.UUID) *UserIdentity { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a UserIdentity. +func (c *UserIdentityClient) QueryUser(ui *UserIdentity) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ui.ID + step := sqlgraph.NewStep( + sqlgraph.From(useridentity.Table, useridentity.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, useridentity.UserTable, useridentity.UserColumn), + ) + fromV = sqlgraph.Neighbors(ui.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserIdentityClient) Hooks() []Hook { + return c.hooks.UserIdentity +} + +// Interceptors returns the client interceptors. +func (c *UserIdentityClient) Interceptors() []Interceptor { + return c.inters.UserIdentity +} + +func (c *UserIdentityClient) mutate(ctx context.Context, m *UserIdentityMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserIdentityCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserIdentityUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserIdentityUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserIdentityDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown UserIdentity mutation op: %q", m.Op()) + } +} + // UserLoginHistoryClient is a client for the UserLoginHistory schema. type UserLoginHistoryClient struct { config @@ -2378,12 +2551,12 @@ func (c *UserLoginHistoryClient) mutate(ctx context.Context, m *UserLoginHistory type ( hooks struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, InviteCode, Model, Setting, Task, TaskRecord, User, + BillingUsage, InviteCode, Model, Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory []ent.Hook } inters struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, InviteCode, Model, Setting, Task, TaskRecord, User, + BillingUsage, InviteCode, Model, Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory []ent.Interceptor } ) diff --git a/backend/db/ent.go b/backend/db/ent.go index 292f941..65ced18 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -25,6 +25,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" ) @@ -99,6 +100,7 @@ func checkColumn(table, column string) error { task.Table: task.ValidColumn, taskrecord.Table: taskrecord.ValidColumn, user.Table: user.ValidColumn, + useridentity.Table: useridentity.ValidColumn, userloginhistory.Table: userloginhistory.ValidColumn, }) }) diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index f9630e1..d61e29e 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -165,6 +165,18 @@ func (f UserFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserMutation", m) } +// The UserIdentityFunc type is an adapter to allow the use of ordinary +// function as UserIdentity mutator. +type UserIdentityFunc func(context.Context, *db.UserIdentityMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f UserIdentityFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.UserIdentityMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserIdentityMutation", m) +} + // The UserLoginHistoryFunc type is an adapter to allow the use of ordinary // function as UserLoginHistory mutator. type UserLoginHistoryFunc func(context.Context, *db.UserLoginHistoryMutation) (db.Value, error) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index d9c7d69..c234f28 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -22,6 +22,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" ) @@ -432,6 +433,33 @@ func (f TraverseUser) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.UserQuery", q) } +// The UserIdentityFunc type is an adapter to allow the use of ordinary function as a Querier. +type UserIdentityFunc func(context.Context, *db.UserIdentityQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f UserIdentityFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.UserIdentityQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.UserIdentityQuery", q) +} + +// The TraverseUserIdentity type is an adapter to allow the use of ordinary function as Traverser. +type TraverseUserIdentity func(context.Context, *db.UserIdentityQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseUserIdentity) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseUserIdentity) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.UserIdentityQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.UserIdentityQuery", q) +} + // The UserLoginHistoryFunc type is an adapter to allow the use of ordinary function as a Querier. type UserLoginHistoryFunc func(context.Context, *db.UserLoginHistoryQuery) (db.Value, error) @@ -488,6 +516,8 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.TaskRecordQuery, predicate.TaskRecord, taskrecord.OrderOption]{typ: db.TypeTaskRecord, tq: q}, nil case *db.UserQuery: return &query[*db.UserQuery, predicate.User, user.OrderOption]{typ: db.TypeUser, tq: q}, nil + case *db.UserIdentityQuery: + return &query[*db.UserIdentityQuery, predicate.UserIdentity, useridentity.OrderOption]{typ: db.TypeUserIdentity, tq: q}, nil case *db.UserLoginHistoryQuery: return &query[*db.UserLoginHistoryQuery, predicate.UserLoginHistory, userloginhistory.OrderOption]{typ: db.TypeUserLoginHistory, tq: q}, nil default: diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index 373a0d0..cc62789 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -191,6 +191,9 @@ var ( {Name: "enable_sso", Type: field.TypeBool, Default: false}, {Name: "force_two_factor_auth", Type: field.TypeBool, Default: false}, {Name: "disable_password_login", Type: field.TypeBool, Default: false}, + {Name: "enable_dingtalk_oauth", Type: field.TypeBool, Default: false}, + {Name: "dingtalk_client_id", Type: field.TypeString, Nullable: true}, + {Name: "dingtalk_client_secret", Type: field.TypeString, Nullable: true}, {Name: "created_at", Type: field.TypeTime}, {Name: "updated_at", Type: field.TypeTime}, } @@ -265,9 +268,11 @@ var ( // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, - {Name: "username", Type: field.TypeString, Unique: true}, - {Name: "password", Type: field.TypeString}, - {Name: "email", Type: field.TypeString, Unique: true}, + {Name: "username", Type: field.TypeString, Nullable: true}, + {Name: "password", Type: field.TypeString, Nullable: true}, + {Name: "email", Type: field.TypeString, Nullable: true}, + {Name: "avatar_url", Type: field.TypeString, Nullable: true}, + {Name: "platform", Type: field.TypeString, Default: "email"}, {Name: "status", Type: field.TypeString, Default: "active"}, {Name: "created_at", Type: field.TypeTime}, {Name: "updated_at", Type: field.TypeTime}, @@ -278,6 +283,32 @@ var ( Columns: UsersColumns, PrimaryKey: []*schema.Column{UsersColumns[0]}, } + // UserIdentitiesColumns holds the columns for the "user_identities" table. + UserIdentitiesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "platform", Type: field.TypeString, Default: "email"}, + {Name: "identity_id", Type: field.TypeString}, + {Name: "union_id", Type: field.TypeString, Nullable: true}, + {Name: "nickname", Type: field.TypeString, Nullable: true}, + {Name: "email", Type: field.TypeString, Nullable: true}, + {Name: "avatar_url", Type: field.TypeString, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeUUID, Nullable: true}, + } + // UserIdentitiesTable holds the schema information for the "user_identities" table. + UserIdentitiesTable = &schema.Table{ + Name: "user_identities", + Columns: UserIdentitiesColumns, + PrimaryKey: []*schema.Column{UserIdentitiesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_identities_users_identities", + Columns: []*schema.Column{UserIdentitiesColumns[8]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // UserLoginHistoriesColumns holds the columns for the "user_login_histories" table. UserLoginHistoriesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -322,6 +353,7 @@ var ( TasksTable, TaskRecordsTable, UsersTable, + UserIdentitiesTable, UserLoginHistoriesTable, } ) @@ -371,6 +403,10 @@ func init() { UsersTable.Annotation = &entsql.Annotation{ Table: "users", } + UserIdentitiesTable.ForeignKeys[0].RefTable = UsersTable + UserIdentitiesTable.Annotation = &entsql.Annotation{ + Table: "user_identities", + } UserLoginHistoriesTable.ForeignKeys[0].RefTable = UsersTable UserLoginHistoriesTable.Annotation = &entsql.Annotation{ Table: "user_login_histories", diff --git a/backend/db/mutation.go b/backend/db/mutation.go index 3f4609c..2e37daf 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -26,6 +26,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" ) @@ -52,6 +53,7 @@ const ( TypeTask = "Task" TypeTaskRecord = "TaskRecord" TypeUser = "User" + TypeUserIdentity = "UserIdentity" TypeUserLoginHistory = "UserLoginHistory" ) @@ -7013,6 +7015,9 @@ type SettingMutation struct { enable_sso *bool force_two_factor_auth *bool disable_password_login *bool + enable_dingtalk_oauth *bool + dingtalk_client_id *string + dingtalk_client_secret *string created_at *time.Time updated_at *time.Time clearedFields map[string]struct{} @@ -7233,6 +7238,140 @@ func (m *SettingMutation) ResetDisablePasswordLogin() { m.disable_password_login = nil } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (m *SettingMutation) SetEnableDingtalkOauth(b bool) { + m.enable_dingtalk_oauth = &b +} + +// EnableDingtalkOauth returns the value of the "enable_dingtalk_oauth" field in the mutation. +func (m *SettingMutation) EnableDingtalkOauth() (r bool, exists bool) { + v := m.enable_dingtalk_oauth + if v == nil { + return + } + return *v, true +} + +// OldEnableDingtalkOauth returns the old "enable_dingtalk_oauth" field's value of the Setting entity. +// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SettingMutation) OldEnableDingtalkOauth(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnableDingtalkOauth is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnableDingtalkOauth requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnableDingtalkOauth: %w", err) + } + return oldValue.EnableDingtalkOauth, nil +} + +// ResetEnableDingtalkOauth resets all changes to the "enable_dingtalk_oauth" field. +func (m *SettingMutation) ResetEnableDingtalkOauth() { + m.enable_dingtalk_oauth = nil +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (m *SettingMutation) SetDingtalkClientID(s string) { + m.dingtalk_client_id = &s +} + +// DingtalkClientID returns the value of the "dingtalk_client_id" field in the mutation. +func (m *SettingMutation) DingtalkClientID() (r string, exists bool) { + v := m.dingtalk_client_id + if v == nil { + return + } + return *v, true +} + +// OldDingtalkClientID returns the old "dingtalk_client_id" field's value of the Setting entity. +// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SettingMutation) OldDingtalkClientID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDingtalkClientID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDingtalkClientID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDingtalkClientID: %w", err) + } + return oldValue.DingtalkClientID, nil +} + +// ClearDingtalkClientID clears the value of the "dingtalk_client_id" field. +func (m *SettingMutation) ClearDingtalkClientID() { + m.dingtalk_client_id = nil + m.clearedFields[setting.FieldDingtalkClientID] = struct{}{} +} + +// DingtalkClientIDCleared returns if the "dingtalk_client_id" field was cleared in this mutation. +func (m *SettingMutation) DingtalkClientIDCleared() bool { + _, ok := m.clearedFields[setting.FieldDingtalkClientID] + return ok +} + +// ResetDingtalkClientID resets all changes to the "dingtalk_client_id" field. +func (m *SettingMutation) ResetDingtalkClientID() { + m.dingtalk_client_id = nil + delete(m.clearedFields, setting.FieldDingtalkClientID) +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (m *SettingMutation) SetDingtalkClientSecret(s string) { + m.dingtalk_client_secret = &s +} + +// DingtalkClientSecret returns the value of the "dingtalk_client_secret" field in the mutation. +func (m *SettingMutation) DingtalkClientSecret() (r string, exists bool) { + v := m.dingtalk_client_secret + if v == nil { + return + } + return *v, true +} + +// OldDingtalkClientSecret returns the old "dingtalk_client_secret" field's value of the Setting entity. +// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SettingMutation) OldDingtalkClientSecret(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDingtalkClientSecret is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDingtalkClientSecret requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDingtalkClientSecret: %w", err) + } + return oldValue.DingtalkClientSecret, nil +} + +// ClearDingtalkClientSecret clears the value of the "dingtalk_client_secret" field. +func (m *SettingMutation) ClearDingtalkClientSecret() { + m.dingtalk_client_secret = nil + m.clearedFields[setting.FieldDingtalkClientSecret] = struct{}{} +} + +// DingtalkClientSecretCleared returns if the "dingtalk_client_secret" field was cleared in this mutation. +func (m *SettingMutation) DingtalkClientSecretCleared() bool { + _, ok := m.clearedFields[setting.FieldDingtalkClientSecret] + return ok +} + +// ResetDingtalkClientSecret resets all changes to the "dingtalk_client_secret" field. +func (m *SettingMutation) ResetDingtalkClientSecret() { + m.dingtalk_client_secret = nil + delete(m.clearedFields, setting.FieldDingtalkClientSecret) +} + // SetCreatedAt sets the "created_at" field. func (m *SettingMutation) SetCreatedAt(t time.Time) { m.created_at = &t @@ -7339,7 +7478,7 @@ func (m *SettingMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *SettingMutation) Fields() []string { - fields := make([]string, 0, 5) + fields := make([]string, 0, 8) if m.enable_sso != nil { fields = append(fields, setting.FieldEnableSSO) } @@ -7349,6 +7488,15 @@ func (m *SettingMutation) Fields() []string { if m.disable_password_login != nil { fields = append(fields, setting.FieldDisablePasswordLogin) } + if m.enable_dingtalk_oauth != nil { + fields = append(fields, setting.FieldEnableDingtalkOauth) + } + if m.dingtalk_client_id != nil { + fields = append(fields, setting.FieldDingtalkClientID) + } + if m.dingtalk_client_secret != nil { + fields = append(fields, setting.FieldDingtalkClientSecret) + } if m.created_at != nil { fields = append(fields, setting.FieldCreatedAt) } @@ -7369,6 +7517,12 @@ func (m *SettingMutation) Field(name string) (ent.Value, bool) { return m.ForceTwoFactorAuth() case setting.FieldDisablePasswordLogin: return m.DisablePasswordLogin() + case setting.FieldEnableDingtalkOauth: + return m.EnableDingtalkOauth() + case setting.FieldDingtalkClientID: + return m.DingtalkClientID() + case setting.FieldDingtalkClientSecret: + return m.DingtalkClientSecret() case setting.FieldCreatedAt: return m.CreatedAt() case setting.FieldUpdatedAt: @@ -7388,6 +7542,12 @@ func (m *SettingMutation) OldField(ctx context.Context, name string) (ent.Value, return m.OldForceTwoFactorAuth(ctx) case setting.FieldDisablePasswordLogin: return m.OldDisablePasswordLogin(ctx) + case setting.FieldEnableDingtalkOauth: + return m.OldEnableDingtalkOauth(ctx) + case setting.FieldDingtalkClientID: + return m.OldDingtalkClientID(ctx) + case setting.FieldDingtalkClientSecret: + return m.OldDingtalkClientSecret(ctx) case setting.FieldCreatedAt: return m.OldCreatedAt(ctx) case setting.FieldUpdatedAt: @@ -7422,6 +7582,27 @@ func (m *SettingMutation) SetField(name string, value ent.Value) error { } m.SetDisablePasswordLogin(v) return nil + case setting.FieldEnableDingtalkOauth: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnableDingtalkOauth(v) + return nil + case setting.FieldDingtalkClientID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDingtalkClientID(v) + return nil + case setting.FieldDingtalkClientSecret: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDingtalkClientSecret(v) + return nil case setting.FieldCreatedAt: v, ok := value.(time.Time) if !ok { @@ -7465,7 +7646,14 @@ func (m *SettingMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *SettingMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(setting.FieldDingtalkClientID) { + fields = append(fields, setting.FieldDingtalkClientID) + } + if m.FieldCleared(setting.FieldDingtalkClientSecret) { + fields = append(fields, setting.FieldDingtalkClientSecret) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -7478,6 +7666,14 @@ func (m *SettingMutation) FieldCleared(name string) bool { // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *SettingMutation) ClearField(name string) error { + switch name { + case setting.FieldDingtalkClientID: + m.ClearDingtalkClientID() + return nil + case setting.FieldDingtalkClientSecret: + m.ClearDingtalkClientSecret() + return nil + } return fmt.Errorf("unknown Setting nullable field %s", name) } @@ -7494,6 +7690,15 @@ func (m *SettingMutation) ResetField(name string) error { case setting.FieldDisablePasswordLogin: m.ResetDisablePasswordLogin() return nil + case setting.FieldEnableDingtalkOauth: + m.ResetEnableDingtalkOauth() + return nil + case setting.FieldDingtalkClientID: + m.ResetDingtalkClientID() + return nil + case setting.FieldDingtalkClientSecret: + m.ResetDingtalkClientSecret() + return nil case setting.FieldCreatedAt: m.ResetCreatedAt() return nil @@ -9792,6 +9997,8 @@ type UserMutation struct { username *string password *string email *string + avatar_url *string + platform *consts.UserPlatform status *consts.UserStatus created_at *time.Time updated_at *time.Time @@ -9805,6 +10012,9 @@ type UserMutation struct { tasks map[uuid.UUID]struct{} removedtasks map[uuid.UUID]struct{} clearedtasks bool + identities map[uuid.UUID]struct{} + removedidentities map[uuid.UUID]struct{} + clearedidentities bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -9945,9 +10155,22 @@ func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) { return oldValue.Username, nil } +// ClearUsername clears the value of the "username" field. +func (m *UserMutation) ClearUsername() { + m.username = nil + m.clearedFields[user.FieldUsername] = struct{}{} +} + +// UsernameCleared returns if the "username" field was cleared in this mutation. +func (m *UserMutation) UsernameCleared() bool { + _, ok := m.clearedFields[user.FieldUsername] + return ok +} + // ResetUsername resets all changes to the "username" field. func (m *UserMutation) ResetUsername() { m.username = nil + delete(m.clearedFields, user.FieldUsername) } // SetPassword sets the "password" field. @@ -9981,9 +10204,22 @@ func (m *UserMutation) OldPassword(ctx context.Context) (v string, err error) { return oldValue.Password, nil } +// ClearPassword clears the value of the "password" field. +func (m *UserMutation) ClearPassword() { + m.password = nil + m.clearedFields[user.FieldPassword] = struct{}{} +} + +// PasswordCleared returns if the "password" field was cleared in this mutation. +func (m *UserMutation) PasswordCleared() bool { + _, ok := m.clearedFields[user.FieldPassword] + return ok +} + // ResetPassword resets all changes to the "password" field. func (m *UserMutation) ResetPassword() { m.password = nil + delete(m.clearedFields, user.FieldPassword) } // SetEmail sets the "email" field. @@ -10017,9 +10253,107 @@ func (m *UserMutation) OldEmail(ctx context.Context) (v string, err error) { return oldValue.Email, nil } +// ClearEmail clears the value of the "email" field. +func (m *UserMutation) ClearEmail() { + m.email = nil + m.clearedFields[user.FieldEmail] = struct{}{} +} + +// EmailCleared returns if the "email" field was cleared in this mutation. +func (m *UserMutation) EmailCleared() bool { + _, ok := m.clearedFields[user.FieldEmail] + return ok +} + // ResetEmail resets all changes to the "email" field. func (m *UserMutation) ResetEmail() { m.email = nil + delete(m.clearedFields, user.FieldEmail) +} + +// SetAvatarURL sets the "avatar_url" field. +func (m *UserMutation) SetAvatarURL(s string) { + m.avatar_url = &s +} + +// AvatarURL returns the value of the "avatar_url" field in the mutation. +func (m *UserMutation) AvatarURL() (r string, exists bool) { + v := m.avatar_url + if v == nil { + return + } + return *v, true +} + +// OldAvatarURL returns the old "avatar_url" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldAvatarURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAvatarURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) + } + return oldValue.AvatarURL, nil +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (m *UserMutation) ClearAvatarURL() { + m.avatar_url = nil + m.clearedFields[user.FieldAvatarURL] = struct{}{} +} + +// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. +func (m *UserMutation) AvatarURLCleared() bool { + _, ok := m.clearedFields[user.FieldAvatarURL] + return ok +} + +// ResetAvatarURL resets all changes to the "avatar_url" field. +func (m *UserMutation) ResetAvatarURL() { + m.avatar_url = nil + delete(m.clearedFields, user.FieldAvatarURL) +} + +// SetPlatform sets the "platform" field. +func (m *UserMutation) SetPlatform(cp consts.UserPlatform) { + m.platform = &cp +} + +// Platform returns the value of the "platform" field in the mutation. +func (m *UserMutation) Platform() (r consts.UserPlatform, exists bool) { + v := m.platform + if v == nil { + return + } + return *v, true +} + +// OldPlatform returns the old "platform" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldPlatform(ctx context.Context) (v consts.UserPlatform, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlatform is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlatform requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlatform: %w", err) + } + return oldValue.Platform, nil +} + +// ResetPlatform resets all changes to the "platform" field. +func (m *UserMutation) ResetPlatform() { + m.platform = nil } // SetStatus sets the "status" field. @@ -10292,6 +10626,60 @@ func (m *UserMutation) ResetTasks() { m.removedtasks = nil } +// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by ids. +func (m *UserMutation) AddIdentityIDs(ids ...uuid.UUID) { + if m.identities == nil { + m.identities = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.identities[ids[i]] = struct{}{} + } +} + +// ClearIdentities clears the "identities" edge to the UserIdentity entity. +func (m *UserMutation) ClearIdentities() { + m.clearedidentities = true +} + +// IdentitiesCleared reports if the "identities" edge to the UserIdentity entity was cleared. +func (m *UserMutation) IdentitiesCleared() bool { + return m.clearedidentities +} + +// RemoveIdentityIDs removes the "identities" edge to the UserIdentity entity by IDs. +func (m *UserMutation) RemoveIdentityIDs(ids ...uuid.UUID) { + if m.removedidentities == nil { + m.removedidentities = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.identities, ids[i]) + m.removedidentities[ids[i]] = struct{}{} + } +} + +// RemovedIdentities returns the removed IDs of the "identities" edge to the UserIdentity entity. +func (m *UserMutation) RemovedIdentitiesIDs() (ids []uuid.UUID) { + for id := range m.removedidentities { + ids = append(ids, id) + } + return +} + +// IdentitiesIDs returns the "identities" edge IDs in the mutation. +func (m *UserMutation) IdentitiesIDs() (ids []uuid.UUID) { + for id := range m.identities { + ids = append(ids, id) + } + return +} + +// ResetIdentities resets all changes to the "identities" edge. +func (m *UserMutation) ResetIdentities() { + m.identities = nil + m.clearedidentities = false + m.removedidentities = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -10326,7 +10714,7 @@ func (m *UserMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *UserMutation) Fields() []string { - fields := make([]string, 0, 6) + fields := make([]string, 0, 8) if m.username != nil { fields = append(fields, user.FieldUsername) } @@ -10336,6 +10724,12 @@ func (m *UserMutation) Fields() []string { if m.email != nil { fields = append(fields, user.FieldEmail) } + if m.avatar_url != nil { + fields = append(fields, user.FieldAvatarURL) + } + if m.platform != nil { + fields = append(fields, user.FieldPlatform) + } if m.status != nil { fields = append(fields, user.FieldStatus) } @@ -10359,6 +10753,10 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) { return m.Password() case user.FieldEmail: return m.Email() + case user.FieldAvatarURL: + return m.AvatarURL() + case user.FieldPlatform: + return m.Platform() case user.FieldStatus: return m.Status() case user.FieldCreatedAt: @@ -10380,6 +10778,10 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er return m.OldPassword(ctx) case user.FieldEmail: return m.OldEmail(ctx) + case user.FieldAvatarURL: + return m.OldAvatarURL(ctx) + case user.FieldPlatform: + return m.OldPlatform(ctx) case user.FieldStatus: return m.OldStatus(ctx) case user.FieldCreatedAt: @@ -10416,6 +10818,20 @@ func (m *UserMutation) SetField(name string, value ent.Value) error { } m.SetEmail(v) return nil + case user.FieldAvatarURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatarURL(v) + return nil + case user.FieldPlatform: + v, ok := value.(consts.UserPlatform) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlatform(v) + return nil case user.FieldStatus: v, ok := value.(consts.UserStatus) if !ok { @@ -10466,7 +10882,20 @@ func (m *UserMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *UserMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(user.FieldUsername) { + fields = append(fields, user.FieldUsername) + } + if m.FieldCleared(user.FieldPassword) { + fields = append(fields, user.FieldPassword) + } + if m.FieldCleared(user.FieldEmail) { + fields = append(fields, user.FieldEmail) + } + if m.FieldCleared(user.FieldAvatarURL) { + fields = append(fields, user.FieldAvatarURL) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -10479,6 +10908,20 @@ func (m *UserMutation) FieldCleared(name string) bool { // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *UserMutation) ClearField(name string) error { + switch name { + case user.FieldUsername: + m.ClearUsername() + return nil + case user.FieldPassword: + m.ClearPassword() + return nil + case user.FieldEmail: + m.ClearEmail() + return nil + case user.FieldAvatarURL: + m.ClearAvatarURL() + return nil + } return fmt.Errorf("unknown User nullable field %s", name) } @@ -10495,6 +10938,12 @@ func (m *UserMutation) ResetField(name string) error { case user.FieldEmail: m.ResetEmail() return nil + case user.FieldAvatarURL: + m.ResetAvatarURL() + return nil + case user.FieldPlatform: + m.ResetPlatform() + return nil case user.FieldStatus: m.ResetStatus() return nil @@ -10510,7 +10959,7 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 4) if m.login_histories != nil { edges = append(edges, user.EdgeLoginHistories) } @@ -10520,6 +10969,9 @@ func (m *UserMutation) AddedEdges() []string { if m.tasks != nil { edges = append(edges, user.EdgeTasks) } + if m.identities != nil { + edges = append(edges, user.EdgeIdentities) + } return edges } @@ -10545,13 +10997,19 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeIdentities: + ids := make([]ent.Value, 0, len(m.identities)) + for id := range m.identities { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 4) if m.removedlogin_histories != nil { edges = append(edges, user.EdgeLoginHistories) } @@ -10561,6 +11019,9 @@ func (m *UserMutation) RemovedEdges() []string { if m.removedtasks != nil { edges = append(edges, user.EdgeTasks) } + if m.removedidentities != nil { + edges = append(edges, user.EdgeIdentities) + } return edges } @@ -10586,13 +11047,19 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeIdentities: + ids := make([]ent.Value, 0, len(m.removedidentities)) + for id := range m.removedidentities { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 4) if m.clearedlogin_histories { edges = append(edges, user.EdgeLoginHistories) } @@ -10602,6 +11069,9 @@ func (m *UserMutation) ClearedEdges() []string { if m.clearedtasks { edges = append(edges, user.EdgeTasks) } + if m.clearedidentities { + edges = append(edges, user.EdgeIdentities) + } return edges } @@ -10615,6 +11085,8 @@ func (m *UserMutation) EdgeCleared(name string) bool { return m.clearedmodels case user.EdgeTasks: return m.clearedtasks + case user.EdgeIdentities: + return m.clearedidentities } return false } @@ -10640,10 +11112,875 @@ func (m *UserMutation) ResetEdge(name string) error { case user.EdgeTasks: m.ResetTasks() return nil + case user.EdgeIdentities: + m.ResetIdentities() + return nil } return fmt.Errorf("unknown User edge %s", name) } +// UserIdentityMutation represents an operation that mutates the UserIdentity nodes in the graph. +type UserIdentityMutation struct { + config + op Op + typ string + id *uuid.UUID + platform *consts.UserPlatform + identity_id *string + union_id *string + nickname *string + email *string + avatar_url *string + created_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*UserIdentity, error) + predicates []predicate.UserIdentity +} + +var _ ent.Mutation = (*UserIdentityMutation)(nil) + +// useridentityOption allows management of the mutation configuration using functional options. +type useridentityOption func(*UserIdentityMutation) + +// newUserIdentityMutation creates new mutation for the UserIdentity entity. +func newUserIdentityMutation(c config, op Op, opts ...useridentityOption) *UserIdentityMutation { + m := &UserIdentityMutation{ + config: c, + op: op, + typ: TypeUserIdentity, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserIdentityID sets the ID field of the mutation. +func withUserIdentityID(id uuid.UUID) useridentityOption { + return func(m *UserIdentityMutation) { + var ( + err error + once sync.Once + value *UserIdentity + ) + m.oldValue = func(ctx context.Context) (*UserIdentity, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserIdentity.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUserIdentity sets the old UserIdentity of the mutation. +func withUserIdentity(node *UserIdentity) useridentityOption { + return func(m *UserIdentityMutation) { + m.oldValue = func(context.Context) (*UserIdentity, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserIdentityMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserIdentityMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of UserIdentity entities. +func (m *UserIdentityMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserIdentityMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserIdentityMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UserIdentity.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUserID sets the "user_id" field. +func (m *UserIdentityMutation) SetUserID(u uuid.UUID) { + m.user = &u +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *UserIdentityMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ClearUserID clears the value of the "user_id" field. +func (m *UserIdentityMutation) ClearUserID() { + m.user = nil + m.clearedFields[useridentity.FieldUserID] = struct{}{} +} + +// UserIDCleared returns if the "user_id" field was cleared in this mutation. +func (m *UserIdentityMutation) UserIDCleared() bool { + _, ok := m.clearedFields[useridentity.FieldUserID] + return ok +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *UserIdentityMutation) ResetUserID() { + m.user = nil + delete(m.clearedFields, useridentity.FieldUserID) +} + +// SetPlatform sets the "platform" field. +func (m *UserIdentityMutation) SetPlatform(cp consts.UserPlatform) { + m.platform = &cp +} + +// Platform returns the value of the "platform" field in the mutation. +func (m *UserIdentityMutation) Platform() (r consts.UserPlatform, exists bool) { + v := m.platform + if v == nil { + return + } + return *v, true +} + +// OldPlatform returns the old "platform" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldPlatform(ctx context.Context) (v consts.UserPlatform, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlatform is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlatform requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlatform: %w", err) + } + return oldValue.Platform, nil +} + +// ResetPlatform resets all changes to the "platform" field. +func (m *UserIdentityMutation) ResetPlatform() { + m.platform = nil +} + +// SetIdentityID sets the "identity_id" field. +func (m *UserIdentityMutation) SetIdentityID(s string) { + m.identity_id = &s +} + +// IdentityID returns the value of the "identity_id" field in the mutation. +func (m *UserIdentityMutation) IdentityID() (r string, exists bool) { + v := m.identity_id + if v == nil { + return + } + return *v, true +} + +// OldIdentityID returns the old "identity_id" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldIdentityID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIdentityID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIdentityID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIdentityID: %w", err) + } + return oldValue.IdentityID, nil +} + +// ResetIdentityID resets all changes to the "identity_id" field. +func (m *UserIdentityMutation) ResetIdentityID() { + m.identity_id = nil +} + +// SetUnionID sets the "union_id" field. +func (m *UserIdentityMutation) SetUnionID(s string) { + m.union_id = &s +} + +// UnionID returns the value of the "union_id" field in the mutation. +func (m *UserIdentityMutation) UnionID() (r string, exists bool) { + v := m.union_id + if v == nil { + return + } + return *v, true +} + +// OldUnionID returns the old "union_id" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldUnionID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnionID: %w", err) + } + return oldValue.UnionID, nil +} + +// ClearUnionID clears the value of the "union_id" field. +func (m *UserIdentityMutation) ClearUnionID() { + m.union_id = nil + m.clearedFields[useridentity.FieldUnionID] = struct{}{} +} + +// UnionIDCleared returns if the "union_id" field was cleared in this mutation. +func (m *UserIdentityMutation) UnionIDCleared() bool { + _, ok := m.clearedFields[useridentity.FieldUnionID] + return ok +} + +// ResetUnionID resets all changes to the "union_id" field. +func (m *UserIdentityMutation) ResetUnionID() { + m.union_id = nil + delete(m.clearedFields, useridentity.FieldUnionID) +} + +// SetNickname sets the "nickname" field. +func (m *UserIdentityMutation) SetNickname(s string) { + m.nickname = &s +} + +// Nickname returns the value of the "nickname" field in the mutation. +func (m *UserIdentityMutation) Nickname() (r string, exists bool) { + v := m.nickname + if v == nil { + return + } + return *v, true +} + +// OldNickname returns the old "nickname" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldNickname(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNickname is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNickname requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNickname: %w", err) + } + return oldValue.Nickname, nil +} + +// ClearNickname clears the value of the "nickname" field. +func (m *UserIdentityMutation) ClearNickname() { + m.nickname = nil + m.clearedFields[useridentity.FieldNickname] = struct{}{} +} + +// NicknameCleared returns if the "nickname" field was cleared in this mutation. +func (m *UserIdentityMutation) NicknameCleared() bool { + _, ok := m.clearedFields[useridentity.FieldNickname] + return ok +} + +// ResetNickname resets all changes to the "nickname" field. +func (m *UserIdentityMutation) ResetNickname() { + m.nickname = nil + delete(m.clearedFields, useridentity.FieldNickname) +} + +// SetEmail sets the "email" field. +func (m *UserIdentityMutation) SetEmail(s string) { + m.email = &s +} + +// Email returns the value of the "email" field in the mutation. +func (m *UserIdentityMutation) Email() (r string, exists bool) { + v := m.email + if v == nil { + return + } + return *v, true +} + +// OldEmail returns the old "email" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldEmail(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEmail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEmail requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEmail: %w", err) + } + return oldValue.Email, nil +} + +// ClearEmail clears the value of the "email" field. +func (m *UserIdentityMutation) ClearEmail() { + m.email = nil + m.clearedFields[useridentity.FieldEmail] = struct{}{} +} + +// EmailCleared returns if the "email" field was cleared in this mutation. +func (m *UserIdentityMutation) EmailCleared() bool { + _, ok := m.clearedFields[useridentity.FieldEmail] + return ok +} + +// ResetEmail resets all changes to the "email" field. +func (m *UserIdentityMutation) ResetEmail() { + m.email = nil + delete(m.clearedFields, useridentity.FieldEmail) +} + +// SetAvatarURL sets the "avatar_url" field. +func (m *UserIdentityMutation) SetAvatarURL(s string) { + m.avatar_url = &s +} + +// AvatarURL returns the value of the "avatar_url" field in the mutation. +func (m *UserIdentityMutation) AvatarURL() (r string, exists bool) { + v := m.avatar_url + if v == nil { + return + } + return *v, true +} + +// OldAvatarURL returns the old "avatar_url" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldAvatarURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAvatarURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) + } + return oldValue.AvatarURL, nil +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (m *UserIdentityMutation) ClearAvatarURL() { + m.avatar_url = nil + m.clearedFields[useridentity.FieldAvatarURL] = struct{}{} +} + +// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. +func (m *UserIdentityMutation) AvatarURLCleared() bool { + _, ok := m.clearedFields[useridentity.FieldAvatarURL] + return ok +} + +// ResetAvatarURL resets all changes to the "avatar_url" field. +func (m *UserIdentityMutation) ResetAvatarURL() { + m.avatar_url = nil + delete(m.clearedFields, useridentity.FieldAvatarURL) +} + +// SetCreatedAt sets the "created_at" field. +func (m *UserIdentityMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserIdentityMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the UserIdentity entity. +// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserIdentityMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserIdentityMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *UserIdentityMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[useridentity.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UserIdentityMutation) UserCleared() bool { + return m.UserIDCleared() || m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UserIdentityMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *UserIdentityMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// Where appends a list predicates to the UserIdentityMutation builder. +func (m *UserIdentityMutation) Where(ps ...predicate.UserIdentity) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserIdentityMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserIdentityMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserIdentity, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UserIdentityMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserIdentityMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UserIdentity). +func (m *UserIdentityMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserIdentityMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.user != nil { + fields = append(fields, useridentity.FieldUserID) + } + if m.platform != nil { + fields = append(fields, useridentity.FieldPlatform) + } + if m.identity_id != nil { + fields = append(fields, useridentity.FieldIdentityID) + } + if m.union_id != nil { + fields = append(fields, useridentity.FieldUnionID) + } + if m.nickname != nil { + fields = append(fields, useridentity.FieldNickname) + } + if m.email != nil { + fields = append(fields, useridentity.FieldEmail) + } + if m.avatar_url != nil { + fields = append(fields, useridentity.FieldAvatarURL) + } + if m.created_at != nil { + fields = append(fields, useridentity.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UserIdentityMutation) Field(name string) (ent.Value, bool) { + switch name { + case useridentity.FieldUserID: + return m.UserID() + case useridentity.FieldPlatform: + return m.Platform() + case useridentity.FieldIdentityID: + return m.IdentityID() + case useridentity.FieldUnionID: + return m.UnionID() + case useridentity.FieldNickname: + return m.Nickname() + case useridentity.FieldEmail: + return m.Email() + case useridentity.FieldAvatarURL: + return m.AvatarURL() + case useridentity.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UserIdentityMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case useridentity.FieldUserID: + return m.OldUserID(ctx) + case useridentity.FieldPlatform: + return m.OldPlatform(ctx) + case useridentity.FieldIdentityID: + return m.OldIdentityID(ctx) + case useridentity.FieldUnionID: + return m.OldUnionID(ctx) + case useridentity.FieldNickname: + return m.OldNickname(ctx) + case useridentity.FieldEmail: + return m.OldEmail(ctx) + case useridentity.FieldAvatarURL: + return m.OldAvatarURL(ctx) + case useridentity.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown UserIdentity field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserIdentityMutation) SetField(name string, value ent.Value) error { + switch name { + case useridentity.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case useridentity.FieldPlatform: + v, ok := value.(consts.UserPlatform) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlatform(v) + return nil + case useridentity.FieldIdentityID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentityID(v) + return nil + case useridentity.FieldUnionID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnionID(v) + return nil + case useridentity.FieldNickname: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNickname(v) + return nil + case useridentity.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + case useridentity.FieldAvatarURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatarURL(v) + return nil + case useridentity.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown UserIdentity field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserIdentityMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UserIdentityMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserIdentityMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UserIdentity numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserIdentityMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(useridentity.FieldUserID) { + fields = append(fields, useridentity.FieldUserID) + } + if m.FieldCleared(useridentity.FieldUnionID) { + fields = append(fields, useridentity.FieldUnionID) + } + if m.FieldCleared(useridentity.FieldNickname) { + fields = append(fields, useridentity.FieldNickname) + } + if m.FieldCleared(useridentity.FieldEmail) { + fields = append(fields, useridentity.FieldEmail) + } + if m.FieldCleared(useridentity.FieldAvatarURL) { + fields = append(fields, useridentity.FieldAvatarURL) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserIdentityMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserIdentityMutation) ClearField(name string) error { + switch name { + case useridentity.FieldUserID: + m.ClearUserID() + return nil + case useridentity.FieldUnionID: + m.ClearUnionID() + return nil + case useridentity.FieldNickname: + m.ClearNickname() + return nil + case useridentity.FieldEmail: + m.ClearEmail() + return nil + case useridentity.FieldAvatarURL: + m.ClearAvatarURL() + return nil + } + return fmt.Errorf("unknown UserIdentity nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserIdentityMutation) ResetField(name string) error { + switch name { + case useridentity.FieldUserID: + m.ResetUserID() + return nil + case useridentity.FieldPlatform: + m.ResetPlatform() + return nil + case useridentity.FieldIdentityID: + m.ResetIdentityID() + return nil + case useridentity.FieldUnionID: + m.ResetUnionID() + return nil + case useridentity.FieldNickname: + m.ResetNickname() + return nil + case useridentity.FieldEmail: + m.ResetEmail() + return nil + case useridentity.FieldAvatarURL: + m.ResetAvatarURL() + return nil + case useridentity.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown UserIdentity field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserIdentityMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, useridentity.EdgeUser) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserIdentityMutation) AddedIDs(name string) []ent.Value { + switch name { + case useridentity.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserIdentityMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserIdentityMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserIdentityMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, useridentity.EdgeUser) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserIdentityMutation) EdgeCleared(name string) bool { + switch name { + case useridentity.EdgeUser: + return m.cleareduser + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserIdentityMutation) ClearEdge(name string) error { + switch name { + case useridentity.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown UserIdentity unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserIdentityMutation) ResetEdge(name string) error { + switch name { + case useridentity.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown UserIdentity edge %s", name) +} + // UserLoginHistoryMutation represents an operation that mutates the UserLoginHistory nodes in the graph. type UserLoginHistoryMutation struct { config diff --git a/backend/db/page.go b/backend/db/page.go index 02856ec..cf0cff9 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -193,6 +193,20 @@ func (u *UserQuery) Page(ctx context.Context, page, size int) ([]*User, *PageInf return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (ui *UserIdentityQuery) Page(ctx context.Context, page, size int) ([]*UserIdentity, *PageInfo, error) { + cnt, err := ui.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := ui.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (ulh *UserLoginHistoryQuery) Page(ctx context.Context, page, size int) ([]*UserLoginHistory, *PageInfo, error) { cnt, err := ulh.Count(ctx) if err != nil { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index fa194b4..56e4ee0 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -45,5 +45,8 @@ type TaskRecord func(*sql.Selector) // User is the predicate function for user builders. type User func(*sql.Selector) +// UserIdentity is the predicate function for useridentity builders. +type UserIdentity func(*sql.Selector) + // UserLoginHistory is the predicate function for userloginhistory builders. type UserLoginHistory func(*sql.Selector) diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index 36513d6..b995480 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -19,6 +19,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/ent/schema" ) @@ -169,12 +170,16 @@ func init() { settingDescDisablePasswordLogin := settingFields[3].Descriptor() // setting.DefaultDisablePasswordLogin holds the default value on creation for the disable_password_login field. setting.DefaultDisablePasswordLogin = settingDescDisablePasswordLogin.Default.(bool) + // settingDescEnableDingtalkOauth is the schema descriptor for enable_dingtalk_oauth field. + settingDescEnableDingtalkOauth := settingFields[4].Descriptor() + // setting.DefaultEnableDingtalkOauth holds the default value on creation for the enable_dingtalk_oauth field. + setting.DefaultEnableDingtalkOauth = settingDescEnableDingtalkOauth.Default.(bool) // settingDescCreatedAt is the schema descriptor for created_at field. - settingDescCreatedAt := settingFields[4].Descriptor() + settingDescCreatedAt := settingFields[7].Descriptor() // setting.DefaultCreatedAt holds the default value on creation for the created_at field. setting.DefaultCreatedAt = settingDescCreatedAt.Default.(func() time.Time) // settingDescUpdatedAt is the schema descriptor for updated_at field. - settingDescUpdatedAt := settingFields[5].Descriptor() + settingDescUpdatedAt := settingFields[8].Descriptor() // setting.DefaultUpdatedAt holds the default value on creation for the updated_at field. setting.DefaultUpdatedAt = settingDescUpdatedAt.Default.(func() time.Time) // setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. @@ -209,18 +214,32 @@ func init() { taskrecord.UpdateDefaultUpdatedAt = taskrecordDescUpdatedAt.UpdateDefault.(func() time.Time) userFields := schema.User{}.Fields() _ = userFields + // userDescPlatform is the schema descriptor for platform field. + userDescPlatform := userFields[5].Descriptor() + // user.DefaultPlatform holds the default value on creation for the platform field. + user.DefaultPlatform = consts.UserPlatform(userDescPlatform.Default.(string)) // userDescStatus is the schema descriptor for status field. - userDescStatus := userFields[4].Descriptor() + userDescStatus := userFields[6].Descriptor() // user.DefaultStatus holds the default value on creation for the status field. user.DefaultStatus = consts.UserStatus(userDescStatus.Default.(string)) // userDescCreatedAt is the schema descriptor for created_at field. - userDescCreatedAt := userFields[5].Descriptor() + userDescCreatedAt := userFields[7].Descriptor() // user.DefaultCreatedAt holds the default value on creation for the created_at field. user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time) // userDescUpdatedAt is the schema descriptor for updated_at field. - userDescUpdatedAt := userFields[6].Descriptor() + userDescUpdatedAt := userFields[8].Descriptor() // user.DefaultUpdatedAt holds the default value on creation for the updated_at field. user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time) + useridentityFields := schema.UserIdentity{}.Fields() + _ = useridentityFields + // useridentityDescPlatform is the schema descriptor for platform field. + useridentityDescPlatform := useridentityFields[2].Descriptor() + // useridentity.DefaultPlatform holds the default value on creation for the platform field. + useridentity.DefaultPlatform = consts.UserPlatform(useridentityDescPlatform.Default.(string)) + // useridentityDescCreatedAt is the schema descriptor for created_at field. + useridentityDescCreatedAt := useridentityFields[8].Descriptor() + // useridentity.DefaultCreatedAt holds the default value on creation for the created_at field. + useridentity.DefaultCreatedAt = useridentityDescCreatedAt.Default.(func() time.Time) userloginhistoryFields := schema.UserLoginHistory{}.Fields() _ = userloginhistoryFields // userloginhistoryDescCreatedAt is the schema descriptor for created_at field. diff --git a/backend/db/setting.go b/backend/db/setting.go index 5f845cb..51bcc21 100644 --- a/backend/db/setting.go +++ b/backend/db/setting.go @@ -24,6 +24,12 @@ type Setting struct { ForceTwoFactorAuth bool `json:"force_two_factor_auth,omitempty"` // DisablePasswordLogin holds the value of the "disable_password_login" field. DisablePasswordLogin bool `json:"disable_password_login,omitempty"` + // EnableDingtalkOauth holds the value of the "enable_dingtalk_oauth" field. + EnableDingtalkOauth bool `json:"enable_dingtalk_oauth,omitempty"` + // DingtalkClientID holds the value of the "dingtalk_client_id" field. + DingtalkClientID string `json:"dingtalk_client_id,omitempty"` + // DingtalkClientSecret holds the value of the "dingtalk_client_secret" field. + DingtalkClientSecret string `json:"dingtalk_client_secret,omitempty"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at,omitempty"` // UpdatedAt holds the value of the "updated_at" field. @@ -36,8 +42,10 @@ func (*Setting) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case setting.FieldEnableSSO, setting.FieldForceTwoFactorAuth, setting.FieldDisablePasswordLogin: + case setting.FieldEnableSSO, setting.FieldForceTwoFactorAuth, setting.FieldDisablePasswordLogin, setting.FieldEnableDingtalkOauth: values[i] = new(sql.NullBool) + case setting.FieldDingtalkClientID, setting.FieldDingtalkClientSecret: + values[i] = new(sql.NullString) case setting.FieldCreatedAt, setting.FieldUpdatedAt: values[i] = new(sql.NullTime) case setting.FieldID: @@ -81,6 +89,24 @@ func (s *Setting) assignValues(columns []string, values []any) error { } else if value.Valid { s.DisablePasswordLogin = value.Bool } + case setting.FieldEnableDingtalkOauth: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field enable_dingtalk_oauth", values[i]) + } else if value.Valid { + s.EnableDingtalkOauth = value.Bool + } + case setting.FieldDingtalkClientID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field dingtalk_client_id", values[i]) + } else if value.Valid { + s.DingtalkClientID = value.String + } + case setting.FieldDingtalkClientSecret: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field dingtalk_client_secret", values[i]) + } else if value.Valid { + s.DingtalkClientSecret = value.String + } case setting.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field created_at", values[i]) @@ -138,6 +164,15 @@ func (s *Setting) String() string { builder.WriteString("disable_password_login=") builder.WriteString(fmt.Sprintf("%v", s.DisablePasswordLogin)) builder.WriteString(", ") + builder.WriteString("enable_dingtalk_oauth=") + builder.WriteString(fmt.Sprintf("%v", s.EnableDingtalkOauth)) + builder.WriteString(", ") + builder.WriteString("dingtalk_client_id=") + builder.WriteString(s.DingtalkClientID) + builder.WriteString(", ") + builder.WriteString("dingtalk_client_secret=") + builder.WriteString(s.DingtalkClientSecret) + builder.WriteString(", ") builder.WriteString("created_at=") builder.WriteString(s.CreatedAt.Format(time.ANSIC)) builder.WriteString(", ") diff --git a/backend/db/setting/setting.go b/backend/db/setting/setting.go index 3f036a2..6a8fd21 100644 --- a/backend/db/setting/setting.go +++ b/backend/db/setting/setting.go @@ -19,6 +19,12 @@ const ( FieldForceTwoFactorAuth = "force_two_factor_auth" // FieldDisablePasswordLogin holds the string denoting the disable_password_login field in the database. FieldDisablePasswordLogin = "disable_password_login" + // FieldEnableDingtalkOauth holds the string denoting the enable_dingtalk_oauth field in the database. + FieldEnableDingtalkOauth = "enable_dingtalk_oauth" + // FieldDingtalkClientID holds the string denoting the dingtalk_client_id field in the database. + FieldDingtalkClientID = "dingtalk_client_id" + // FieldDingtalkClientSecret holds the string denoting the dingtalk_client_secret field in the database. + FieldDingtalkClientSecret = "dingtalk_client_secret" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" // FieldUpdatedAt holds the string denoting the updated_at field in the database. @@ -33,6 +39,9 @@ var Columns = []string{ FieldEnableSSO, FieldForceTwoFactorAuth, FieldDisablePasswordLogin, + FieldEnableDingtalkOauth, + FieldDingtalkClientID, + FieldDingtalkClientSecret, FieldCreatedAt, FieldUpdatedAt, } @@ -54,6 +63,8 @@ var ( DefaultForceTwoFactorAuth bool // DefaultDisablePasswordLogin holds the default value on creation for the "disable_password_login" field. DefaultDisablePasswordLogin bool + // DefaultEnableDingtalkOauth holds the default value on creation for the "enable_dingtalk_oauth" field. + DefaultEnableDingtalkOauth bool // DefaultCreatedAt holds the default value on creation for the "created_at" field. DefaultCreatedAt func() time.Time // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. @@ -85,6 +96,21 @@ func ByDisablePasswordLogin(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldDisablePasswordLogin, opts...).ToFunc() } +// ByEnableDingtalkOauth orders the results by the enable_dingtalk_oauth field. +func ByEnableDingtalkOauth(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEnableDingtalkOauth, opts...).ToFunc() +} + +// ByDingtalkClientID orders the results by the dingtalk_client_id field. +func ByDingtalkClientID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDingtalkClientID, opts...).ToFunc() +} + +// ByDingtalkClientSecret orders the results by the dingtalk_client_secret field. +func ByDingtalkClientSecret(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDingtalkClientSecret, opts...).ToFunc() +} + // ByCreatedAt orders the results by the created_at field. func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() diff --git a/backend/db/setting/where.go b/backend/db/setting/where.go index 90e9461..b2db507 100644 --- a/backend/db/setting/where.go +++ b/backend/db/setting/where.go @@ -70,6 +70,21 @@ func DisablePasswordLogin(v bool) predicate.Setting { return predicate.Setting(sql.FieldEQ(FieldDisablePasswordLogin, v)) } +// EnableDingtalkOauth applies equality check predicate on the "enable_dingtalk_oauth" field. It's identical to EnableDingtalkOauthEQ. +func EnableDingtalkOauth(v bool) predicate.Setting { + return predicate.Setting(sql.FieldEQ(FieldEnableDingtalkOauth, v)) +} + +// DingtalkClientID applies equality check predicate on the "dingtalk_client_id" field. It's identical to DingtalkClientIDEQ. +func DingtalkClientID(v string) predicate.Setting { + return predicate.Setting(sql.FieldEQ(FieldDingtalkClientID, v)) +} + +// DingtalkClientSecret applies equality check predicate on the "dingtalk_client_secret" field. It's identical to DingtalkClientSecretEQ. +func DingtalkClientSecret(v string) predicate.Setting { + return predicate.Setting(sql.FieldEQ(FieldDingtalkClientSecret, v)) +} + // CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. func CreatedAt(v time.Time) predicate.Setting { return predicate.Setting(sql.FieldEQ(FieldCreatedAt, v)) @@ -110,6 +125,166 @@ func DisablePasswordLoginNEQ(v bool) predicate.Setting { return predicate.Setting(sql.FieldNEQ(FieldDisablePasswordLogin, v)) } +// EnableDingtalkOauthEQ applies the EQ predicate on the "enable_dingtalk_oauth" field. +func EnableDingtalkOauthEQ(v bool) predicate.Setting { + return predicate.Setting(sql.FieldEQ(FieldEnableDingtalkOauth, v)) +} + +// EnableDingtalkOauthNEQ applies the NEQ predicate on the "enable_dingtalk_oauth" field. +func EnableDingtalkOauthNEQ(v bool) predicate.Setting { + return predicate.Setting(sql.FieldNEQ(FieldEnableDingtalkOauth, v)) +} + +// DingtalkClientIDEQ applies the EQ predicate on the "dingtalk_client_id" field. +func DingtalkClientIDEQ(v string) predicate.Setting { + return predicate.Setting(sql.FieldEQ(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDNEQ applies the NEQ predicate on the "dingtalk_client_id" field. +func DingtalkClientIDNEQ(v string) predicate.Setting { + return predicate.Setting(sql.FieldNEQ(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDIn applies the In predicate on the "dingtalk_client_id" field. +func DingtalkClientIDIn(vs ...string) predicate.Setting { + return predicate.Setting(sql.FieldIn(FieldDingtalkClientID, vs...)) +} + +// DingtalkClientIDNotIn applies the NotIn predicate on the "dingtalk_client_id" field. +func DingtalkClientIDNotIn(vs ...string) predicate.Setting { + return predicate.Setting(sql.FieldNotIn(FieldDingtalkClientID, vs...)) +} + +// DingtalkClientIDGT applies the GT predicate on the "dingtalk_client_id" field. +func DingtalkClientIDGT(v string) predicate.Setting { + return predicate.Setting(sql.FieldGT(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDGTE applies the GTE predicate on the "dingtalk_client_id" field. +func DingtalkClientIDGTE(v string) predicate.Setting { + return predicate.Setting(sql.FieldGTE(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDLT applies the LT predicate on the "dingtalk_client_id" field. +func DingtalkClientIDLT(v string) predicate.Setting { + return predicate.Setting(sql.FieldLT(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDLTE applies the LTE predicate on the "dingtalk_client_id" field. +func DingtalkClientIDLTE(v string) predicate.Setting { + return predicate.Setting(sql.FieldLTE(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDContains applies the Contains predicate on the "dingtalk_client_id" field. +func DingtalkClientIDContains(v string) predicate.Setting { + return predicate.Setting(sql.FieldContains(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDHasPrefix applies the HasPrefix predicate on the "dingtalk_client_id" field. +func DingtalkClientIDHasPrefix(v string) predicate.Setting { + return predicate.Setting(sql.FieldHasPrefix(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDHasSuffix applies the HasSuffix predicate on the "dingtalk_client_id" field. +func DingtalkClientIDHasSuffix(v string) predicate.Setting { + return predicate.Setting(sql.FieldHasSuffix(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDIsNil applies the IsNil predicate on the "dingtalk_client_id" field. +func DingtalkClientIDIsNil() predicate.Setting { + return predicate.Setting(sql.FieldIsNull(FieldDingtalkClientID)) +} + +// DingtalkClientIDNotNil applies the NotNil predicate on the "dingtalk_client_id" field. +func DingtalkClientIDNotNil() predicate.Setting { + return predicate.Setting(sql.FieldNotNull(FieldDingtalkClientID)) +} + +// DingtalkClientIDEqualFold applies the EqualFold predicate on the "dingtalk_client_id" field. +func DingtalkClientIDEqualFold(v string) predicate.Setting { + return predicate.Setting(sql.FieldEqualFold(FieldDingtalkClientID, v)) +} + +// DingtalkClientIDContainsFold applies the ContainsFold predicate on the "dingtalk_client_id" field. +func DingtalkClientIDContainsFold(v string) predicate.Setting { + return predicate.Setting(sql.FieldContainsFold(FieldDingtalkClientID, v)) +} + +// DingtalkClientSecretEQ applies the EQ predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretEQ(v string) predicate.Setting { + return predicate.Setting(sql.FieldEQ(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretNEQ applies the NEQ predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretNEQ(v string) predicate.Setting { + return predicate.Setting(sql.FieldNEQ(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretIn applies the In predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretIn(vs ...string) predicate.Setting { + return predicate.Setting(sql.FieldIn(FieldDingtalkClientSecret, vs...)) +} + +// DingtalkClientSecretNotIn applies the NotIn predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretNotIn(vs ...string) predicate.Setting { + return predicate.Setting(sql.FieldNotIn(FieldDingtalkClientSecret, vs...)) +} + +// DingtalkClientSecretGT applies the GT predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretGT(v string) predicate.Setting { + return predicate.Setting(sql.FieldGT(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretGTE applies the GTE predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretGTE(v string) predicate.Setting { + return predicate.Setting(sql.FieldGTE(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretLT applies the LT predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretLT(v string) predicate.Setting { + return predicate.Setting(sql.FieldLT(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretLTE applies the LTE predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretLTE(v string) predicate.Setting { + return predicate.Setting(sql.FieldLTE(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretContains applies the Contains predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretContains(v string) predicate.Setting { + return predicate.Setting(sql.FieldContains(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretHasPrefix applies the HasPrefix predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretHasPrefix(v string) predicate.Setting { + return predicate.Setting(sql.FieldHasPrefix(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretHasSuffix applies the HasSuffix predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretHasSuffix(v string) predicate.Setting { + return predicate.Setting(sql.FieldHasSuffix(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretIsNil applies the IsNil predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretIsNil() predicate.Setting { + return predicate.Setting(sql.FieldIsNull(FieldDingtalkClientSecret)) +} + +// DingtalkClientSecretNotNil applies the NotNil predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretNotNil() predicate.Setting { + return predicate.Setting(sql.FieldNotNull(FieldDingtalkClientSecret)) +} + +// DingtalkClientSecretEqualFold applies the EqualFold predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretEqualFold(v string) predicate.Setting { + return predicate.Setting(sql.FieldEqualFold(FieldDingtalkClientSecret, v)) +} + +// DingtalkClientSecretContainsFold applies the ContainsFold predicate on the "dingtalk_client_secret" field. +func DingtalkClientSecretContainsFold(v string) predicate.Setting { + return predicate.Setting(sql.FieldContainsFold(FieldDingtalkClientSecret, v)) +} + // CreatedAtEQ applies the EQ predicate on the "created_at" field. func CreatedAtEQ(v time.Time) predicate.Setting { return predicate.Setting(sql.FieldEQ(FieldCreatedAt, v)) diff --git a/backend/db/setting_create.go b/backend/db/setting_create.go index 6f2c293..069217b 100644 --- a/backend/db/setting_create.go +++ b/backend/db/setting_create.go @@ -66,6 +66,48 @@ func (sc *SettingCreate) SetNillableDisablePasswordLogin(b *bool) *SettingCreate return sc } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (sc *SettingCreate) SetEnableDingtalkOauth(b bool) *SettingCreate { + sc.mutation.SetEnableDingtalkOauth(b) + return sc +} + +// SetNillableEnableDingtalkOauth sets the "enable_dingtalk_oauth" field if the given value is not nil. +func (sc *SettingCreate) SetNillableEnableDingtalkOauth(b *bool) *SettingCreate { + if b != nil { + sc.SetEnableDingtalkOauth(*b) + } + return sc +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (sc *SettingCreate) SetDingtalkClientID(s string) *SettingCreate { + sc.mutation.SetDingtalkClientID(s) + return sc +} + +// SetNillableDingtalkClientID sets the "dingtalk_client_id" field if the given value is not nil. +func (sc *SettingCreate) SetNillableDingtalkClientID(s *string) *SettingCreate { + if s != nil { + sc.SetDingtalkClientID(*s) + } + return sc +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (sc *SettingCreate) SetDingtalkClientSecret(s string) *SettingCreate { + sc.mutation.SetDingtalkClientSecret(s) + return sc +} + +// SetNillableDingtalkClientSecret sets the "dingtalk_client_secret" field if the given value is not nil. +func (sc *SettingCreate) SetNillableDingtalkClientSecret(s *string) *SettingCreate { + if s != nil { + sc.SetDingtalkClientSecret(*s) + } + return sc +} + // SetCreatedAt sets the "created_at" field. func (sc *SettingCreate) SetCreatedAt(t time.Time) *SettingCreate { sc.mutation.SetCreatedAt(t) @@ -147,6 +189,10 @@ func (sc *SettingCreate) defaults() { v := setting.DefaultDisablePasswordLogin sc.mutation.SetDisablePasswordLogin(v) } + if _, ok := sc.mutation.EnableDingtalkOauth(); !ok { + v := setting.DefaultEnableDingtalkOauth + sc.mutation.SetEnableDingtalkOauth(v) + } if _, ok := sc.mutation.CreatedAt(); !ok { v := setting.DefaultCreatedAt() sc.mutation.SetCreatedAt(v) @@ -168,6 +214,9 @@ func (sc *SettingCreate) check() error { if _, ok := sc.mutation.DisablePasswordLogin(); !ok { return &ValidationError{Name: "disable_password_login", err: errors.New(`db: missing required field "Setting.disable_password_login"`)} } + if _, ok := sc.mutation.EnableDingtalkOauth(); !ok { + return &ValidationError{Name: "enable_dingtalk_oauth", err: errors.New(`db: missing required field "Setting.enable_dingtalk_oauth"`)} + } if _, ok := sc.mutation.CreatedAt(); !ok { return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Setting.created_at"`)} } @@ -222,6 +271,18 @@ func (sc *SettingCreate) createSpec() (*Setting, *sqlgraph.CreateSpec) { _spec.SetField(setting.FieldDisablePasswordLogin, field.TypeBool, value) _node.DisablePasswordLogin = value } + if value, ok := sc.mutation.EnableDingtalkOauth(); ok { + _spec.SetField(setting.FieldEnableDingtalkOauth, field.TypeBool, value) + _node.EnableDingtalkOauth = value + } + if value, ok := sc.mutation.DingtalkClientID(); ok { + _spec.SetField(setting.FieldDingtalkClientID, field.TypeString, value) + _node.DingtalkClientID = value + } + if value, ok := sc.mutation.DingtalkClientSecret(); ok { + _spec.SetField(setting.FieldDingtalkClientSecret, field.TypeString, value) + _node.DingtalkClientSecret = value + } if value, ok := sc.mutation.CreatedAt(); ok { _spec.SetField(setting.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value @@ -318,6 +379,54 @@ func (u *SettingUpsert) UpdateDisablePasswordLogin() *SettingUpsert { return u } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (u *SettingUpsert) SetEnableDingtalkOauth(v bool) *SettingUpsert { + u.Set(setting.FieldEnableDingtalkOauth, v) + return u +} + +// UpdateEnableDingtalkOauth sets the "enable_dingtalk_oauth" field to the value that was provided on create. +func (u *SettingUpsert) UpdateEnableDingtalkOauth() *SettingUpsert { + u.SetExcluded(setting.FieldEnableDingtalkOauth) + return u +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (u *SettingUpsert) SetDingtalkClientID(v string) *SettingUpsert { + u.Set(setting.FieldDingtalkClientID, v) + return u +} + +// UpdateDingtalkClientID sets the "dingtalk_client_id" field to the value that was provided on create. +func (u *SettingUpsert) UpdateDingtalkClientID() *SettingUpsert { + u.SetExcluded(setting.FieldDingtalkClientID) + return u +} + +// ClearDingtalkClientID clears the value of the "dingtalk_client_id" field. +func (u *SettingUpsert) ClearDingtalkClientID() *SettingUpsert { + u.SetNull(setting.FieldDingtalkClientID) + return u +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (u *SettingUpsert) SetDingtalkClientSecret(v string) *SettingUpsert { + u.Set(setting.FieldDingtalkClientSecret, v) + return u +} + +// UpdateDingtalkClientSecret sets the "dingtalk_client_secret" field to the value that was provided on create. +func (u *SettingUpsert) UpdateDingtalkClientSecret() *SettingUpsert { + u.SetExcluded(setting.FieldDingtalkClientSecret) + return u +} + +// ClearDingtalkClientSecret clears the value of the "dingtalk_client_secret" field. +func (u *SettingUpsert) ClearDingtalkClientSecret() *SettingUpsert { + u.SetNull(setting.FieldDingtalkClientSecret) + return u +} + // SetCreatedAt sets the "created_at" field. func (u *SettingUpsert) SetCreatedAt(v time.Time) *SettingUpsert { u.Set(setting.FieldCreatedAt, v) @@ -432,6 +541,62 @@ func (u *SettingUpsertOne) UpdateDisablePasswordLogin() *SettingUpsertOne { }) } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (u *SettingUpsertOne) SetEnableDingtalkOauth(v bool) *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.SetEnableDingtalkOauth(v) + }) +} + +// UpdateEnableDingtalkOauth sets the "enable_dingtalk_oauth" field to the value that was provided on create. +func (u *SettingUpsertOne) UpdateEnableDingtalkOauth() *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.UpdateEnableDingtalkOauth() + }) +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (u *SettingUpsertOne) SetDingtalkClientID(v string) *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.SetDingtalkClientID(v) + }) +} + +// UpdateDingtalkClientID sets the "dingtalk_client_id" field to the value that was provided on create. +func (u *SettingUpsertOne) UpdateDingtalkClientID() *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.UpdateDingtalkClientID() + }) +} + +// ClearDingtalkClientID clears the value of the "dingtalk_client_id" field. +func (u *SettingUpsertOne) ClearDingtalkClientID() *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.ClearDingtalkClientID() + }) +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (u *SettingUpsertOne) SetDingtalkClientSecret(v string) *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.SetDingtalkClientSecret(v) + }) +} + +// UpdateDingtalkClientSecret sets the "dingtalk_client_secret" field to the value that was provided on create. +func (u *SettingUpsertOne) UpdateDingtalkClientSecret() *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.UpdateDingtalkClientSecret() + }) +} + +// ClearDingtalkClientSecret clears the value of the "dingtalk_client_secret" field. +func (u *SettingUpsertOne) ClearDingtalkClientSecret() *SettingUpsertOne { + return u.Update(func(s *SettingUpsert) { + s.ClearDingtalkClientSecret() + }) +} + // SetCreatedAt sets the "created_at" field. func (u *SettingUpsertOne) SetCreatedAt(v time.Time) *SettingUpsertOne { return u.Update(func(s *SettingUpsert) { @@ -717,6 +882,62 @@ func (u *SettingUpsertBulk) UpdateDisablePasswordLogin() *SettingUpsertBulk { }) } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (u *SettingUpsertBulk) SetEnableDingtalkOauth(v bool) *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.SetEnableDingtalkOauth(v) + }) +} + +// UpdateEnableDingtalkOauth sets the "enable_dingtalk_oauth" field to the value that was provided on create. +func (u *SettingUpsertBulk) UpdateEnableDingtalkOauth() *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.UpdateEnableDingtalkOauth() + }) +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (u *SettingUpsertBulk) SetDingtalkClientID(v string) *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.SetDingtalkClientID(v) + }) +} + +// UpdateDingtalkClientID sets the "dingtalk_client_id" field to the value that was provided on create. +func (u *SettingUpsertBulk) UpdateDingtalkClientID() *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.UpdateDingtalkClientID() + }) +} + +// ClearDingtalkClientID clears the value of the "dingtalk_client_id" field. +func (u *SettingUpsertBulk) ClearDingtalkClientID() *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.ClearDingtalkClientID() + }) +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (u *SettingUpsertBulk) SetDingtalkClientSecret(v string) *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.SetDingtalkClientSecret(v) + }) +} + +// UpdateDingtalkClientSecret sets the "dingtalk_client_secret" field to the value that was provided on create. +func (u *SettingUpsertBulk) UpdateDingtalkClientSecret() *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.UpdateDingtalkClientSecret() + }) +} + +// ClearDingtalkClientSecret clears the value of the "dingtalk_client_secret" field. +func (u *SettingUpsertBulk) ClearDingtalkClientSecret() *SettingUpsertBulk { + return u.Update(func(s *SettingUpsert) { + s.ClearDingtalkClientSecret() + }) +} + // SetCreatedAt sets the "created_at" field. func (u *SettingUpsertBulk) SetCreatedAt(v time.Time) *SettingUpsertBulk { return u.Update(func(s *SettingUpsert) { diff --git a/backend/db/setting_update.go b/backend/db/setting_update.go index 5028777..6d57184 100644 --- a/backend/db/setting_update.go +++ b/backend/db/setting_update.go @@ -71,6 +71,60 @@ func (su *SettingUpdate) SetNillableDisablePasswordLogin(b *bool) *SettingUpdate return su } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (su *SettingUpdate) SetEnableDingtalkOauth(b bool) *SettingUpdate { + su.mutation.SetEnableDingtalkOauth(b) + return su +} + +// SetNillableEnableDingtalkOauth sets the "enable_dingtalk_oauth" field if the given value is not nil. +func (su *SettingUpdate) SetNillableEnableDingtalkOauth(b *bool) *SettingUpdate { + if b != nil { + su.SetEnableDingtalkOauth(*b) + } + return su +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (su *SettingUpdate) SetDingtalkClientID(s string) *SettingUpdate { + su.mutation.SetDingtalkClientID(s) + return su +} + +// SetNillableDingtalkClientID sets the "dingtalk_client_id" field if the given value is not nil. +func (su *SettingUpdate) SetNillableDingtalkClientID(s *string) *SettingUpdate { + if s != nil { + su.SetDingtalkClientID(*s) + } + return su +} + +// ClearDingtalkClientID clears the value of the "dingtalk_client_id" field. +func (su *SettingUpdate) ClearDingtalkClientID() *SettingUpdate { + su.mutation.ClearDingtalkClientID() + return su +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (su *SettingUpdate) SetDingtalkClientSecret(s string) *SettingUpdate { + su.mutation.SetDingtalkClientSecret(s) + return su +} + +// SetNillableDingtalkClientSecret sets the "dingtalk_client_secret" field if the given value is not nil. +func (su *SettingUpdate) SetNillableDingtalkClientSecret(s *string) *SettingUpdate { + if s != nil { + su.SetDingtalkClientSecret(*s) + } + return su +} + +// ClearDingtalkClientSecret clears the value of the "dingtalk_client_secret" field. +func (su *SettingUpdate) ClearDingtalkClientSecret() *SettingUpdate { + su.mutation.ClearDingtalkClientSecret() + return su +} + // SetCreatedAt sets the "created_at" field. func (su *SettingUpdate) SetCreatedAt(t time.Time) *SettingUpdate { su.mutation.SetCreatedAt(t) @@ -156,6 +210,21 @@ func (su *SettingUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := su.mutation.DisablePasswordLogin(); ok { _spec.SetField(setting.FieldDisablePasswordLogin, field.TypeBool, value) } + if value, ok := su.mutation.EnableDingtalkOauth(); ok { + _spec.SetField(setting.FieldEnableDingtalkOauth, field.TypeBool, value) + } + if value, ok := su.mutation.DingtalkClientID(); ok { + _spec.SetField(setting.FieldDingtalkClientID, field.TypeString, value) + } + if su.mutation.DingtalkClientIDCleared() { + _spec.ClearField(setting.FieldDingtalkClientID, field.TypeString) + } + if value, ok := su.mutation.DingtalkClientSecret(); ok { + _spec.SetField(setting.FieldDingtalkClientSecret, field.TypeString, value) + } + if su.mutation.DingtalkClientSecretCleared() { + _spec.ClearField(setting.FieldDingtalkClientSecret, field.TypeString) + } if value, ok := su.mutation.CreatedAt(); ok { _spec.SetField(setting.FieldCreatedAt, field.TypeTime, value) } @@ -226,6 +295,60 @@ func (suo *SettingUpdateOne) SetNillableDisablePasswordLogin(b *bool) *SettingUp return suo } +// SetEnableDingtalkOauth sets the "enable_dingtalk_oauth" field. +func (suo *SettingUpdateOne) SetEnableDingtalkOauth(b bool) *SettingUpdateOne { + suo.mutation.SetEnableDingtalkOauth(b) + return suo +} + +// SetNillableEnableDingtalkOauth sets the "enable_dingtalk_oauth" field if the given value is not nil. +func (suo *SettingUpdateOne) SetNillableEnableDingtalkOauth(b *bool) *SettingUpdateOne { + if b != nil { + suo.SetEnableDingtalkOauth(*b) + } + return suo +} + +// SetDingtalkClientID sets the "dingtalk_client_id" field. +func (suo *SettingUpdateOne) SetDingtalkClientID(s string) *SettingUpdateOne { + suo.mutation.SetDingtalkClientID(s) + return suo +} + +// SetNillableDingtalkClientID sets the "dingtalk_client_id" field if the given value is not nil. +func (suo *SettingUpdateOne) SetNillableDingtalkClientID(s *string) *SettingUpdateOne { + if s != nil { + suo.SetDingtalkClientID(*s) + } + return suo +} + +// ClearDingtalkClientID clears the value of the "dingtalk_client_id" field. +func (suo *SettingUpdateOne) ClearDingtalkClientID() *SettingUpdateOne { + suo.mutation.ClearDingtalkClientID() + return suo +} + +// SetDingtalkClientSecret sets the "dingtalk_client_secret" field. +func (suo *SettingUpdateOne) SetDingtalkClientSecret(s string) *SettingUpdateOne { + suo.mutation.SetDingtalkClientSecret(s) + return suo +} + +// SetNillableDingtalkClientSecret sets the "dingtalk_client_secret" field if the given value is not nil. +func (suo *SettingUpdateOne) SetNillableDingtalkClientSecret(s *string) *SettingUpdateOne { + if s != nil { + suo.SetDingtalkClientSecret(*s) + } + return suo +} + +// ClearDingtalkClientSecret clears the value of the "dingtalk_client_secret" field. +func (suo *SettingUpdateOne) ClearDingtalkClientSecret() *SettingUpdateOne { + suo.mutation.ClearDingtalkClientSecret() + return suo +} + // SetCreatedAt sets the "created_at" field. func (suo *SettingUpdateOne) SetCreatedAt(t time.Time) *SettingUpdateOne { suo.mutation.SetCreatedAt(t) @@ -341,6 +464,21 @@ func (suo *SettingUpdateOne) sqlSave(ctx context.Context) (_node *Setting, err e if value, ok := suo.mutation.DisablePasswordLogin(); ok { _spec.SetField(setting.FieldDisablePasswordLogin, field.TypeBool, value) } + if value, ok := suo.mutation.EnableDingtalkOauth(); ok { + _spec.SetField(setting.FieldEnableDingtalkOauth, field.TypeBool, value) + } + if value, ok := suo.mutation.DingtalkClientID(); ok { + _spec.SetField(setting.FieldDingtalkClientID, field.TypeString, value) + } + if suo.mutation.DingtalkClientIDCleared() { + _spec.ClearField(setting.FieldDingtalkClientID, field.TypeString) + } + if value, ok := suo.mutation.DingtalkClientSecret(); ok { + _spec.SetField(setting.FieldDingtalkClientSecret, field.TypeString, value) + } + if suo.mutation.DingtalkClientSecretCleared() { + _spec.ClearField(setting.FieldDingtalkClientSecret, field.TypeString) + } if value, ok := suo.mutation.CreatedAt(); ok { _spec.SetField(setting.FieldCreatedAt, field.TypeTime, value) } diff --git a/backend/db/tx.go b/backend/db/tx.go index d0914d3..0053e14 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -40,6 +40,8 @@ type Tx struct { TaskRecord *TaskRecordClient // User is the client for interacting with the User builders. User *UserClient + // UserIdentity is the client for interacting with the UserIdentity builders. + UserIdentity *UserIdentityClient // UserLoginHistory is the client for interacting with the UserLoginHistory builders. UserLoginHistory *UserLoginHistoryClient @@ -186,6 +188,7 @@ func (tx *Tx) init() { tx.Task = NewTaskClient(tx.config) tx.TaskRecord = NewTaskRecordClient(tx.config) tx.User = NewUserClient(tx.config) + tx.UserIdentity = NewUserIdentityClient(tx.config) tx.UserLoginHistory = NewUserLoginHistoryClient(tx.config) } diff --git a/backend/db/user.go b/backend/db/user.go index 667fd02..d62628b 100644 --- a/backend/db/user.go +++ b/backend/db/user.go @@ -25,6 +25,10 @@ type User struct { Password string `json:"password,omitempty"` // Email holds the value of the "email" field. Email string `json:"email,omitempty"` + // AvatarURL holds the value of the "avatar_url" field. + AvatarURL string `json:"avatar_url,omitempty"` + // Platform holds the value of the "platform" field. + Platform consts.UserPlatform `json:"platform,omitempty"` // Status holds the value of the "status" field. Status consts.UserStatus `json:"status,omitempty"` // CreatedAt holds the value of the "created_at" field. @@ -45,9 +49,11 @@ type UserEdges struct { Models []*Model `json:"models,omitempty"` // Tasks holds the value of the tasks edge. Tasks []*Task `json:"tasks,omitempty"` + // Identities holds the value of the identities edge. + Identities []*UserIdentity `json:"identities,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [3]bool + loadedTypes [4]bool } // LoginHistoriesOrErr returns the LoginHistories value or an error if the edge @@ -77,12 +83,21 @@ func (e UserEdges) TasksOrErr() ([]*Task, error) { return nil, &NotLoadedError{edge: "tasks"} } +// IdentitiesOrErr returns the Identities value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) IdentitiesOrErr() ([]*UserIdentity, error) { + if e.loadedTypes[3] { + return e.Identities, nil + } + return nil, &NotLoadedError{edge: "identities"} +} + // 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.FieldUsername, user.FieldPassword, user.FieldEmail, user.FieldStatus: + case user.FieldUsername, user.FieldPassword, user.FieldEmail, user.FieldAvatarURL, user.FieldPlatform, user.FieldStatus: values[i] = new(sql.NullString) case user.FieldCreatedAt, user.FieldUpdatedAt: values[i] = new(sql.NullTime) @@ -127,6 +142,18 @@ func (u *User) assignValues(columns []string, values []any) error { } else if value.Valid { u.Email = value.String } + case user.FieldAvatarURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field avatar_url", values[i]) + } else if value.Valid { + u.AvatarURL = value.String + } + case user.FieldPlatform: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field platform", values[i]) + } else if value.Valid { + u.Platform = consts.UserPlatform(value.String) + } case user.FieldStatus: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field status", values[i]) @@ -173,6 +200,11 @@ func (u *User) QueryTasks() *TaskQuery { return NewUserClient(u.config).QueryTasks(u) } +// QueryIdentities queries the "identities" edge of the User entity. +func (u *User) QueryIdentities() *UserIdentityQuery { + return NewUserClient(u.config).QueryIdentities(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. @@ -205,6 +237,12 @@ func (u *User) String() string { builder.WriteString("email=") builder.WriteString(u.Email) builder.WriteString(", ") + builder.WriteString("avatar_url=") + builder.WriteString(u.AvatarURL) + builder.WriteString(", ") + builder.WriteString("platform=") + builder.WriteString(fmt.Sprintf("%v", u.Platform)) + builder.WriteString(", ") builder.WriteString("status=") builder.WriteString(fmt.Sprintf("%v", u.Status)) builder.WriteString(", ") diff --git a/backend/db/user/user.go b/backend/db/user/user.go index 5ddbc56..29f0043 100644 --- a/backend/db/user/user.go +++ b/backend/db/user/user.go @@ -21,6 +21,10 @@ const ( FieldPassword = "password" // FieldEmail holds the string denoting the email field in the database. FieldEmail = "email" + // FieldAvatarURL holds the string denoting the avatar_url field in the database. + FieldAvatarURL = "avatar_url" + // FieldPlatform holds the string denoting the platform field in the database. + FieldPlatform = "platform" // FieldStatus holds the string denoting the status field in the database. FieldStatus = "status" // FieldCreatedAt holds the string denoting the created_at field in the database. @@ -33,6 +37,8 @@ const ( EdgeModels = "models" // EdgeTasks holds the string denoting the tasks edge name in mutations. EdgeTasks = "tasks" + // EdgeIdentities holds the string denoting the identities edge name in mutations. + EdgeIdentities = "identities" // Table holds the table name of the user in the database. Table = "users" // LoginHistoriesTable is the table that holds the login_histories relation/edge. @@ -56,6 +62,13 @@ const ( TasksInverseTable = "tasks" // TasksColumn is the table column denoting the tasks relation/edge. TasksColumn = "user_id" + // IdentitiesTable is the table that holds the identities relation/edge. + IdentitiesTable = "user_identities" + // IdentitiesInverseTable is the table name for the UserIdentity entity. + // It exists in this package in order to avoid circular dependency with the "useridentity" package. + IdentitiesInverseTable = "user_identities" + // IdentitiesColumn is the table column denoting the identities relation/edge. + IdentitiesColumn = "user_id" ) // Columns holds all SQL columns for user fields. @@ -64,6 +77,8 @@ var Columns = []string{ FieldUsername, FieldPassword, FieldEmail, + FieldAvatarURL, + FieldPlatform, FieldStatus, FieldCreatedAt, FieldUpdatedAt, @@ -80,6 +95,8 @@ func ValidColumn(column string) bool { } var ( + // DefaultPlatform holds the default value on creation for the "platform" field. + DefaultPlatform consts.UserPlatform // DefaultStatus holds the default value on creation for the "status" field. DefaultStatus consts.UserStatus // DefaultCreatedAt holds the default value on creation for the "created_at" field. @@ -111,6 +128,16 @@ func ByEmail(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldEmail, opts...).ToFunc() } +// ByAvatarURL orders the results by the avatar_url field. +func ByAvatarURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAvatarURL, opts...).ToFunc() +} + +// ByPlatform orders the results by the platform field. +func ByPlatform(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPlatform, opts...).ToFunc() +} + // ByStatus orders the results by the status field. func ByStatus(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldStatus, opts...).ToFunc() @@ -167,6 +194,20 @@ func ByTasks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newTasksStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByIdentitiesCount orders the results by identities count. +func ByIdentitiesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newIdentitiesStep(), opts...) + } +} + +// ByIdentities orders the results by identities terms. +func ByIdentities(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newIdentitiesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newLoginHistoriesStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -188,3 +229,10 @@ func newTasksStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn), ) } +func newIdentitiesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(IdentitiesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, IdentitiesTable, IdentitiesColumn), + ) +} diff --git a/backend/db/user/where.go b/backend/db/user/where.go index 25e0816..92b7ff4 100644 --- a/backend/db/user/where.go +++ b/backend/db/user/where.go @@ -72,6 +72,17 @@ func Email(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldEmail, v)) } +// AvatarURL applies equality check predicate on the "avatar_url" field. It's identical to AvatarURLEQ. +func AvatarURL(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldAvatarURL, v)) +} + +// Platform applies equality check predicate on the "platform" field. It's identical to PlatformEQ. +func Platform(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldEQ(FieldPlatform, vc)) +} + // Status applies equality check predicate on the "status" field. It's identical to StatusEQ. func Status(v consts.UserStatus) predicate.User { vc := string(v) @@ -143,6 +154,16 @@ func UsernameHasSuffix(v string) predicate.User { return predicate.User(sql.FieldHasSuffix(FieldUsername, v)) } +// UsernameIsNil applies the IsNil predicate on the "username" field. +func UsernameIsNil() predicate.User { + return predicate.User(sql.FieldIsNull(FieldUsername)) +} + +// UsernameNotNil applies the NotNil predicate on the "username" field. +func UsernameNotNil() predicate.User { + return predicate.User(sql.FieldNotNull(FieldUsername)) +} + // UsernameEqualFold applies the EqualFold predicate on the "username" field. func UsernameEqualFold(v string) predicate.User { return predicate.User(sql.FieldEqualFold(FieldUsername, v)) @@ -208,6 +229,16 @@ func PasswordHasSuffix(v string) predicate.User { return predicate.User(sql.FieldHasSuffix(FieldPassword, v)) } +// PasswordIsNil applies the IsNil predicate on the "password" field. +func PasswordIsNil() predicate.User { + return predicate.User(sql.FieldIsNull(FieldPassword)) +} + +// PasswordNotNil applies the NotNil predicate on the "password" field. +func PasswordNotNil() predicate.User { + return predicate.User(sql.FieldNotNull(FieldPassword)) +} + // PasswordEqualFold applies the EqualFold predicate on the "password" field. func PasswordEqualFold(v string) predicate.User { return predicate.User(sql.FieldEqualFold(FieldPassword, v)) @@ -273,6 +304,16 @@ func EmailHasSuffix(v string) predicate.User { return predicate.User(sql.FieldHasSuffix(FieldEmail, v)) } +// EmailIsNil applies the IsNil predicate on the "email" field. +func EmailIsNil() predicate.User { + return predicate.User(sql.FieldIsNull(FieldEmail)) +} + +// EmailNotNil applies the NotNil predicate on the "email" field. +func EmailNotNil() predicate.User { + return predicate.User(sql.FieldNotNull(FieldEmail)) +} + // EmailEqualFold applies the EqualFold predicate on the "email" field. func EmailEqualFold(v string) predicate.User { return predicate.User(sql.FieldEqualFold(FieldEmail, v)) @@ -283,6 +324,165 @@ func EmailContainsFold(v string) predicate.User { return predicate.User(sql.FieldContainsFold(FieldEmail, v)) } +// AvatarURLEQ applies the EQ predicate on the "avatar_url" field. +func AvatarURLEQ(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldAvatarURL, v)) +} + +// AvatarURLNEQ applies the NEQ predicate on the "avatar_url" field. +func AvatarURLNEQ(v string) predicate.User { + return predicate.User(sql.FieldNEQ(FieldAvatarURL, v)) +} + +// AvatarURLIn applies the In predicate on the "avatar_url" field. +func AvatarURLIn(vs ...string) predicate.User { + return predicate.User(sql.FieldIn(FieldAvatarURL, vs...)) +} + +// AvatarURLNotIn applies the NotIn predicate on the "avatar_url" field. +func AvatarURLNotIn(vs ...string) predicate.User { + return predicate.User(sql.FieldNotIn(FieldAvatarURL, vs...)) +} + +// AvatarURLGT applies the GT predicate on the "avatar_url" field. +func AvatarURLGT(v string) predicate.User { + return predicate.User(sql.FieldGT(FieldAvatarURL, v)) +} + +// AvatarURLGTE applies the GTE predicate on the "avatar_url" field. +func AvatarURLGTE(v string) predicate.User { + return predicate.User(sql.FieldGTE(FieldAvatarURL, v)) +} + +// AvatarURLLT applies the LT predicate on the "avatar_url" field. +func AvatarURLLT(v string) predicate.User { + return predicate.User(sql.FieldLT(FieldAvatarURL, v)) +} + +// AvatarURLLTE applies the LTE predicate on the "avatar_url" field. +func AvatarURLLTE(v string) predicate.User { + return predicate.User(sql.FieldLTE(FieldAvatarURL, v)) +} + +// AvatarURLContains applies the Contains predicate on the "avatar_url" field. +func AvatarURLContains(v string) predicate.User { + return predicate.User(sql.FieldContains(FieldAvatarURL, v)) +} + +// AvatarURLHasPrefix applies the HasPrefix predicate on the "avatar_url" field. +func AvatarURLHasPrefix(v string) predicate.User { + return predicate.User(sql.FieldHasPrefix(FieldAvatarURL, v)) +} + +// AvatarURLHasSuffix applies the HasSuffix predicate on the "avatar_url" field. +func AvatarURLHasSuffix(v string) predicate.User { + return predicate.User(sql.FieldHasSuffix(FieldAvatarURL, v)) +} + +// AvatarURLIsNil applies the IsNil predicate on the "avatar_url" field. +func AvatarURLIsNil() predicate.User { + return predicate.User(sql.FieldIsNull(FieldAvatarURL)) +} + +// AvatarURLNotNil applies the NotNil predicate on the "avatar_url" field. +func AvatarURLNotNil() predicate.User { + return predicate.User(sql.FieldNotNull(FieldAvatarURL)) +} + +// AvatarURLEqualFold applies the EqualFold predicate on the "avatar_url" field. +func AvatarURLEqualFold(v string) predicate.User { + return predicate.User(sql.FieldEqualFold(FieldAvatarURL, v)) +} + +// AvatarURLContainsFold applies the ContainsFold predicate on the "avatar_url" field. +func AvatarURLContainsFold(v string) predicate.User { + return predicate.User(sql.FieldContainsFold(FieldAvatarURL, v)) +} + +// PlatformEQ applies the EQ predicate on the "platform" field. +func PlatformEQ(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldEQ(FieldPlatform, vc)) +} + +// PlatformNEQ applies the NEQ predicate on the "platform" field. +func PlatformNEQ(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldNEQ(FieldPlatform, vc)) +} + +// PlatformIn applies the In predicate on the "platform" field. +func PlatformIn(vs ...consts.UserPlatform) predicate.User { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.User(sql.FieldIn(FieldPlatform, v...)) +} + +// PlatformNotIn applies the NotIn predicate on the "platform" field. +func PlatformNotIn(vs ...consts.UserPlatform) predicate.User { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.User(sql.FieldNotIn(FieldPlatform, v...)) +} + +// PlatformGT applies the GT predicate on the "platform" field. +func PlatformGT(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldGT(FieldPlatform, vc)) +} + +// PlatformGTE applies the GTE predicate on the "platform" field. +func PlatformGTE(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldGTE(FieldPlatform, vc)) +} + +// PlatformLT applies the LT predicate on the "platform" field. +func PlatformLT(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldLT(FieldPlatform, vc)) +} + +// PlatformLTE applies the LTE predicate on the "platform" field. +func PlatformLTE(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldLTE(FieldPlatform, vc)) +} + +// PlatformContains applies the Contains predicate on the "platform" field. +func PlatformContains(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldContains(FieldPlatform, vc)) +} + +// PlatformHasPrefix applies the HasPrefix predicate on the "platform" field. +func PlatformHasPrefix(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldHasPrefix(FieldPlatform, vc)) +} + +// PlatformHasSuffix applies the HasSuffix predicate on the "platform" field. +func PlatformHasSuffix(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldHasSuffix(FieldPlatform, vc)) +} + +// PlatformEqualFold applies the EqualFold predicate on the "platform" field. +func PlatformEqualFold(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldEqualFold(FieldPlatform, vc)) +} + +// PlatformContainsFold applies the ContainsFold predicate on the "platform" field. +func PlatformContainsFold(v consts.UserPlatform) predicate.User { + vc := string(v) + return predicate.User(sql.FieldContainsFold(FieldPlatform, vc)) +} + // StatusEQ applies the EQ predicate on the "status" field. func StatusEQ(v consts.UserStatus) predicate.User { vc := string(v) @@ -516,6 +716,29 @@ func HasTasksWith(preds ...predicate.Task) predicate.User { }) } +// HasIdentities applies the HasEdge predicate on the "identities" edge. +func HasIdentities() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, IdentitiesTable, IdentitiesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasIdentitiesWith applies the HasEdge predicate on the "identities" edge with a given conditions (other predicates). +func HasIdentitiesWith(preds ...predicate.UserIdentity) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newIdentitiesStep() + 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(sql.AndPredicates(predicates...)) diff --git a/backend/db/user_create.go b/backend/db/user_create.go index 269ee34..21c3646 100644 --- a/backend/db/user_create.go +++ b/backend/db/user_create.go @@ -16,6 +16,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" ) @@ -34,18 +35,70 @@ func (uc *UserCreate) SetUsername(s string) *UserCreate { return uc } +// SetNillableUsername sets the "username" field if the given value is not nil. +func (uc *UserCreate) SetNillableUsername(s *string) *UserCreate { + if s != nil { + uc.SetUsername(*s) + } + return uc +} + // SetPassword sets the "password" field. func (uc *UserCreate) SetPassword(s string) *UserCreate { uc.mutation.SetPassword(s) return uc } +// SetNillablePassword sets the "password" field if the given value is not nil. +func (uc *UserCreate) SetNillablePassword(s *string) *UserCreate { + if s != nil { + uc.SetPassword(*s) + } + return uc +} + // SetEmail sets the "email" field. func (uc *UserCreate) SetEmail(s string) *UserCreate { uc.mutation.SetEmail(s) return uc } +// SetNillableEmail sets the "email" field if the given value is not nil. +func (uc *UserCreate) SetNillableEmail(s *string) *UserCreate { + if s != nil { + uc.SetEmail(*s) + } + return uc +} + +// SetAvatarURL sets the "avatar_url" field. +func (uc *UserCreate) SetAvatarURL(s string) *UserCreate { + uc.mutation.SetAvatarURL(s) + return uc +} + +// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil. +func (uc *UserCreate) SetNillableAvatarURL(s *string) *UserCreate { + if s != nil { + uc.SetAvatarURL(*s) + } + return uc +} + +// SetPlatform sets the "platform" field. +func (uc *UserCreate) SetPlatform(cp consts.UserPlatform) *UserCreate { + uc.mutation.SetPlatform(cp) + return uc +} + +// SetNillablePlatform sets the "platform" field if the given value is not nil. +func (uc *UserCreate) SetNillablePlatform(cp *consts.UserPlatform) *UserCreate { + if cp != nil { + uc.SetPlatform(*cp) + } + return uc +} + // SetStatus sets the "status" field. func (uc *UserCreate) SetStatus(cs consts.UserStatus) *UserCreate { uc.mutation.SetStatus(cs) @@ -139,6 +192,21 @@ func (uc *UserCreate) AddTasks(t ...*Task) *UserCreate { return uc.AddTaskIDs(ids...) } +// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by IDs. +func (uc *UserCreate) AddIdentityIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddIdentityIDs(ids...) + return uc +} + +// AddIdentities adds the "identities" edges to the UserIdentity entity. +func (uc *UserCreate) AddIdentities(u ...*UserIdentity) *UserCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddIdentityIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -174,6 +242,10 @@ func (uc *UserCreate) ExecX(ctx context.Context) { // defaults sets the default values of the builder before save. func (uc *UserCreate) defaults() { + if _, ok := uc.mutation.Platform(); !ok { + v := user.DefaultPlatform + uc.mutation.SetPlatform(v) + } if _, ok := uc.mutation.Status(); !ok { v := user.DefaultStatus uc.mutation.SetStatus(v) @@ -190,14 +262,8 @@ func (uc *UserCreate) defaults() { // check runs all checks and user-defined validators on the builder. func (uc *UserCreate) check() error { - if _, ok := uc.mutation.Username(); !ok { - return &ValidationError{Name: "username", err: errors.New(`db: missing required field "User.username"`)} - } - if _, ok := uc.mutation.Password(); !ok { - return &ValidationError{Name: "password", err: errors.New(`db: missing required field "User.password"`)} - } - if _, ok := uc.mutation.Email(); !ok { - return &ValidationError{Name: "email", err: errors.New(`db: missing required field "User.email"`)} + if _, ok := uc.mutation.Platform(); !ok { + return &ValidationError{Name: "platform", err: errors.New(`db: missing required field "User.platform"`)} } if _, ok := uc.mutation.Status(); !ok { return &ValidationError{Name: "status", err: errors.New(`db: missing required field "User.status"`)} @@ -256,6 +322,14 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { _spec.SetField(user.FieldEmail, field.TypeString, value) _node.Email = value } + if value, ok := uc.mutation.AvatarURL(); ok { + _spec.SetField(user.FieldAvatarURL, field.TypeString, value) + _node.AvatarURL = value + } + if value, ok := uc.mutation.Platform(); ok { + _spec.SetField(user.FieldPlatform, field.TypeString, value) + _node.Platform = value + } if value, ok := uc.mutation.Status(); ok { _spec.SetField(user.FieldStatus, field.TypeString, value) _node.Status = value @@ -316,6 +390,22 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.IdentitiesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } @@ -380,6 +470,12 @@ func (u *UserUpsert) UpdateUsername() *UserUpsert { return u } +// ClearUsername clears the value of the "username" field. +func (u *UserUpsert) ClearUsername() *UserUpsert { + u.SetNull(user.FieldUsername) + return u +} + // SetPassword sets the "password" field. func (u *UserUpsert) SetPassword(v string) *UserUpsert { u.Set(user.FieldPassword, v) @@ -392,6 +488,12 @@ func (u *UserUpsert) UpdatePassword() *UserUpsert { return u } +// ClearPassword clears the value of the "password" field. +func (u *UserUpsert) ClearPassword() *UserUpsert { + u.SetNull(user.FieldPassword) + return u +} + // SetEmail sets the "email" field. func (u *UserUpsert) SetEmail(v string) *UserUpsert { u.Set(user.FieldEmail, v) @@ -404,6 +506,42 @@ func (u *UserUpsert) UpdateEmail() *UserUpsert { return u } +// ClearEmail clears the value of the "email" field. +func (u *UserUpsert) ClearEmail() *UserUpsert { + u.SetNull(user.FieldEmail) + return u +} + +// SetAvatarURL sets the "avatar_url" field. +func (u *UserUpsert) SetAvatarURL(v string) *UserUpsert { + u.Set(user.FieldAvatarURL, v) + return u +} + +// UpdateAvatarURL sets the "avatar_url" field to the value that was provided on create. +func (u *UserUpsert) UpdateAvatarURL() *UserUpsert { + u.SetExcluded(user.FieldAvatarURL) + return u +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (u *UserUpsert) ClearAvatarURL() *UserUpsert { + u.SetNull(user.FieldAvatarURL) + return u +} + +// SetPlatform sets the "platform" field. +func (u *UserUpsert) SetPlatform(v consts.UserPlatform) *UserUpsert { + u.Set(user.FieldPlatform, v) + return u +} + +// UpdatePlatform sets the "platform" field to the value that was provided on create. +func (u *UserUpsert) UpdatePlatform() *UserUpsert { + u.SetExcluded(user.FieldPlatform) + return u +} + // SetStatus sets the "status" field. func (u *UserUpsert) SetStatus(v consts.UserStatus) *UserUpsert { u.Set(user.FieldStatus, v) @@ -502,6 +640,13 @@ func (u *UserUpsertOne) UpdateUsername() *UserUpsertOne { }) } +// ClearUsername clears the value of the "username" field. +func (u *UserUpsertOne) ClearUsername() *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.ClearUsername() + }) +} + // SetPassword sets the "password" field. func (u *UserUpsertOne) SetPassword(v string) *UserUpsertOne { return u.Update(func(s *UserUpsert) { @@ -516,6 +661,13 @@ func (u *UserUpsertOne) UpdatePassword() *UserUpsertOne { }) } +// ClearPassword clears the value of the "password" field. +func (u *UserUpsertOne) ClearPassword() *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.ClearPassword() + }) +} + // SetEmail sets the "email" field. func (u *UserUpsertOne) SetEmail(v string) *UserUpsertOne { return u.Update(func(s *UserUpsert) { @@ -530,6 +682,48 @@ func (u *UserUpsertOne) UpdateEmail() *UserUpsertOne { }) } +// ClearEmail clears the value of the "email" field. +func (u *UserUpsertOne) ClearEmail() *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.ClearEmail() + }) +} + +// SetAvatarURL sets the "avatar_url" field. +func (u *UserUpsertOne) SetAvatarURL(v string) *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.SetAvatarURL(v) + }) +} + +// UpdateAvatarURL sets the "avatar_url" field to the value that was provided on create. +func (u *UserUpsertOne) UpdateAvatarURL() *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.UpdateAvatarURL() + }) +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (u *UserUpsertOne) ClearAvatarURL() *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.ClearAvatarURL() + }) +} + +// SetPlatform sets the "platform" field. +func (u *UserUpsertOne) SetPlatform(v consts.UserPlatform) *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.SetPlatform(v) + }) +} + +// UpdatePlatform sets the "platform" field to the value that was provided on create. +func (u *UserUpsertOne) UpdatePlatform() *UserUpsertOne { + return u.Update(func(s *UserUpsert) { + s.UpdatePlatform() + }) +} + // SetStatus sets the "status" field. func (u *UserUpsertOne) SetStatus(v consts.UserStatus) *UserUpsertOne { return u.Update(func(s *UserUpsert) { @@ -801,6 +995,13 @@ func (u *UserUpsertBulk) UpdateUsername() *UserUpsertBulk { }) } +// ClearUsername clears the value of the "username" field. +func (u *UserUpsertBulk) ClearUsername() *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.ClearUsername() + }) +} + // SetPassword sets the "password" field. func (u *UserUpsertBulk) SetPassword(v string) *UserUpsertBulk { return u.Update(func(s *UserUpsert) { @@ -815,6 +1016,13 @@ func (u *UserUpsertBulk) UpdatePassword() *UserUpsertBulk { }) } +// ClearPassword clears the value of the "password" field. +func (u *UserUpsertBulk) ClearPassword() *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.ClearPassword() + }) +} + // SetEmail sets the "email" field. func (u *UserUpsertBulk) SetEmail(v string) *UserUpsertBulk { return u.Update(func(s *UserUpsert) { @@ -829,6 +1037,48 @@ func (u *UserUpsertBulk) UpdateEmail() *UserUpsertBulk { }) } +// ClearEmail clears the value of the "email" field. +func (u *UserUpsertBulk) ClearEmail() *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.ClearEmail() + }) +} + +// SetAvatarURL sets the "avatar_url" field. +func (u *UserUpsertBulk) SetAvatarURL(v string) *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.SetAvatarURL(v) + }) +} + +// UpdateAvatarURL sets the "avatar_url" field to the value that was provided on create. +func (u *UserUpsertBulk) UpdateAvatarURL() *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.UpdateAvatarURL() + }) +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (u *UserUpsertBulk) ClearAvatarURL() *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.ClearAvatarURL() + }) +} + +// SetPlatform sets the "platform" field. +func (u *UserUpsertBulk) SetPlatform(v consts.UserPlatform) *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.SetPlatform(v) + }) +} + +// UpdatePlatform sets the "platform" field to the value that was provided on create. +func (u *UserUpsertBulk) UpdatePlatform() *UserUpsertBulk { + return u.Update(func(s *UserUpsert) { + s.UpdatePlatform() + }) +} + // SetStatus sets the "status" field. func (u *UserUpsertBulk) SetStatus(v consts.UserStatus) *UserUpsertBulk { return u.Update(func(s *UserUpsert) { diff --git a/backend/db/user_query.go b/backend/db/user_query.go index c9d6609..089a910 100644 --- a/backend/db/user_query.go +++ b/backend/db/user_query.go @@ -17,6 +17,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" ) @@ -31,6 +32,7 @@ type UserQuery struct { withLoginHistories *UserLoginHistoryQuery withModels *ModelQuery withTasks *TaskQuery + withIdentities *UserIdentityQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -134,6 +136,28 @@ func (uq *UserQuery) QueryTasks() *TaskQuery { return query } +// QueryIdentities chains the current query on the "identities" edge. +func (uq *UserQuery) QueryIdentities() *UserIdentityQuery { + query := (&UserIdentityClient{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(useridentity.Table, useridentity.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.IdentitiesTable, user.IdentitiesColumn), + ) + 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) { @@ -329,6 +353,7 @@ func (uq *UserQuery) Clone() *UserQuery { withLoginHistories: uq.withLoginHistories.Clone(), withModels: uq.withModels.Clone(), withTasks: uq.withTasks.Clone(), + withIdentities: uq.withIdentities.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, @@ -369,6 +394,17 @@ func (uq *UserQuery) WithTasks(opts ...func(*TaskQuery)) *UserQuery { return uq } +// WithIdentities tells the query-builder to eager-load the nodes that are connected to +// the "identities" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithIdentities(opts ...func(*UserIdentityQuery)) *UserQuery { + query := (&UserIdentityClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withIdentities = 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. // @@ -447,10 +483,11 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = uq.querySpec() - loadedTypes = [3]bool{ + loadedTypes = [4]bool{ uq.withLoginHistories != nil, uq.withModels != nil, uq.withTasks != nil, + uq.withIdentities != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -495,6 +532,13 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := uq.withIdentities; query != nil { + if err := uq.loadIdentities(ctx, query, nodes, + func(n *User) { n.Edges.Identities = []*UserIdentity{} }, + func(n *User, e *UserIdentity) { n.Edges.Identities = append(n.Edges.Identities, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -589,6 +633,36 @@ func (uq *UserQuery) loadTasks(ctx context.Context, query *TaskQuery, nodes []*U } return nil } +func (uq *UserQuery) loadIdentities(ctx context.Context, query *UserIdentityQuery, nodes []*User, init func(*User), assign func(*User, *UserIdentity)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(useridentity.FieldUserID) + } + query.Where(predicate.UserIdentity(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.IdentitiesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" 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() diff --git a/backend/db/user_update.go b/backend/db/user_update.go index a6ffc8f..8fc4a43 100644 --- a/backend/db/user_update.go +++ b/backend/db/user_update.go @@ -16,6 +16,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" ) @@ -48,6 +49,12 @@ func (uu *UserUpdate) SetNillableUsername(s *string) *UserUpdate { return uu } +// ClearUsername clears the value of the "username" field. +func (uu *UserUpdate) ClearUsername() *UserUpdate { + uu.mutation.ClearUsername() + return uu +} + // SetPassword sets the "password" field. func (uu *UserUpdate) SetPassword(s string) *UserUpdate { uu.mutation.SetPassword(s) @@ -62,6 +69,12 @@ func (uu *UserUpdate) SetNillablePassword(s *string) *UserUpdate { return uu } +// ClearPassword clears the value of the "password" field. +func (uu *UserUpdate) ClearPassword() *UserUpdate { + uu.mutation.ClearPassword() + return uu +} + // SetEmail sets the "email" field. func (uu *UserUpdate) SetEmail(s string) *UserUpdate { uu.mutation.SetEmail(s) @@ -76,6 +89,46 @@ func (uu *UserUpdate) SetNillableEmail(s *string) *UserUpdate { return uu } +// ClearEmail clears the value of the "email" field. +func (uu *UserUpdate) ClearEmail() *UserUpdate { + uu.mutation.ClearEmail() + return uu +} + +// SetAvatarURL sets the "avatar_url" field. +func (uu *UserUpdate) SetAvatarURL(s string) *UserUpdate { + uu.mutation.SetAvatarURL(s) + return uu +} + +// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil. +func (uu *UserUpdate) SetNillableAvatarURL(s *string) *UserUpdate { + if s != nil { + uu.SetAvatarURL(*s) + } + return uu +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (uu *UserUpdate) ClearAvatarURL() *UserUpdate { + uu.mutation.ClearAvatarURL() + return uu +} + +// SetPlatform sets the "platform" field. +func (uu *UserUpdate) SetPlatform(cp consts.UserPlatform) *UserUpdate { + uu.mutation.SetPlatform(cp) + return uu +} + +// SetNillablePlatform sets the "platform" field if the given value is not nil. +func (uu *UserUpdate) SetNillablePlatform(cp *consts.UserPlatform) *UserUpdate { + if cp != nil { + uu.SetPlatform(*cp) + } + return uu +} + // SetStatus sets the "status" field. func (uu *UserUpdate) SetStatus(cs consts.UserStatus) *UserUpdate { uu.mutation.SetStatus(cs) @@ -163,6 +216,21 @@ func (uu *UserUpdate) AddTasks(t ...*Task) *UserUpdate { return uu.AddTaskIDs(ids...) } +// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by IDs. +func (uu *UserUpdate) AddIdentityIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddIdentityIDs(ids...) + return uu +} + +// AddIdentities adds the "identities" edges to the UserIdentity entity. +func (uu *UserUpdate) AddIdentities(u ...*UserIdentity) *UserUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddIdentityIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation @@ -231,6 +299,27 @@ func (uu *UserUpdate) RemoveTasks(t ...*Task) *UserUpdate { return uu.RemoveTaskIDs(ids...) } +// ClearIdentities clears all "identities" edges to the UserIdentity entity. +func (uu *UserUpdate) ClearIdentities() *UserUpdate { + uu.mutation.ClearIdentities() + return uu +} + +// RemoveIdentityIDs removes the "identities" edge to UserIdentity entities by IDs. +func (uu *UserUpdate) RemoveIdentityIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveIdentityIDs(ids...) + return uu +} + +// RemoveIdentities removes "identities" edges to UserIdentity entities. +func (uu *UserUpdate) RemoveIdentities(u ...*UserIdentity) *UserUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveIdentityIDs(ids...) +} + // 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) @@ -276,12 +365,30 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := uu.mutation.Username(); ok { _spec.SetField(user.FieldUsername, field.TypeString, value) } + if uu.mutation.UsernameCleared() { + _spec.ClearField(user.FieldUsername, field.TypeString) + } if value, ok := uu.mutation.Password(); ok { _spec.SetField(user.FieldPassword, field.TypeString, value) } + if uu.mutation.PasswordCleared() { + _spec.ClearField(user.FieldPassword, field.TypeString) + } if value, ok := uu.mutation.Email(); ok { _spec.SetField(user.FieldEmail, field.TypeString, value) } + if uu.mutation.EmailCleared() { + _spec.ClearField(user.FieldEmail, field.TypeString) + } + if value, ok := uu.mutation.AvatarURL(); ok { + _spec.SetField(user.FieldAvatarURL, field.TypeString, value) + } + if uu.mutation.AvatarURLCleared() { + _spec.ClearField(user.FieldAvatarURL, field.TypeString) + } + if value, ok := uu.mutation.Platform(); ok { + _spec.SetField(user.FieldPlatform, field.TypeString, value) + } if value, ok := uu.mutation.Status(); ok { _spec.SetField(user.FieldStatus, field.TypeString, value) } @@ -426,6 +533,51 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.IdentitiesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedIdentitiesIDs(); len(nodes) > 0 && !uu.mutation.IdentitiesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.IdentitiesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(uu.modifiers...) if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -462,6 +614,12 @@ func (uuo *UserUpdateOne) SetNillableUsername(s *string) *UserUpdateOne { return uuo } +// ClearUsername clears the value of the "username" field. +func (uuo *UserUpdateOne) ClearUsername() *UserUpdateOne { + uuo.mutation.ClearUsername() + return uuo +} + // SetPassword sets the "password" field. func (uuo *UserUpdateOne) SetPassword(s string) *UserUpdateOne { uuo.mutation.SetPassword(s) @@ -476,6 +634,12 @@ func (uuo *UserUpdateOne) SetNillablePassword(s *string) *UserUpdateOne { return uuo } +// ClearPassword clears the value of the "password" field. +func (uuo *UserUpdateOne) ClearPassword() *UserUpdateOne { + uuo.mutation.ClearPassword() + return uuo +} + // SetEmail sets the "email" field. func (uuo *UserUpdateOne) SetEmail(s string) *UserUpdateOne { uuo.mutation.SetEmail(s) @@ -490,6 +654,46 @@ func (uuo *UserUpdateOne) SetNillableEmail(s *string) *UserUpdateOne { return uuo } +// ClearEmail clears the value of the "email" field. +func (uuo *UserUpdateOne) ClearEmail() *UserUpdateOne { + uuo.mutation.ClearEmail() + return uuo +} + +// SetAvatarURL sets the "avatar_url" field. +func (uuo *UserUpdateOne) SetAvatarURL(s string) *UserUpdateOne { + uuo.mutation.SetAvatarURL(s) + return uuo +} + +// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableAvatarURL(s *string) *UserUpdateOne { + if s != nil { + uuo.SetAvatarURL(*s) + } + return uuo +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (uuo *UserUpdateOne) ClearAvatarURL() *UserUpdateOne { + uuo.mutation.ClearAvatarURL() + return uuo +} + +// SetPlatform sets the "platform" field. +func (uuo *UserUpdateOne) SetPlatform(cp consts.UserPlatform) *UserUpdateOne { + uuo.mutation.SetPlatform(cp) + return uuo +} + +// SetNillablePlatform sets the "platform" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillablePlatform(cp *consts.UserPlatform) *UserUpdateOne { + if cp != nil { + uuo.SetPlatform(*cp) + } + return uuo +} + // SetStatus sets the "status" field. func (uuo *UserUpdateOne) SetStatus(cs consts.UserStatus) *UserUpdateOne { uuo.mutation.SetStatus(cs) @@ -577,6 +781,21 @@ func (uuo *UserUpdateOne) AddTasks(t ...*Task) *UserUpdateOne { return uuo.AddTaskIDs(ids...) } +// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by IDs. +func (uuo *UserUpdateOne) AddIdentityIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddIdentityIDs(ids...) + return uuo +} + +// AddIdentities adds the "identities" edges to the UserIdentity entity. +func (uuo *UserUpdateOne) AddIdentities(u ...*UserIdentity) *UserUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddIdentityIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation @@ -645,6 +864,27 @@ func (uuo *UserUpdateOne) RemoveTasks(t ...*Task) *UserUpdateOne { return uuo.RemoveTaskIDs(ids...) } +// ClearIdentities clears all "identities" edges to the UserIdentity entity. +func (uuo *UserUpdateOne) ClearIdentities() *UserUpdateOne { + uuo.mutation.ClearIdentities() + return uuo +} + +// RemoveIdentityIDs removes the "identities" edge to UserIdentity entities by IDs. +func (uuo *UserUpdateOne) RemoveIdentityIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveIdentityIDs(ids...) + return uuo +} + +// RemoveIdentities removes "identities" edges to UserIdentity entities. +func (uuo *UserUpdateOne) RemoveIdentities(u ...*UserIdentity) *UserUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveIdentityIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) @@ -720,12 +960,30 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) if value, ok := uuo.mutation.Username(); ok { _spec.SetField(user.FieldUsername, field.TypeString, value) } + if uuo.mutation.UsernameCleared() { + _spec.ClearField(user.FieldUsername, field.TypeString) + } if value, ok := uuo.mutation.Password(); ok { _spec.SetField(user.FieldPassword, field.TypeString, value) } + if uuo.mutation.PasswordCleared() { + _spec.ClearField(user.FieldPassword, field.TypeString) + } if value, ok := uuo.mutation.Email(); ok { _spec.SetField(user.FieldEmail, field.TypeString, value) } + if uuo.mutation.EmailCleared() { + _spec.ClearField(user.FieldEmail, field.TypeString) + } + if value, ok := uuo.mutation.AvatarURL(); ok { + _spec.SetField(user.FieldAvatarURL, field.TypeString, value) + } + if uuo.mutation.AvatarURLCleared() { + _spec.ClearField(user.FieldAvatarURL, field.TypeString) + } + if value, ok := uuo.mutation.Platform(); ok { + _spec.SetField(user.FieldPlatform, field.TypeString, value) + } if value, ok := uuo.mutation.Status(); ok { _spec.SetField(user.FieldStatus, field.TypeString, value) } @@ -870,6 +1128,51 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.IdentitiesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedIdentitiesIDs(); len(nodes) > 0 && !uuo.mutation.IdentitiesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.IdentitiesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.IdentitiesTable, + Columns: []string{user.IdentitiesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(uuo.modifiers...) _node = &User{config: uuo.config} _spec.Assign = _node.assignValues diff --git a/backend/db/useridentity.go b/backend/db/useridentity.go new file mode 100644 index 0000000..22f4aa4 --- /dev/null +++ b/backend/db/useridentity.go @@ -0,0 +1,214 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/google/uuid" +) + +// UserIdentity is the model entity for the UserIdentity schema. +type UserIdentity struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID uuid.UUID `json:"user_id,omitempty"` + // Platform holds the value of the "platform" field. + Platform consts.UserPlatform `json:"platform,omitempty"` + // IdentityID holds the value of the "identity_id" field. + IdentityID string `json:"identity_id,omitempty"` + // UnionID holds the value of the "union_id" field. + UnionID string `json:"union_id,omitempty"` + // Nickname holds the value of the "nickname" field. + Nickname string `json:"nickname,omitempty"` + // Email holds the value of the "email" field. + Email string `json:"email,omitempty"` + // AvatarURL holds the value of the "avatar_url" field. + AvatarURL string `json:"avatar_url,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserIdentityQuery when eager-loading is set. + Edges UserIdentityEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserIdentityEdges holds the relations/edges for other nodes in the graph. +type UserIdentityEdges 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 UserIdentityEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserIdentity) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case useridentity.FieldPlatform, useridentity.FieldIdentityID, useridentity.FieldUnionID, useridentity.FieldNickname, useridentity.FieldEmail, useridentity.FieldAvatarURL: + values[i] = new(sql.NullString) + case useridentity.FieldCreatedAt: + values[i] = new(sql.NullTime) + case useridentity.FieldID, useridentity.FieldUserID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the UserIdentity fields. +func (ui *UserIdentity) 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 useridentity.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + ui.ID = *value + } + case useridentity.FieldUserID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value != nil { + ui.UserID = *value + } + case useridentity.FieldPlatform: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field platform", values[i]) + } else if value.Valid { + ui.Platform = consts.UserPlatform(value.String) + } + case useridentity.FieldIdentityID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field identity_id", values[i]) + } else if value.Valid { + ui.IdentityID = value.String + } + case useridentity.FieldUnionID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field union_id", values[i]) + } else if value.Valid { + ui.UnionID = value.String + } + case useridentity.FieldNickname: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field nickname", values[i]) + } else if value.Valid { + ui.Nickname = value.String + } + case useridentity.FieldEmail: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field email", values[i]) + } else if value.Valid { + ui.Email = value.String + } + case useridentity.FieldAvatarURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field avatar_url", values[i]) + } else if value.Valid { + ui.AvatarURL = value.String + } + case useridentity.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + ui.CreatedAt = value.Time + } + default: + ui.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserIdentity. +// This includes values selected through modifiers, order, etc. +func (ui *UserIdentity) Value(name string) (ent.Value, error) { + return ui.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the UserIdentity entity. +func (ui *UserIdentity) QueryUser() *UserQuery { + return NewUserIdentityClient(ui.config).QueryUser(ui) +} + +// Update returns a builder for updating this UserIdentity. +// Note that you need to call UserIdentity.Unwrap() before calling this method if this UserIdentity +// was returned from a transaction, and the transaction was committed or rolled back. +func (ui *UserIdentity) Update() *UserIdentityUpdateOne { + return NewUserIdentityClient(ui.config).UpdateOne(ui) +} + +// Unwrap unwraps the UserIdentity 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 (ui *UserIdentity) Unwrap() *UserIdentity { + _tx, ok := ui.config.driver.(*txDriver) + if !ok { + panic("db: UserIdentity is not a transactional entity") + } + ui.config.driver = _tx.drv + return ui +} + +// String implements the fmt.Stringer. +func (ui *UserIdentity) String() string { + var builder strings.Builder + builder.WriteString("UserIdentity(") + builder.WriteString(fmt.Sprintf("id=%v, ", ui.ID)) + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", ui.UserID)) + builder.WriteString(", ") + builder.WriteString("platform=") + builder.WriteString(fmt.Sprintf("%v", ui.Platform)) + builder.WriteString(", ") + builder.WriteString("identity_id=") + builder.WriteString(ui.IdentityID) + builder.WriteString(", ") + builder.WriteString("union_id=") + builder.WriteString(ui.UnionID) + builder.WriteString(", ") + builder.WriteString("nickname=") + builder.WriteString(ui.Nickname) + builder.WriteString(", ") + builder.WriteString("email=") + builder.WriteString(ui.Email) + builder.WriteString(", ") + builder.WriteString("avatar_url=") + builder.WriteString(ui.AvatarURL) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(ui.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// UserIdentities is a parsable slice of UserIdentity. +type UserIdentities []*UserIdentity diff --git a/backend/db/useridentity/useridentity.go b/backend/db/useridentity/useridentity.go new file mode 100644 index 0000000..dd265c8 --- /dev/null +++ b/backend/db/useridentity/useridentity.go @@ -0,0 +1,137 @@ +// Code generated by ent, DO NOT EDIT. + +package useridentity + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/consts" +) + +const ( + // Label holds the string label denoting the useridentity type in the database. + Label = "user_identity" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldPlatform holds the string denoting the platform field in the database. + FieldPlatform = "platform" + // FieldIdentityID holds the string denoting the identity_id field in the database. + FieldIdentityID = "identity_id" + // FieldUnionID holds the string denoting the union_id field in the database. + FieldUnionID = "union_id" + // FieldNickname holds the string denoting the nickname field in the database. + FieldNickname = "nickname" + // FieldEmail holds the string denoting the email field in the database. + FieldEmail = "email" + // FieldAvatarURL holds the string denoting the avatar_url field in the database. + FieldAvatarURL = "avatar_url" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the useridentity in the database. + Table = "user_identities" + // UserTable is the table that holds the user relation/edge. + UserTable = "user_identities" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" +) + +// Columns holds all SQL columns for useridentity fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldPlatform, + FieldIdentityID, + FieldUnionID, + FieldNickname, + FieldEmail, + FieldAvatarURL, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultPlatform holds the default value on creation for the "platform" field. + DefaultPlatform consts.UserPlatform + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the UserIdentity 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() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByPlatform orders the results by the platform field. +func ByPlatform(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPlatform, opts...).ToFunc() +} + +// ByIdentityID orders the results by the identity_id field. +func ByIdentityID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIdentityID, opts...).ToFunc() +} + +// ByUnionID orders the results by the union_id field. +func ByUnionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnionID, opts...).ToFunc() +} + +// ByNickname orders the results by the nickname field. +func ByNickname(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNickname, opts...).ToFunc() +} + +// ByEmail orders the results by the email field. +func ByEmail(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEmail, opts...).ToFunc() +} + +// ByAvatarURL orders the results by the avatar_url field. +func ByAvatarURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAvatarURL, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, 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, true, UserTable, UserColumn), + ) +} diff --git a/backend/db/useridentity/where.go b/backend/db/useridentity/where.go new file mode 100644 index 0000000..e509027 --- /dev/null +++ b/backend/db/useridentity/where.go @@ -0,0 +1,656 @@ +// Code generated by ent, DO NOT EDIT. + +package useridentity + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldID, id)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldUserID, v)) +} + +// Platform applies equality check predicate on the "platform" field. It's identical to PlatformEQ. +func Platform(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldEQ(FieldPlatform, vc)) +} + +// IdentityID applies equality check predicate on the "identity_id" field. It's identical to IdentityIDEQ. +func IdentityID(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldIdentityID, v)) +} + +// UnionID applies equality check predicate on the "union_id" field. It's identical to UnionIDEQ. +func UnionID(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldUnionID, v)) +} + +// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ. +func Nickname(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldNickname, v)) +} + +// Email applies equality check predicate on the "email" field. It's identical to EmailEQ. +func Email(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldEmail, v)) +} + +// AvatarURL applies equality check predicate on the "avatar_url" field. It's identical to AvatarURLEQ. +func AvatarURL(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldAvatarURL, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...uuid.UUID) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDIsNil applies the IsNil predicate on the "user_id" field. +func UserIDIsNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIsNull(FieldUserID)) +} + +// UserIDNotNil applies the NotNil predicate on the "user_id" field. +func UserIDNotNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotNull(FieldUserID)) +} + +// PlatformEQ applies the EQ predicate on the "platform" field. +func PlatformEQ(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldEQ(FieldPlatform, vc)) +} + +// PlatformNEQ applies the NEQ predicate on the "platform" field. +func PlatformNEQ(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldNEQ(FieldPlatform, vc)) +} + +// PlatformIn applies the In predicate on the "platform" field. +func PlatformIn(vs ...consts.UserPlatform) predicate.UserIdentity { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.UserIdentity(sql.FieldIn(FieldPlatform, v...)) +} + +// PlatformNotIn applies the NotIn predicate on the "platform" field. +func PlatformNotIn(vs ...consts.UserPlatform) predicate.UserIdentity { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.UserIdentity(sql.FieldNotIn(FieldPlatform, v...)) +} + +// PlatformGT applies the GT predicate on the "platform" field. +func PlatformGT(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldGT(FieldPlatform, vc)) +} + +// PlatformGTE applies the GTE predicate on the "platform" field. +func PlatformGTE(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldGTE(FieldPlatform, vc)) +} + +// PlatformLT applies the LT predicate on the "platform" field. +func PlatformLT(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldLT(FieldPlatform, vc)) +} + +// PlatformLTE applies the LTE predicate on the "platform" field. +func PlatformLTE(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldLTE(FieldPlatform, vc)) +} + +// PlatformContains applies the Contains predicate on the "platform" field. +func PlatformContains(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldContains(FieldPlatform, vc)) +} + +// PlatformHasPrefix applies the HasPrefix predicate on the "platform" field. +func PlatformHasPrefix(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldHasPrefix(FieldPlatform, vc)) +} + +// PlatformHasSuffix applies the HasSuffix predicate on the "platform" field. +func PlatformHasSuffix(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldHasSuffix(FieldPlatform, vc)) +} + +// PlatformEqualFold applies the EqualFold predicate on the "platform" field. +func PlatformEqualFold(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldEqualFold(FieldPlatform, vc)) +} + +// PlatformContainsFold applies the ContainsFold predicate on the "platform" field. +func PlatformContainsFold(v consts.UserPlatform) predicate.UserIdentity { + vc := string(v) + return predicate.UserIdentity(sql.FieldContainsFold(FieldPlatform, vc)) +} + +// IdentityIDEQ applies the EQ predicate on the "identity_id" field. +func IdentityIDEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldIdentityID, v)) +} + +// IdentityIDNEQ applies the NEQ predicate on the "identity_id" field. +func IdentityIDNEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldIdentityID, v)) +} + +// IdentityIDIn applies the In predicate on the "identity_id" field. +func IdentityIDIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldIdentityID, vs...)) +} + +// IdentityIDNotIn applies the NotIn predicate on the "identity_id" field. +func IdentityIDNotIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldIdentityID, vs...)) +} + +// IdentityIDGT applies the GT predicate on the "identity_id" field. +func IdentityIDGT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldIdentityID, v)) +} + +// IdentityIDGTE applies the GTE predicate on the "identity_id" field. +func IdentityIDGTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldIdentityID, v)) +} + +// IdentityIDLT applies the LT predicate on the "identity_id" field. +func IdentityIDLT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldIdentityID, v)) +} + +// IdentityIDLTE applies the LTE predicate on the "identity_id" field. +func IdentityIDLTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldIdentityID, v)) +} + +// IdentityIDContains applies the Contains predicate on the "identity_id" field. +func IdentityIDContains(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContains(FieldIdentityID, v)) +} + +// IdentityIDHasPrefix applies the HasPrefix predicate on the "identity_id" field. +func IdentityIDHasPrefix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasPrefix(FieldIdentityID, v)) +} + +// IdentityIDHasSuffix applies the HasSuffix predicate on the "identity_id" field. +func IdentityIDHasSuffix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasSuffix(FieldIdentityID, v)) +} + +// IdentityIDEqualFold applies the EqualFold predicate on the "identity_id" field. +func IdentityIDEqualFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEqualFold(FieldIdentityID, v)) +} + +// IdentityIDContainsFold applies the ContainsFold predicate on the "identity_id" field. +func IdentityIDContainsFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContainsFold(FieldIdentityID, v)) +} + +// UnionIDEQ applies the EQ predicate on the "union_id" field. +func UnionIDEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldUnionID, v)) +} + +// UnionIDNEQ applies the NEQ predicate on the "union_id" field. +func UnionIDNEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldUnionID, v)) +} + +// UnionIDIn applies the In predicate on the "union_id" field. +func UnionIDIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldUnionID, vs...)) +} + +// UnionIDNotIn applies the NotIn predicate on the "union_id" field. +func UnionIDNotIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldUnionID, vs...)) +} + +// UnionIDGT applies the GT predicate on the "union_id" field. +func UnionIDGT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldUnionID, v)) +} + +// UnionIDGTE applies the GTE predicate on the "union_id" field. +func UnionIDGTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldUnionID, v)) +} + +// UnionIDLT applies the LT predicate on the "union_id" field. +func UnionIDLT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldUnionID, v)) +} + +// UnionIDLTE applies the LTE predicate on the "union_id" field. +func UnionIDLTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldUnionID, v)) +} + +// UnionIDContains applies the Contains predicate on the "union_id" field. +func UnionIDContains(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContains(FieldUnionID, v)) +} + +// UnionIDHasPrefix applies the HasPrefix predicate on the "union_id" field. +func UnionIDHasPrefix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasPrefix(FieldUnionID, v)) +} + +// UnionIDHasSuffix applies the HasSuffix predicate on the "union_id" field. +func UnionIDHasSuffix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasSuffix(FieldUnionID, v)) +} + +// UnionIDIsNil applies the IsNil predicate on the "union_id" field. +func UnionIDIsNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIsNull(FieldUnionID)) +} + +// UnionIDNotNil applies the NotNil predicate on the "union_id" field. +func UnionIDNotNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotNull(FieldUnionID)) +} + +// UnionIDEqualFold applies the EqualFold predicate on the "union_id" field. +func UnionIDEqualFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEqualFold(FieldUnionID, v)) +} + +// UnionIDContainsFold applies the ContainsFold predicate on the "union_id" field. +func UnionIDContainsFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContainsFold(FieldUnionID, v)) +} + +// NicknameEQ applies the EQ predicate on the "nickname" field. +func NicknameEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldNickname, v)) +} + +// NicknameNEQ applies the NEQ predicate on the "nickname" field. +func NicknameNEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldNickname, v)) +} + +// NicknameIn applies the In predicate on the "nickname" field. +func NicknameIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldNickname, vs...)) +} + +// NicknameNotIn applies the NotIn predicate on the "nickname" field. +func NicknameNotIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldNickname, vs...)) +} + +// NicknameGT applies the GT predicate on the "nickname" field. +func NicknameGT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldNickname, v)) +} + +// NicknameGTE applies the GTE predicate on the "nickname" field. +func NicknameGTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldNickname, v)) +} + +// NicknameLT applies the LT predicate on the "nickname" field. +func NicknameLT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldNickname, v)) +} + +// NicknameLTE applies the LTE predicate on the "nickname" field. +func NicknameLTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldNickname, v)) +} + +// NicknameContains applies the Contains predicate on the "nickname" field. +func NicknameContains(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContains(FieldNickname, v)) +} + +// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field. +func NicknameHasPrefix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasPrefix(FieldNickname, v)) +} + +// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field. +func NicknameHasSuffix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasSuffix(FieldNickname, v)) +} + +// NicknameIsNil applies the IsNil predicate on the "nickname" field. +func NicknameIsNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIsNull(FieldNickname)) +} + +// NicknameNotNil applies the NotNil predicate on the "nickname" field. +func NicknameNotNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotNull(FieldNickname)) +} + +// NicknameEqualFold applies the EqualFold predicate on the "nickname" field. +func NicknameEqualFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEqualFold(FieldNickname, v)) +} + +// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field. +func NicknameContainsFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContainsFold(FieldNickname, v)) +} + +// EmailEQ applies the EQ predicate on the "email" field. +func EmailEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldEmail, v)) +} + +// EmailNEQ applies the NEQ predicate on the "email" field. +func EmailNEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldEmail, v)) +} + +// EmailIn applies the In predicate on the "email" field. +func EmailIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldEmail, vs...)) +} + +// EmailNotIn applies the NotIn predicate on the "email" field. +func EmailNotIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldEmail, vs...)) +} + +// EmailGT applies the GT predicate on the "email" field. +func EmailGT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldEmail, v)) +} + +// EmailGTE applies the GTE predicate on the "email" field. +func EmailGTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldEmail, v)) +} + +// EmailLT applies the LT predicate on the "email" field. +func EmailLT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldEmail, v)) +} + +// EmailLTE applies the LTE predicate on the "email" field. +func EmailLTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldEmail, v)) +} + +// EmailContains applies the Contains predicate on the "email" field. +func EmailContains(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContains(FieldEmail, v)) +} + +// EmailHasPrefix applies the HasPrefix predicate on the "email" field. +func EmailHasPrefix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasPrefix(FieldEmail, v)) +} + +// EmailHasSuffix applies the HasSuffix predicate on the "email" field. +func EmailHasSuffix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasSuffix(FieldEmail, v)) +} + +// EmailIsNil applies the IsNil predicate on the "email" field. +func EmailIsNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIsNull(FieldEmail)) +} + +// EmailNotNil applies the NotNil predicate on the "email" field. +func EmailNotNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotNull(FieldEmail)) +} + +// EmailEqualFold applies the EqualFold predicate on the "email" field. +func EmailEqualFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEqualFold(FieldEmail, v)) +} + +// EmailContainsFold applies the ContainsFold predicate on the "email" field. +func EmailContainsFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContainsFold(FieldEmail, v)) +} + +// AvatarURLEQ applies the EQ predicate on the "avatar_url" field. +func AvatarURLEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldAvatarURL, v)) +} + +// AvatarURLNEQ applies the NEQ predicate on the "avatar_url" field. +func AvatarURLNEQ(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldAvatarURL, v)) +} + +// AvatarURLIn applies the In predicate on the "avatar_url" field. +func AvatarURLIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldAvatarURL, vs...)) +} + +// AvatarURLNotIn applies the NotIn predicate on the "avatar_url" field. +func AvatarURLNotIn(vs ...string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldAvatarURL, vs...)) +} + +// AvatarURLGT applies the GT predicate on the "avatar_url" field. +func AvatarURLGT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldAvatarURL, v)) +} + +// AvatarURLGTE applies the GTE predicate on the "avatar_url" field. +func AvatarURLGTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldAvatarURL, v)) +} + +// AvatarURLLT applies the LT predicate on the "avatar_url" field. +func AvatarURLLT(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldAvatarURL, v)) +} + +// AvatarURLLTE applies the LTE predicate on the "avatar_url" field. +func AvatarURLLTE(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldAvatarURL, v)) +} + +// AvatarURLContains applies the Contains predicate on the "avatar_url" field. +func AvatarURLContains(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContains(FieldAvatarURL, v)) +} + +// AvatarURLHasPrefix applies the HasPrefix predicate on the "avatar_url" field. +func AvatarURLHasPrefix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasPrefix(FieldAvatarURL, v)) +} + +// AvatarURLHasSuffix applies the HasSuffix predicate on the "avatar_url" field. +func AvatarURLHasSuffix(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldHasSuffix(FieldAvatarURL, v)) +} + +// AvatarURLIsNil applies the IsNil predicate on the "avatar_url" field. +func AvatarURLIsNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIsNull(FieldAvatarURL)) +} + +// AvatarURLNotNil applies the NotNil predicate on the "avatar_url" field. +func AvatarURLNotNil() predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotNull(FieldAvatarURL)) +} + +// AvatarURLEqualFold applies the EqualFold predicate on the "avatar_url" field. +func AvatarURLEqualFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEqualFold(FieldAvatarURL, v)) +} + +// AvatarURLContainsFold applies the ContainsFold predicate on the "avatar_url" field. +func AvatarURLContainsFold(v string) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldContainsFold(FieldAvatarURL, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.UserIdentity { + return predicate.UserIdentity(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.UserIdentity { + return predicate.UserIdentity(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.UserIdentity { + return predicate.UserIdentity(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.UserIdentity) predicate.UserIdentity { + return predicate.UserIdentity(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserIdentity) predicate.UserIdentity { + return predicate.UserIdentity(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserIdentity) predicate.UserIdentity { + return predicate.UserIdentity(sql.NotPredicates(p)) +} diff --git a/backend/db/useridentity_create.go b/backend/db/useridentity_create.go new file mode 100644 index 0000000..7296bd8 --- /dev/null +++ b/backend/db/useridentity_create.go @@ -0,0 +1,1037 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/google/uuid" +) + +// UserIdentityCreate is the builder for creating a UserIdentity entity. +type UserIdentityCreate struct { + config + mutation *UserIdentityMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetUserID sets the "user_id" field. +func (uic *UserIdentityCreate) SetUserID(u uuid.UUID) *UserIdentityCreate { + uic.mutation.SetUserID(u) + return uic +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillableUserID(u *uuid.UUID) *UserIdentityCreate { + if u != nil { + uic.SetUserID(*u) + } + return uic +} + +// SetPlatform sets the "platform" field. +func (uic *UserIdentityCreate) SetPlatform(cp consts.UserPlatform) *UserIdentityCreate { + uic.mutation.SetPlatform(cp) + return uic +} + +// SetNillablePlatform sets the "platform" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillablePlatform(cp *consts.UserPlatform) *UserIdentityCreate { + if cp != nil { + uic.SetPlatform(*cp) + } + return uic +} + +// SetIdentityID sets the "identity_id" field. +func (uic *UserIdentityCreate) SetIdentityID(s string) *UserIdentityCreate { + uic.mutation.SetIdentityID(s) + return uic +} + +// SetUnionID sets the "union_id" field. +func (uic *UserIdentityCreate) SetUnionID(s string) *UserIdentityCreate { + uic.mutation.SetUnionID(s) + return uic +} + +// SetNillableUnionID sets the "union_id" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillableUnionID(s *string) *UserIdentityCreate { + if s != nil { + uic.SetUnionID(*s) + } + return uic +} + +// SetNickname sets the "nickname" field. +func (uic *UserIdentityCreate) SetNickname(s string) *UserIdentityCreate { + uic.mutation.SetNickname(s) + return uic +} + +// SetNillableNickname sets the "nickname" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillableNickname(s *string) *UserIdentityCreate { + if s != nil { + uic.SetNickname(*s) + } + return uic +} + +// SetEmail sets the "email" field. +func (uic *UserIdentityCreate) SetEmail(s string) *UserIdentityCreate { + uic.mutation.SetEmail(s) + return uic +} + +// SetNillableEmail sets the "email" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillableEmail(s *string) *UserIdentityCreate { + if s != nil { + uic.SetEmail(*s) + } + return uic +} + +// SetAvatarURL sets the "avatar_url" field. +func (uic *UserIdentityCreate) SetAvatarURL(s string) *UserIdentityCreate { + uic.mutation.SetAvatarURL(s) + return uic +} + +// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillableAvatarURL(s *string) *UserIdentityCreate { + if s != nil { + uic.SetAvatarURL(*s) + } + return uic +} + +// SetCreatedAt sets the "created_at" field. +func (uic *UserIdentityCreate) SetCreatedAt(t time.Time) *UserIdentityCreate { + uic.mutation.SetCreatedAt(t) + return uic +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (uic *UserIdentityCreate) SetNillableCreatedAt(t *time.Time) *UserIdentityCreate { + if t != nil { + uic.SetCreatedAt(*t) + } + return uic +} + +// SetID sets the "id" field. +func (uic *UserIdentityCreate) SetID(u uuid.UUID) *UserIdentityCreate { + uic.mutation.SetID(u) + return uic +} + +// SetUser sets the "user" edge to the User entity. +func (uic *UserIdentityCreate) SetUser(u *User) *UserIdentityCreate { + return uic.SetUserID(u.ID) +} + +// Mutation returns the UserIdentityMutation object of the builder. +func (uic *UserIdentityCreate) Mutation() *UserIdentityMutation { + return uic.mutation +} + +// Save creates the UserIdentity in the database. +func (uic *UserIdentityCreate) Save(ctx context.Context) (*UserIdentity, error) { + uic.defaults() + return withHooks(ctx, uic.sqlSave, uic.mutation, uic.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (uic *UserIdentityCreate) SaveX(ctx context.Context) *UserIdentity { + v, err := uic.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uic *UserIdentityCreate) Exec(ctx context.Context) error { + _, err := uic.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uic *UserIdentityCreate) ExecX(ctx context.Context) { + if err := uic.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (uic *UserIdentityCreate) defaults() { + if _, ok := uic.mutation.Platform(); !ok { + v := useridentity.DefaultPlatform + uic.mutation.SetPlatform(v) + } + if _, ok := uic.mutation.CreatedAt(); !ok { + v := useridentity.DefaultCreatedAt() + uic.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uic *UserIdentityCreate) check() error { + if _, ok := uic.mutation.Platform(); !ok { + return &ValidationError{Name: "platform", err: errors.New(`db: missing required field "UserIdentity.platform"`)} + } + if _, ok := uic.mutation.IdentityID(); !ok { + return &ValidationError{Name: "identity_id", err: errors.New(`db: missing required field "UserIdentity.identity_id"`)} + } + if _, ok := uic.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "UserIdentity.created_at"`)} + } + return nil +} + +func (uic *UserIdentityCreate) sqlSave(ctx context.Context) (*UserIdentity, error) { + if err := uic.check(); err != nil { + return nil, err + } + _node, _spec := uic.createSpec() + if err := sqlgraph.CreateNode(ctx, uic.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + uic.mutation.id = &_node.ID + uic.mutation.done = true + return _node, nil +} + +func (uic *UserIdentityCreate) createSpec() (*UserIdentity, *sqlgraph.CreateSpec) { + var ( + _node = &UserIdentity{config: uic.config} + _spec = sqlgraph.NewCreateSpec(useridentity.Table, sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = uic.conflict + if id, ok := uic.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := uic.mutation.Platform(); ok { + _spec.SetField(useridentity.FieldPlatform, field.TypeString, value) + _node.Platform = value + } + if value, ok := uic.mutation.IdentityID(); ok { + _spec.SetField(useridentity.FieldIdentityID, field.TypeString, value) + _node.IdentityID = value + } + if value, ok := uic.mutation.UnionID(); ok { + _spec.SetField(useridentity.FieldUnionID, field.TypeString, value) + _node.UnionID = value + } + if value, ok := uic.mutation.Nickname(); ok { + _spec.SetField(useridentity.FieldNickname, field.TypeString, value) + _node.Nickname = value + } + if value, ok := uic.mutation.Email(); ok { + _spec.SetField(useridentity.FieldEmail, field.TypeString, value) + _node.Email = value + } + if value, ok := uic.mutation.AvatarURL(); ok { + _spec.SetField(useridentity.FieldAvatarURL, field.TypeString, value) + _node.AvatarURL = value + } + if value, ok := uic.mutation.CreatedAt(); ok { + _spec.SetField(useridentity.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := uic.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: useridentity.UserTable, + Columns: []string{useridentity.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserIdentity.Create(). +// SetUserID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.UserIdentityUpsert) { +// SetUserID(v+v). +// }). +// Exec(ctx) +func (uic *UserIdentityCreate) OnConflict(opts ...sql.ConflictOption) *UserIdentityUpsertOne { + uic.conflict = opts + return &UserIdentityUpsertOne{ + create: uic, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserIdentity.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (uic *UserIdentityCreate) OnConflictColumns(columns ...string) *UserIdentityUpsertOne { + uic.conflict = append(uic.conflict, sql.ConflictColumns(columns...)) + return &UserIdentityUpsertOne{ + create: uic, + } +} + +type ( + // UserIdentityUpsertOne is the builder for "upsert"-ing + // one UserIdentity node. + UserIdentityUpsertOne struct { + create *UserIdentityCreate + } + + // UserIdentityUpsert is the "OnConflict" setter. + UserIdentityUpsert struct { + *sql.UpdateSet + } +) + +// SetUserID sets the "user_id" field. +func (u *UserIdentityUpsert) SetUserID(v uuid.UUID) *UserIdentityUpsert { + u.Set(useridentity.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateUserID() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldUserID) + return u +} + +// ClearUserID clears the value of the "user_id" field. +func (u *UserIdentityUpsert) ClearUserID() *UserIdentityUpsert { + u.SetNull(useridentity.FieldUserID) + return u +} + +// SetPlatform sets the "platform" field. +func (u *UserIdentityUpsert) SetPlatform(v consts.UserPlatform) *UserIdentityUpsert { + u.Set(useridentity.FieldPlatform, v) + return u +} + +// UpdatePlatform sets the "platform" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdatePlatform() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldPlatform) + return u +} + +// SetIdentityID sets the "identity_id" field. +func (u *UserIdentityUpsert) SetIdentityID(v string) *UserIdentityUpsert { + u.Set(useridentity.FieldIdentityID, v) + return u +} + +// UpdateIdentityID sets the "identity_id" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateIdentityID() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldIdentityID) + return u +} + +// SetUnionID sets the "union_id" field. +func (u *UserIdentityUpsert) SetUnionID(v string) *UserIdentityUpsert { + u.Set(useridentity.FieldUnionID, v) + return u +} + +// UpdateUnionID sets the "union_id" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateUnionID() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldUnionID) + return u +} + +// ClearUnionID clears the value of the "union_id" field. +func (u *UserIdentityUpsert) ClearUnionID() *UserIdentityUpsert { + u.SetNull(useridentity.FieldUnionID) + return u +} + +// SetNickname sets the "nickname" field. +func (u *UserIdentityUpsert) SetNickname(v string) *UserIdentityUpsert { + u.Set(useridentity.FieldNickname, v) + return u +} + +// UpdateNickname sets the "nickname" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateNickname() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldNickname) + return u +} + +// ClearNickname clears the value of the "nickname" field. +func (u *UserIdentityUpsert) ClearNickname() *UserIdentityUpsert { + u.SetNull(useridentity.FieldNickname) + return u +} + +// SetEmail sets the "email" field. +func (u *UserIdentityUpsert) SetEmail(v string) *UserIdentityUpsert { + u.Set(useridentity.FieldEmail, v) + return u +} + +// UpdateEmail sets the "email" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateEmail() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldEmail) + return u +} + +// ClearEmail clears the value of the "email" field. +func (u *UserIdentityUpsert) ClearEmail() *UserIdentityUpsert { + u.SetNull(useridentity.FieldEmail) + return u +} + +// SetAvatarURL sets the "avatar_url" field. +func (u *UserIdentityUpsert) SetAvatarURL(v string) *UserIdentityUpsert { + u.Set(useridentity.FieldAvatarURL, v) + return u +} + +// UpdateAvatarURL sets the "avatar_url" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateAvatarURL() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldAvatarURL) + return u +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (u *UserIdentityUpsert) ClearAvatarURL() *UserIdentityUpsert { + u.SetNull(useridentity.FieldAvatarURL) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *UserIdentityUpsert) SetCreatedAt(v time.Time) *UserIdentityUpsert { + u.Set(useridentity.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *UserIdentityUpsert) UpdateCreatedAt() *UserIdentityUpsert { + u.SetExcluded(useridentity.FieldCreatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.UserIdentity.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(useridentity.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserIdentityUpsertOne) UpdateNewValues() *UserIdentityUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(useridentity.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserIdentity.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserIdentityUpsertOne) Ignore() *UserIdentityUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *UserIdentityUpsertOne) DoNothing() *UserIdentityUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserIdentityCreate.OnConflict +// documentation for more info. +func (u *UserIdentityUpsertOne) Update(set func(*UserIdentityUpsert)) *UserIdentityUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserIdentityUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserID sets the "user_id" field. +func (u *UserIdentityUpsertOne) SetUserID(v uuid.UUID) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateUserID() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateUserID() + }) +} + +// ClearUserID clears the value of the "user_id" field. +func (u *UserIdentityUpsertOne) ClearUserID() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearUserID() + }) +} + +// SetPlatform sets the "platform" field. +func (u *UserIdentityUpsertOne) SetPlatform(v consts.UserPlatform) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetPlatform(v) + }) +} + +// UpdatePlatform sets the "platform" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdatePlatform() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdatePlatform() + }) +} + +// SetIdentityID sets the "identity_id" field. +func (u *UserIdentityUpsertOne) SetIdentityID(v string) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetIdentityID(v) + }) +} + +// UpdateIdentityID sets the "identity_id" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateIdentityID() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateIdentityID() + }) +} + +// SetUnionID sets the "union_id" field. +func (u *UserIdentityUpsertOne) SetUnionID(v string) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetUnionID(v) + }) +} + +// UpdateUnionID sets the "union_id" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateUnionID() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateUnionID() + }) +} + +// ClearUnionID clears the value of the "union_id" field. +func (u *UserIdentityUpsertOne) ClearUnionID() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearUnionID() + }) +} + +// SetNickname sets the "nickname" field. +func (u *UserIdentityUpsertOne) SetNickname(v string) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetNickname(v) + }) +} + +// UpdateNickname sets the "nickname" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateNickname() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateNickname() + }) +} + +// ClearNickname clears the value of the "nickname" field. +func (u *UserIdentityUpsertOne) ClearNickname() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearNickname() + }) +} + +// SetEmail sets the "email" field. +func (u *UserIdentityUpsertOne) SetEmail(v string) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetEmail(v) + }) +} + +// UpdateEmail sets the "email" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateEmail() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateEmail() + }) +} + +// ClearEmail clears the value of the "email" field. +func (u *UserIdentityUpsertOne) ClearEmail() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearEmail() + }) +} + +// SetAvatarURL sets the "avatar_url" field. +func (u *UserIdentityUpsertOne) SetAvatarURL(v string) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetAvatarURL(v) + }) +} + +// UpdateAvatarURL sets the "avatar_url" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateAvatarURL() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateAvatarURL() + }) +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (u *UserIdentityUpsertOne) ClearAvatarURL() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearAvatarURL() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *UserIdentityUpsertOne) SetCreatedAt(v time.Time) *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *UserIdentityUpsertOne) UpdateCreatedAt() *UserIdentityUpsertOne { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *UserIdentityUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserIdentityCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserIdentityUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *UserIdentityUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: UserIdentityUpsertOne.ID is not supported by MySQL driver. Use UserIdentityUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *UserIdentityUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// UserIdentityCreateBulk is the builder for creating many UserIdentity entities in bulk. +type UserIdentityCreateBulk struct { + config + err error + builders []*UserIdentityCreate + conflict []sql.ConflictOption +} + +// Save creates the UserIdentity entities in the database. +func (uicb *UserIdentityCreateBulk) Save(ctx context.Context) ([]*UserIdentity, error) { + if uicb.err != nil { + return nil, uicb.err + } + specs := make([]*sqlgraph.CreateSpec, len(uicb.builders)) + nodes := make([]*UserIdentity, len(uicb.builders)) + mutators := make([]Mutator, len(uicb.builders)) + for i := range uicb.builders { + func(i int, root context.Context) { + builder := uicb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserIdentityMutation) + 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, uicb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = uicb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, uicb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, uicb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (uicb *UserIdentityCreateBulk) SaveX(ctx context.Context) []*UserIdentity { + v, err := uicb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uicb *UserIdentityCreateBulk) Exec(ctx context.Context) error { + _, err := uicb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uicb *UserIdentityCreateBulk) ExecX(ctx context.Context) { + if err := uicb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserIdentity.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.UserIdentityUpsert) { +// SetUserID(v+v). +// }). +// Exec(ctx) +func (uicb *UserIdentityCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserIdentityUpsertBulk { + uicb.conflict = opts + return &UserIdentityUpsertBulk{ + create: uicb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserIdentity.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (uicb *UserIdentityCreateBulk) OnConflictColumns(columns ...string) *UserIdentityUpsertBulk { + uicb.conflict = append(uicb.conflict, sql.ConflictColumns(columns...)) + return &UserIdentityUpsertBulk{ + create: uicb, + } +} + +// UserIdentityUpsertBulk is the builder for "upsert"-ing +// a bulk of UserIdentity nodes. +type UserIdentityUpsertBulk struct { + create *UserIdentityCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.UserIdentity.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(useridentity.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserIdentityUpsertBulk) UpdateNewValues() *UserIdentityUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(useridentity.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserIdentity.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserIdentityUpsertBulk) Ignore() *UserIdentityUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *UserIdentityUpsertBulk) DoNothing() *UserIdentityUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserIdentityCreateBulk.OnConflict +// documentation for more info. +func (u *UserIdentityUpsertBulk) Update(set func(*UserIdentityUpsert)) *UserIdentityUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserIdentityUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserID sets the "user_id" field. +func (u *UserIdentityUpsertBulk) SetUserID(v uuid.UUID) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateUserID() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateUserID() + }) +} + +// ClearUserID clears the value of the "user_id" field. +func (u *UserIdentityUpsertBulk) ClearUserID() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearUserID() + }) +} + +// SetPlatform sets the "platform" field. +func (u *UserIdentityUpsertBulk) SetPlatform(v consts.UserPlatform) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetPlatform(v) + }) +} + +// UpdatePlatform sets the "platform" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdatePlatform() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdatePlatform() + }) +} + +// SetIdentityID sets the "identity_id" field. +func (u *UserIdentityUpsertBulk) SetIdentityID(v string) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetIdentityID(v) + }) +} + +// UpdateIdentityID sets the "identity_id" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateIdentityID() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateIdentityID() + }) +} + +// SetUnionID sets the "union_id" field. +func (u *UserIdentityUpsertBulk) SetUnionID(v string) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetUnionID(v) + }) +} + +// UpdateUnionID sets the "union_id" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateUnionID() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateUnionID() + }) +} + +// ClearUnionID clears the value of the "union_id" field. +func (u *UserIdentityUpsertBulk) ClearUnionID() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearUnionID() + }) +} + +// SetNickname sets the "nickname" field. +func (u *UserIdentityUpsertBulk) SetNickname(v string) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetNickname(v) + }) +} + +// UpdateNickname sets the "nickname" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateNickname() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateNickname() + }) +} + +// ClearNickname clears the value of the "nickname" field. +func (u *UserIdentityUpsertBulk) ClearNickname() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearNickname() + }) +} + +// SetEmail sets the "email" field. +func (u *UserIdentityUpsertBulk) SetEmail(v string) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetEmail(v) + }) +} + +// UpdateEmail sets the "email" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateEmail() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateEmail() + }) +} + +// ClearEmail clears the value of the "email" field. +func (u *UserIdentityUpsertBulk) ClearEmail() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearEmail() + }) +} + +// SetAvatarURL sets the "avatar_url" field. +func (u *UserIdentityUpsertBulk) SetAvatarURL(v string) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetAvatarURL(v) + }) +} + +// UpdateAvatarURL sets the "avatar_url" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateAvatarURL() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateAvatarURL() + }) +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (u *UserIdentityUpsertBulk) ClearAvatarURL() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.ClearAvatarURL() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *UserIdentityUpsertBulk) SetCreatedAt(v time.Time) *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *UserIdentityUpsertBulk) UpdateCreatedAt() *UserIdentityUpsertBulk { + return u.Update(func(s *UserIdentityUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *UserIdentityUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the UserIdentityCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserIdentityCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserIdentityUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/useridentity_delete.go b/backend/db/useridentity_delete.go new file mode 100644 index 0000000..35cb8e1 --- /dev/null +++ b/backend/db/useridentity_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" +) + +// UserIdentityDelete is the builder for deleting a UserIdentity entity. +type UserIdentityDelete struct { + config + hooks []Hook + mutation *UserIdentityMutation +} + +// Where appends a list predicates to the UserIdentityDelete builder. +func (uid *UserIdentityDelete) Where(ps ...predicate.UserIdentity) *UserIdentityDelete { + uid.mutation.Where(ps...) + return uid +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (uid *UserIdentityDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, uid.sqlExec, uid.mutation, uid.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (uid *UserIdentityDelete) ExecX(ctx context.Context) int { + n, err := uid.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (uid *UserIdentityDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(useridentity.Table, sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID)) + if ps := uid.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, uid.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + uid.mutation.done = true + return affected, err +} + +// UserIdentityDeleteOne is the builder for deleting a single UserIdentity entity. +type UserIdentityDeleteOne struct { + uid *UserIdentityDelete +} + +// Where appends a list predicates to the UserIdentityDelete builder. +func (uido *UserIdentityDeleteOne) Where(ps ...predicate.UserIdentity) *UserIdentityDeleteOne { + uido.uid.mutation.Where(ps...) + return uido +} + +// Exec executes the deletion query. +func (uido *UserIdentityDeleteOne) Exec(ctx context.Context) error { + n, err := uido.uid.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{useridentity.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (uido *UserIdentityDeleteOne) ExecX(ctx context.Context) { + if err := uido.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/useridentity_query.go b/backend/db/useridentity_query.go new file mode 100644 index 0000000..48b1769 --- /dev/null +++ b/backend/db/useridentity_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/google/uuid" +) + +// UserIdentityQuery is the builder for querying UserIdentity entities. +type UserIdentityQuery struct { + config + ctx *QueryContext + order []useridentity.OrderOption + inters []Interceptor + predicates []predicate.UserIdentity + withUser *UserQuery + 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 UserIdentityQuery builder. +func (uiq *UserIdentityQuery) Where(ps ...predicate.UserIdentity) *UserIdentityQuery { + uiq.predicates = append(uiq.predicates, ps...) + return uiq +} + +// Limit the number of records to be returned by this query. +func (uiq *UserIdentityQuery) Limit(limit int) *UserIdentityQuery { + uiq.ctx.Limit = &limit + return uiq +} + +// Offset to start from. +func (uiq *UserIdentityQuery) Offset(offset int) *UserIdentityQuery { + uiq.ctx.Offset = &offset + return uiq +} + +// 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 (uiq *UserIdentityQuery) Unique(unique bool) *UserIdentityQuery { + uiq.ctx.Unique = &unique + return uiq +} + +// Order specifies how the records should be ordered. +func (uiq *UserIdentityQuery) Order(o ...useridentity.OrderOption) *UserIdentityQuery { + uiq.order = append(uiq.order, o...) + return uiq +} + +// QueryUser chains the current query on the "user" edge. +func (uiq *UserIdentityQuery) QueryUser() *UserQuery { + query := (&UserClient{config: uiq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uiq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uiq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(useridentity.Table, useridentity.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, useridentity.UserTable, useridentity.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(uiq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserIdentity entity from the query. +// Returns a *NotFoundError when no UserIdentity was found. +func (uiq *UserIdentityQuery) First(ctx context.Context) (*UserIdentity, error) { + nodes, err := uiq.Limit(1).All(setContextOp(ctx, uiq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{useridentity.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (uiq *UserIdentityQuery) FirstX(ctx context.Context) *UserIdentity { + node, err := uiq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserIdentity ID from the query. +// Returns a *NotFoundError when no UserIdentity ID was found. +func (uiq *UserIdentityQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = uiq.Limit(1).IDs(setContextOp(ctx, uiq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{useridentity.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (uiq *UserIdentityQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := uiq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserIdentity entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserIdentity entity is found. +// Returns a *NotFoundError when no UserIdentity entities are found. +func (uiq *UserIdentityQuery) Only(ctx context.Context) (*UserIdentity, error) { + nodes, err := uiq.Limit(2).All(setContextOp(ctx, uiq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{useridentity.Label} + default: + return nil, &NotSingularError{useridentity.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (uiq *UserIdentityQuery) OnlyX(ctx context.Context) *UserIdentity { + node, err := uiq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserIdentity ID in the query. +// Returns a *NotSingularError when more than one UserIdentity ID is found. +// Returns a *NotFoundError when no entities are found. +func (uiq *UserIdentityQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = uiq.Limit(2).IDs(setContextOp(ctx, uiq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{useridentity.Label} + default: + err = &NotSingularError{useridentity.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (uiq *UserIdentityQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := uiq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserIdentities. +func (uiq *UserIdentityQuery) All(ctx context.Context) ([]*UserIdentity, error) { + ctx = setContextOp(ctx, uiq.ctx, ent.OpQueryAll) + if err := uiq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserIdentity, *UserIdentityQuery]() + return withInterceptors[[]*UserIdentity](ctx, uiq, qr, uiq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (uiq *UserIdentityQuery) AllX(ctx context.Context) []*UserIdentity { + nodes, err := uiq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserIdentity IDs. +func (uiq *UserIdentityQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if uiq.ctx.Unique == nil && uiq.path != nil { + uiq.Unique(true) + } + ctx = setContextOp(ctx, uiq.ctx, ent.OpQueryIDs) + if err = uiq.Select(useridentity.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (uiq *UserIdentityQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := uiq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uiq *UserIdentityQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, uiq.ctx, ent.OpQueryCount) + if err := uiq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, uiq, querierCount[*UserIdentityQuery](), uiq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (uiq *UserIdentityQuery) CountX(ctx context.Context) int { + count, err := uiq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uiq *UserIdentityQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, uiq.ctx, ent.OpQueryExist) + switch _, err := uiq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (uiq *UserIdentityQuery) ExistX(ctx context.Context) bool { + exist, err := uiq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserIdentityQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (uiq *UserIdentityQuery) Clone() *UserIdentityQuery { + if uiq == nil { + return nil + } + return &UserIdentityQuery{ + config: uiq.config, + ctx: uiq.ctx.Clone(), + order: append([]useridentity.OrderOption{}, uiq.order...), + inters: append([]Interceptor{}, uiq.inters...), + predicates: append([]predicate.UserIdentity{}, uiq.predicates...), + withUser: uiq.withUser.Clone(), + // clone intermediate query. + sql: uiq.sql.Clone(), + path: uiq.path, + modifiers: append([]func(*sql.Selector){}, uiq.modifiers...), + } +} + +// 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 (uiq *UserIdentityQuery) WithUser(opts ...func(*UserQuery)) *UserIdentityQuery { + query := (&UserClient{config: uiq.config}).Query() + for _, opt := range opts { + opt(query) + } + uiq.withUser = query + return uiq +} + +// 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 { +// UserID uuid.UUID `json:"user_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserIdentity.Query(). +// GroupBy(useridentity.FieldUserID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (uiq *UserIdentityQuery) GroupBy(field string, fields ...string) *UserIdentityGroupBy { + uiq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserIdentityGroupBy{build: uiq} + grbuild.flds = &uiq.ctx.Fields + grbuild.label = useridentity.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 { +// UserID uuid.UUID `json:"user_id,omitempty"` +// } +// +// client.UserIdentity.Query(). +// Select(useridentity.FieldUserID). +// Scan(ctx, &v) +func (uiq *UserIdentityQuery) Select(fields ...string) *UserIdentitySelect { + uiq.ctx.Fields = append(uiq.ctx.Fields, fields...) + sbuild := &UserIdentitySelect{UserIdentityQuery: uiq} + sbuild.label = useridentity.Label + sbuild.flds, sbuild.scan = &uiq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserIdentitySelect configured with the given aggregations. +func (uiq *UserIdentityQuery) Aggregate(fns ...AggregateFunc) *UserIdentitySelect { + return uiq.Select().Aggregate(fns...) +} + +func (uiq *UserIdentityQuery) prepareQuery(ctx context.Context) error { + for _, inter := range uiq.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, uiq); err != nil { + return err + } + } + } + for _, f := range uiq.ctx.Fields { + if !useridentity.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if uiq.path != nil { + prev, err := uiq.path(ctx) + if err != nil { + return err + } + uiq.sql = prev + } + return nil +} + +func (uiq *UserIdentityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserIdentity, error) { + var ( + nodes = []*UserIdentity{} + _spec = uiq.querySpec() + loadedTypes = [1]bool{ + uiq.withUser != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserIdentity).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserIdentity{config: uiq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(uiq.modifiers) > 0 { + _spec.Modifiers = uiq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, uiq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := uiq.withUser; query != nil { + if err := uiq.loadUser(ctx, query, nodes, nil, + func(n *UserIdentity, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (uiq *UserIdentityQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserIdentity, init func(*UserIdentity), assign func(*UserIdentity, *User)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*UserIdentity) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (uiq *UserIdentityQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uiq.querySpec() + if len(uiq.modifiers) > 0 { + _spec.Modifiers = uiq.modifiers + } + _spec.Node.Columns = uiq.ctx.Fields + if len(uiq.ctx.Fields) > 0 { + _spec.Unique = uiq.ctx.Unique != nil && *uiq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, uiq.driver, _spec) +} + +func (uiq *UserIdentityQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(useridentity.Table, useridentity.Columns, sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID)) + _spec.From = uiq.sql + if unique := uiq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if uiq.path != nil { + _spec.Unique = true + } + if fields := uiq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, useridentity.FieldID) + for i := range fields { + if fields[i] != useridentity.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if uiq.withUser != nil { + _spec.Node.AddColumnOnce(useridentity.FieldUserID) + } + } + if ps := uiq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uiq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := uiq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := uiq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uiq *UserIdentityQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uiq.driver.Dialect()) + t1 := builder.Table(useridentity.Table) + columns := uiq.ctx.Fields + if len(columns) == 0 { + columns = useridentity.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uiq.sql != nil { + selector = uiq.sql + selector.Select(selector.Columns(columns...)...) + } + if uiq.ctx.Unique != nil && *uiq.ctx.Unique { + selector.Distinct() + } + for _, m := range uiq.modifiers { + m(selector) + } + for _, p := range uiq.predicates { + p(selector) + } + for _, p := range uiq.order { + p(selector) + } + if offset := uiq.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 := uiq.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 (uiq *UserIdentityQuery) ForUpdate(opts ...sql.LockOption) *UserIdentityQuery { + if uiq.driver.Dialect() == dialect.Postgres { + uiq.Unique(false) + } + uiq.modifiers = append(uiq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return uiq +} + +// 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 (uiq *UserIdentityQuery) ForShare(opts ...sql.LockOption) *UserIdentityQuery { + if uiq.driver.Dialect() == dialect.Postgres { + uiq.Unique(false) + } + uiq.modifiers = append(uiq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return uiq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (uiq *UserIdentityQuery) Modify(modifiers ...func(s *sql.Selector)) *UserIdentitySelect { + uiq.modifiers = append(uiq.modifiers, modifiers...) + return uiq.Select() +} + +// UserIdentityGroupBy is the group-by builder for UserIdentity entities. +type UserIdentityGroupBy struct { + selector + build *UserIdentityQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (uigb *UserIdentityGroupBy) Aggregate(fns ...AggregateFunc) *UserIdentityGroupBy { + uigb.fns = append(uigb.fns, fns...) + return uigb +} + +// Scan applies the selector query and scans the result into the given value. +func (uigb *UserIdentityGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, uigb.build.ctx, ent.OpQueryGroupBy) + if err := uigb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserIdentityQuery, *UserIdentityGroupBy](ctx, uigb.build, uigb, uigb.build.inters, v) +} + +func (uigb *UserIdentityGroupBy) sqlScan(ctx context.Context, root *UserIdentityQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(uigb.fns)) + for _, fn := range uigb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*uigb.flds)+len(uigb.fns)) + for _, f := range *uigb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*uigb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := uigb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserIdentitySelect is the builder for selecting fields of UserIdentity entities. +type UserIdentitySelect struct { + *UserIdentityQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (uis *UserIdentitySelect) Aggregate(fns ...AggregateFunc) *UserIdentitySelect { + uis.fns = append(uis.fns, fns...) + return uis +} + +// Scan applies the selector query and scans the result into the given value. +func (uis *UserIdentitySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, uis.ctx, ent.OpQuerySelect) + if err := uis.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserIdentityQuery, *UserIdentitySelect](ctx, uis.UserIdentityQuery, uis, uis.inters, v) +} + +func (uis *UserIdentitySelect) sqlScan(ctx context.Context, root *UserIdentityQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(uis.fns)) + for _, fn := range uis.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*uis.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 := uis.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (uis *UserIdentitySelect) Modify(modifiers ...func(s *sql.Selector)) *UserIdentitySelect { + uis.modifiers = append(uis.modifiers, modifiers...) + return uis +} diff --git a/backend/db/useridentity_update.go b/backend/db/useridentity_update.go new file mode 100644 index 0000000..235ac9f --- /dev/null +++ b/backend/db/useridentity_update.go @@ -0,0 +1,625 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/google/uuid" +) + +// UserIdentityUpdate is the builder for updating UserIdentity entities. +type UserIdentityUpdate struct { + config + hooks []Hook + mutation *UserIdentityMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the UserIdentityUpdate builder. +func (uiu *UserIdentityUpdate) Where(ps ...predicate.UserIdentity) *UserIdentityUpdate { + uiu.mutation.Where(ps...) + return uiu +} + +// SetUserID sets the "user_id" field. +func (uiu *UserIdentityUpdate) SetUserID(u uuid.UUID) *UserIdentityUpdate { + uiu.mutation.SetUserID(u) + return uiu +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableUserID(u *uuid.UUID) *UserIdentityUpdate { + if u != nil { + uiu.SetUserID(*u) + } + return uiu +} + +// ClearUserID clears the value of the "user_id" field. +func (uiu *UserIdentityUpdate) ClearUserID() *UserIdentityUpdate { + uiu.mutation.ClearUserID() + return uiu +} + +// SetPlatform sets the "platform" field. +func (uiu *UserIdentityUpdate) SetPlatform(cp consts.UserPlatform) *UserIdentityUpdate { + uiu.mutation.SetPlatform(cp) + return uiu +} + +// SetNillablePlatform sets the "platform" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillablePlatform(cp *consts.UserPlatform) *UserIdentityUpdate { + if cp != nil { + uiu.SetPlatform(*cp) + } + return uiu +} + +// SetIdentityID sets the "identity_id" field. +func (uiu *UserIdentityUpdate) SetIdentityID(s string) *UserIdentityUpdate { + uiu.mutation.SetIdentityID(s) + return uiu +} + +// SetNillableIdentityID sets the "identity_id" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableIdentityID(s *string) *UserIdentityUpdate { + if s != nil { + uiu.SetIdentityID(*s) + } + return uiu +} + +// SetUnionID sets the "union_id" field. +func (uiu *UserIdentityUpdate) SetUnionID(s string) *UserIdentityUpdate { + uiu.mutation.SetUnionID(s) + return uiu +} + +// SetNillableUnionID sets the "union_id" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableUnionID(s *string) *UserIdentityUpdate { + if s != nil { + uiu.SetUnionID(*s) + } + return uiu +} + +// ClearUnionID clears the value of the "union_id" field. +func (uiu *UserIdentityUpdate) ClearUnionID() *UserIdentityUpdate { + uiu.mutation.ClearUnionID() + return uiu +} + +// SetNickname sets the "nickname" field. +func (uiu *UserIdentityUpdate) SetNickname(s string) *UserIdentityUpdate { + uiu.mutation.SetNickname(s) + return uiu +} + +// SetNillableNickname sets the "nickname" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableNickname(s *string) *UserIdentityUpdate { + if s != nil { + uiu.SetNickname(*s) + } + return uiu +} + +// ClearNickname clears the value of the "nickname" field. +func (uiu *UserIdentityUpdate) ClearNickname() *UserIdentityUpdate { + uiu.mutation.ClearNickname() + return uiu +} + +// SetEmail sets the "email" field. +func (uiu *UserIdentityUpdate) SetEmail(s string) *UserIdentityUpdate { + uiu.mutation.SetEmail(s) + return uiu +} + +// SetNillableEmail sets the "email" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableEmail(s *string) *UserIdentityUpdate { + if s != nil { + uiu.SetEmail(*s) + } + return uiu +} + +// ClearEmail clears the value of the "email" field. +func (uiu *UserIdentityUpdate) ClearEmail() *UserIdentityUpdate { + uiu.mutation.ClearEmail() + return uiu +} + +// SetAvatarURL sets the "avatar_url" field. +func (uiu *UserIdentityUpdate) SetAvatarURL(s string) *UserIdentityUpdate { + uiu.mutation.SetAvatarURL(s) + return uiu +} + +// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableAvatarURL(s *string) *UserIdentityUpdate { + if s != nil { + uiu.SetAvatarURL(*s) + } + return uiu +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (uiu *UserIdentityUpdate) ClearAvatarURL() *UserIdentityUpdate { + uiu.mutation.ClearAvatarURL() + return uiu +} + +// SetCreatedAt sets the "created_at" field. +func (uiu *UserIdentityUpdate) SetCreatedAt(t time.Time) *UserIdentityUpdate { + uiu.mutation.SetCreatedAt(t) + return uiu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (uiu *UserIdentityUpdate) SetNillableCreatedAt(t *time.Time) *UserIdentityUpdate { + if t != nil { + uiu.SetCreatedAt(*t) + } + return uiu +} + +// SetUser sets the "user" edge to the User entity. +func (uiu *UserIdentityUpdate) SetUser(u *User) *UserIdentityUpdate { + return uiu.SetUserID(u.ID) +} + +// Mutation returns the UserIdentityMutation object of the builder. +func (uiu *UserIdentityUpdate) Mutation() *UserIdentityMutation { + return uiu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (uiu *UserIdentityUpdate) ClearUser() *UserIdentityUpdate { + uiu.mutation.ClearUser() + return uiu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (uiu *UserIdentityUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, uiu.sqlSave, uiu.mutation, uiu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uiu *UserIdentityUpdate) SaveX(ctx context.Context) int { + affected, err := uiu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uiu *UserIdentityUpdate) Exec(ctx context.Context) error { + _, err := uiu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uiu *UserIdentityUpdate) ExecX(ctx context.Context) { + if err := uiu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uiu *UserIdentityUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserIdentityUpdate { + uiu.modifiers = append(uiu.modifiers, modifiers...) + return uiu +} + +func (uiu *UserIdentityUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(useridentity.Table, useridentity.Columns, sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID)) + if ps := uiu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uiu.mutation.Platform(); ok { + _spec.SetField(useridentity.FieldPlatform, field.TypeString, value) + } + if value, ok := uiu.mutation.IdentityID(); ok { + _spec.SetField(useridentity.FieldIdentityID, field.TypeString, value) + } + if value, ok := uiu.mutation.UnionID(); ok { + _spec.SetField(useridentity.FieldUnionID, field.TypeString, value) + } + if uiu.mutation.UnionIDCleared() { + _spec.ClearField(useridentity.FieldUnionID, field.TypeString) + } + if value, ok := uiu.mutation.Nickname(); ok { + _spec.SetField(useridentity.FieldNickname, field.TypeString, value) + } + if uiu.mutation.NicknameCleared() { + _spec.ClearField(useridentity.FieldNickname, field.TypeString) + } + if value, ok := uiu.mutation.Email(); ok { + _spec.SetField(useridentity.FieldEmail, field.TypeString, value) + } + if uiu.mutation.EmailCleared() { + _spec.ClearField(useridentity.FieldEmail, field.TypeString) + } + if value, ok := uiu.mutation.AvatarURL(); ok { + _spec.SetField(useridentity.FieldAvatarURL, field.TypeString, value) + } + if uiu.mutation.AvatarURLCleared() { + _spec.ClearField(useridentity.FieldAvatarURL, field.TypeString) + } + if value, ok := uiu.mutation.CreatedAt(); ok { + _spec.SetField(useridentity.FieldCreatedAt, field.TypeTime, value) + } + if uiu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: useridentity.UserTable, + Columns: []string{useridentity.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uiu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: useridentity.UserTable, + Columns: []string{useridentity.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(uiu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, uiu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{useridentity.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + uiu.mutation.done = true + return n, nil +} + +// UserIdentityUpdateOne is the builder for updating a single UserIdentity entity. +type UserIdentityUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserIdentityMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetUserID sets the "user_id" field. +func (uiuo *UserIdentityUpdateOne) SetUserID(u uuid.UUID) *UserIdentityUpdateOne { + uiuo.mutation.SetUserID(u) + return uiuo +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableUserID(u *uuid.UUID) *UserIdentityUpdateOne { + if u != nil { + uiuo.SetUserID(*u) + } + return uiuo +} + +// ClearUserID clears the value of the "user_id" field. +func (uiuo *UserIdentityUpdateOne) ClearUserID() *UserIdentityUpdateOne { + uiuo.mutation.ClearUserID() + return uiuo +} + +// SetPlatform sets the "platform" field. +func (uiuo *UserIdentityUpdateOne) SetPlatform(cp consts.UserPlatform) *UserIdentityUpdateOne { + uiuo.mutation.SetPlatform(cp) + return uiuo +} + +// SetNillablePlatform sets the "platform" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillablePlatform(cp *consts.UserPlatform) *UserIdentityUpdateOne { + if cp != nil { + uiuo.SetPlatform(*cp) + } + return uiuo +} + +// SetIdentityID sets the "identity_id" field. +func (uiuo *UserIdentityUpdateOne) SetIdentityID(s string) *UserIdentityUpdateOne { + uiuo.mutation.SetIdentityID(s) + return uiuo +} + +// SetNillableIdentityID sets the "identity_id" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableIdentityID(s *string) *UserIdentityUpdateOne { + if s != nil { + uiuo.SetIdentityID(*s) + } + return uiuo +} + +// SetUnionID sets the "union_id" field. +func (uiuo *UserIdentityUpdateOne) SetUnionID(s string) *UserIdentityUpdateOne { + uiuo.mutation.SetUnionID(s) + return uiuo +} + +// SetNillableUnionID sets the "union_id" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableUnionID(s *string) *UserIdentityUpdateOne { + if s != nil { + uiuo.SetUnionID(*s) + } + return uiuo +} + +// ClearUnionID clears the value of the "union_id" field. +func (uiuo *UserIdentityUpdateOne) ClearUnionID() *UserIdentityUpdateOne { + uiuo.mutation.ClearUnionID() + return uiuo +} + +// SetNickname sets the "nickname" field. +func (uiuo *UserIdentityUpdateOne) SetNickname(s string) *UserIdentityUpdateOne { + uiuo.mutation.SetNickname(s) + return uiuo +} + +// SetNillableNickname sets the "nickname" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableNickname(s *string) *UserIdentityUpdateOne { + if s != nil { + uiuo.SetNickname(*s) + } + return uiuo +} + +// ClearNickname clears the value of the "nickname" field. +func (uiuo *UserIdentityUpdateOne) ClearNickname() *UserIdentityUpdateOne { + uiuo.mutation.ClearNickname() + return uiuo +} + +// SetEmail sets the "email" field. +func (uiuo *UserIdentityUpdateOne) SetEmail(s string) *UserIdentityUpdateOne { + uiuo.mutation.SetEmail(s) + return uiuo +} + +// SetNillableEmail sets the "email" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableEmail(s *string) *UserIdentityUpdateOne { + if s != nil { + uiuo.SetEmail(*s) + } + return uiuo +} + +// ClearEmail clears the value of the "email" field. +func (uiuo *UserIdentityUpdateOne) ClearEmail() *UserIdentityUpdateOne { + uiuo.mutation.ClearEmail() + return uiuo +} + +// SetAvatarURL sets the "avatar_url" field. +func (uiuo *UserIdentityUpdateOne) SetAvatarURL(s string) *UserIdentityUpdateOne { + uiuo.mutation.SetAvatarURL(s) + return uiuo +} + +// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableAvatarURL(s *string) *UserIdentityUpdateOne { + if s != nil { + uiuo.SetAvatarURL(*s) + } + return uiuo +} + +// ClearAvatarURL clears the value of the "avatar_url" field. +func (uiuo *UserIdentityUpdateOne) ClearAvatarURL() *UserIdentityUpdateOne { + uiuo.mutation.ClearAvatarURL() + return uiuo +} + +// SetCreatedAt sets the "created_at" field. +func (uiuo *UserIdentityUpdateOne) SetCreatedAt(t time.Time) *UserIdentityUpdateOne { + uiuo.mutation.SetCreatedAt(t) + return uiuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (uiuo *UserIdentityUpdateOne) SetNillableCreatedAt(t *time.Time) *UserIdentityUpdateOne { + if t != nil { + uiuo.SetCreatedAt(*t) + } + return uiuo +} + +// SetUser sets the "user" edge to the User entity. +func (uiuo *UserIdentityUpdateOne) SetUser(u *User) *UserIdentityUpdateOne { + return uiuo.SetUserID(u.ID) +} + +// Mutation returns the UserIdentityMutation object of the builder. +func (uiuo *UserIdentityUpdateOne) Mutation() *UserIdentityMutation { + return uiuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (uiuo *UserIdentityUpdateOne) ClearUser() *UserIdentityUpdateOne { + uiuo.mutation.ClearUser() + return uiuo +} + +// Where appends a list predicates to the UserIdentityUpdate builder. +func (uiuo *UserIdentityUpdateOne) Where(ps ...predicate.UserIdentity) *UserIdentityUpdateOne { + uiuo.mutation.Where(ps...) + return uiuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uiuo *UserIdentityUpdateOne) Select(field string, fields ...string) *UserIdentityUpdateOne { + uiuo.fields = append([]string{field}, fields...) + return uiuo +} + +// Save executes the query and returns the updated UserIdentity entity. +func (uiuo *UserIdentityUpdateOne) Save(ctx context.Context) (*UserIdentity, error) { + return withHooks(ctx, uiuo.sqlSave, uiuo.mutation, uiuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uiuo *UserIdentityUpdateOne) SaveX(ctx context.Context) *UserIdentity { + node, err := uiuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uiuo *UserIdentityUpdateOne) Exec(ctx context.Context) error { + _, err := uiuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uiuo *UserIdentityUpdateOne) ExecX(ctx context.Context) { + if err := uiuo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uiuo *UserIdentityUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserIdentityUpdateOne { + uiuo.modifiers = append(uiuo.modifiers, modifiers...) + return uiuo +} + +func (uiuo *UserIdentityUpdateOne) sqlSave(ctx context.Context) (_node *UserIdentity, err error) { + _spec := sqlgraph.NewUpdateSpec(useridentity.Table, useridentity.Columns, sqlgraph.NewFieldSpec(useridentity.FieldID, field.TypeUUID)) + id, ok := uiuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "UserIdentity.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uiuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, useridentity.FieldID) + for _, f := range fields { + if !useridentity.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != useridentity.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uiuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uiuo.mutation.Platform(); ok { + _spec.SetField(useridentity.FieldPlatform, field.TypeString, value) + } + if value, ok := uiuo.mutation.IdentityID(); ok { + _spec.SetField(useridentity.FieldIdentityID, field.TypeString, value) + } + if value, ok := uiuo.mutation.UnionID(); ok { + _spec.SetField(useridentity.FieldUnionID, field.TypeString, value) + } + if uiuo.mutation.UnionIDCleared() { + _spec.ClearField(useridentity.FieldUnionID, field.TypeString) + } + if value, ok := uiuo.mutation.Nickname(); ok { + _spec.SetField(useridentity.FieldNickname, field.TypeString, value) + } + if uiuo.mutation.NicknameCleared() { + _spec.ClearField(useridentity.FieldNickname, field.TypeString) + } + if value, ok := uiuo.mutation.Email(); ok { + _spec.SetField(useridentity.FieldEmail, field.TypeString, value) + } + if uiuo.mutation.EmailCleared() { + _spec.ClearField(useridentity.FieldEmail, field.TypeString) + } + if value, ok := uiuo.mutation.AvatarURL(); ok { + _spec.SetField(useridentity.FieldAvatarURL, field.TypeString, value) + } + if uiuo.mutation.AvatarURLCleared() { + _spec.ClearField(useridentity.FieldAvatarURL, field.TypeString) + } + if value, ok := uiuo.mutation.CreatedAt(); ok { + _spec.SetField(useridentity.FieldCreatedAt, field.TypeTime, value) + } + if uiuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: useridentity.UserTable, + Columns: []string{useridentity.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uiuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: useridentity.UserTable, + Columns: []string{useridentity.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(uiuo.modifiers...) + _node = &UserIdentity{config: uiuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uiuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{useridentity.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + uiuo.mutation.done = true + return _node, nil +} diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json index 715ad54..89063ed 100644 --- a/backend/docs/swagger.json +++ b/backend/docs/swagger.json @@ -1375,6 +1375,121 @@ } } }, + "/api/v1/user/oauth/callback": { + "get": { + "description": "用户 OAuth 回调", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户 OAuth 回调", + "operationId": "user-oauth-callback", + "parameters": [ + { + "type": "string", + "name": "code", + "in": "query", + "required": true + }, + { + "type": "string", + "name": "state", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "string" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/oauth/signup-or-in": { + "get": { + "description": "用户 OAuth 登录或注册", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户 OAuth 登录或注册", + "operationId": "user-oauth-signup-or-in", + "parameters": [ + { + "enum": [ + "email", + "dingtalk" + ], + "type": "string", + "x-enum-varnames": [ + "UserPlatformEmail", + "UserPlatformDingTalk" + ], + "description": "第三方平台 dingtalk", + "name": "platform", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "登录成功后跳转的 URL", + "name": "redirect_url", + "in": "query" + }, + { + "type": "string", + "description": "会话ID", + "name": "session_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.OAuthURLResp" + } + } + } + ] + } + } + } + } + }, "/api/v1/user/register": { "post": { "description": "注册用户", @@ -1653,6 +1768,17 @@ "ModelTypeReranker" ] }, + "consts.UserPlatform": { + "type": "string", + "enum": [ + "email", + "dingtalk" + ], + "x-enum-varnames": [ + "UserPlatformEmail", + "UserPlatformDingTalk" + ] + }, "consts.UserStatus": { "type": "string", "enum": [ @@ -2312,6 +2438,14 @@ } } }, + "domain.OAuthURLResp": { + "type": "object", + "properties": { + "url": { + "type": "string" + } + } + }, "domain.ProviderModel": { "type": "object", "properties": { @@ -2356,6 +2490,10 @@ "description": "是否禁用密码登录", "type": "boolean" }, + "enable_dingtalk_oauth": { + "description": "是否开启钉钉OAuth", + "type": "boolean" + }, "enable_sso": { "description": "是否开启SSO", "type": "boolean" @@ -2546,10 +2684,22 @@ "domain.UpdateSettingReq": { "type": "object", "properties": { + "dingtalk_client_id": { + "description": "钉钉客户端ID", + "type": "string" + }, + "dingtalk_client_secret": { + "description": "钉钉客户端密钥", + "type": "string" + }, "disable_password_login": { "description": "是否禁用密码登录", "type": "boolean" }, + "enable_dingtalk_oauth": { + "description": "是否开启钉钉OAuth", + "type": "boolean" + }, "enable_sso": { "description": "是否开启SSO", "type": "boolean" diff --git a/backend/domain/oauth.go b/backend/domain/oauth.go new file mode 100644 index 0000000..776053c --- /dev/null +++ b/backend/domain/oauth.go @@ -0,0 +1,46 @@ +package domain + +import "github.com/chaitin/MonkeyCode/backend/consts" + +type OAuther interface { + GetAuthorizeURL() (state string, url string) + GetUserInfo(code string) (*OAuthUserInfo, error) +} + +type OAuthConfig struct { + Debug bool + Platform consts.UserPlatform + ClientID string + ClientSecret string + RedirectURI string +} + +type OAuthUserInfo struct { + ID string `json:"id"` + UnionID string `json:"union_id"` + Name string `json:"name"` + Email string `json:"email"` + AvatarURL string `json:"avatar_url"` +} + +type OAuthSignUpOrInReq struct { + Platform consts.UserPlatform `json:"platform" query:"platform" validate:"required"` // 第三方平台 dingtalk + SessionID string `json:"session_id" query:"session_id"` // 会话ID + RedirectURL string `json:"redirect_url" query:"redirect_url"` // 登录成功后跳转的 URL +} + +type OAuthCallbackReq struct { + State string `json:"state" query:"state" validate:"required"` + Code string `json:"code" query:"code" validate:"required"` +} + +type OAuthURLResp struct { + URL string `json:"url"` +} + +type OAuthState struct { + Kind consts.OAuthKind `json:"kind" query:"kind" validate:"required"` // 注册或登录 + SessionID string `json:"session_id"` // 会话ID + Platform consts.UserPlatform `json:"platform" query:"platform" validate:"required"` // 第三方平台 dingtalk + RedirectURL string `json:"redirect_url" query:"redirect_url"` // 登录成功后跳转的 URL +} diff --git a/backend/domain/user.go b/backend/domain/user.go index 7abb9a5..45f811d 100644 --- a/backend/domain/user.go +++ b/backend/domain/user.go @@ -27,6 +27,8 @@ type UserUsecase interface { Register(ctx context.Context, req *RegisterReq) (*User, error) GetSetting(ctx context.Context) (*Setting, error) UpdateSetting(ctx context.Context, req *UpdateSettingReq) (*Setting, error) + OAuthSignUpOrIn(ctx context.Context, req *OAuthSignUpOrInReq) (*OAuthURLResp, error) + OAuthCallback(ctx context.Context, req *OAuthCallbackReq) (string, error) } type UserRepo interface { @@ -47,6 +49,7 @@ type UserRepo interface { AdminLoginHistory(ctx context.Context, page *web.Pagination) ([]*db.AdminLoginHistory, *db.PageInfo, error) GetSetting(ctx context.Context) (*db.Setting, error) UpdateSetting(ctx context.Context, fn func(*db.SettingUpdateOne)) (*db.Setting, error) + SignUpOrIn(ctx context.Context, platform consts.UserPlatform, req *OAuthUserInfo) (*db.User, error) } type UpdateUserReq struct { @@ -245,15 +248,19 @@ type VSCodeSession struct { } type UpdateSettingReq struct { - EnableSSO *bool `json:"enable_sso"` // 是否开启SSO - ForceTwoFactorAuth *bool `json:"force_two_factor_auth"` // 是否强制两步验证 - DisablePasswordLogin *bool `json:"disable_password_login"` // 是否禁用密码登录 + EnableSSO *bool `json:"enable_sso"` // 是否开启SSO + ForceTwoFactorAuth *bool `json:"force_two_factor_auth"` // 是否强制两步验证 + DisablePasswordLogin *bool `json:"disable_password_login"` // 是否禁用密码登录 + EnableDingtalkOAuth *bool `json:"enable_dingtalk_oauth"` // 是否开启钉钉OAuth + DingtalkClientID *string `json:"dingtalk_client_id"` // 钉钉客户端ID + DingtalkClientSecret *string `json:"dingtalk_client_secret"` // 钉钉客户端密钥 } type Setting struct { EnableSSO bool `json:"enable_sso"` // 是否开启SSO ForceTwoFactorAuth bool `json:"force_two_factor_auth"` // 是否强制两步验证 DisablePasswordLogin bool `json:"disable_password_login"` // 是否禁用密码登录 + EnableDingtalkOAuth bool `json:"enable_dingtalk_oauth"` // 是否开启钉钉OAuth CreatedAt int64 `json:"created_at"` // 创建时间 UpdatedAt int64 `json:"updated_at"` // 更新时间 } @@ -266,6 +273,7 @@ func (s *Setting) From(e *db.Setting) *Setting { s.EnableSSO = e.EnableSSO s.ForceTwoFactorAuth = e.ForceTwoFactorAuth s.DisablePasswordLogin = e.DisablePasswordLogin + s.EnableDingtalkOAuth = e.EnableDingtalkOauth s.CreatedAt = e.CreatedAt.Unix() s.UpdatedAt = e.UpdatedAt.Unix() diff --git a/backend/ent/schema/setting.go b/backend/ent/schema/setting.go index b58e519..d8e85ee 100644 --- a/backend/ent/schema/setting.go +++ b/backend/ent/schema/setting.go @@ -31,6 +31,9 @@ func (Setting) Fields() []ent.Field { field.Bool("enable_sso").Default(false), field.Bool("force_two_factor_auth").Default(false), field.Bool("disable_password_login").Default(false), + field.Bool("enable_dingtalk_oauth").Default(false), + field.String("dingtalk_client_id").Optional(), + field.String("dingtalk_client_secret").Optional(), field.Time("created_at").Default(time.Now), field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), } diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go index 01c7898..b4a2bbc 100644 --- a/backend/ent/schema/user.go +++ b/backend/ent/schema/user.go @@ -30,9 +30,11 @@ func (User) Annotations() []schema.Annotation { func (User) Fields() []ent.Field { return []ent.Field{ field.UUID("id", uuid.UUID{}), - field.String("username").Unique(), - field.String("password"), - field.String("email").Unique(), + field.String("username").Optional(), + field.String("password").Optional(), + field.String("email").Optional(), + field.String("avatar_url").Optional(), + field.String("platform").GoType(consts.UserPlatform("")).Default(string(consts.UserPlatformEmail)), field.String("status").GoType(consts.UserStatus("")).Default(string(consts.UserStatusActive)), field.Time("created_at").Default(time.Now), field.Time("updated_at").Default(time.Now), @@ -45,5 +47,6 @@ func (User) Edges() []ent.Edge { edge.To("login_histories", UserLoginHistory.Type), edge.To("models", Model.Type), edge.To("tasks", Task.Type), + edge.To("identities", UserIdentity.Type), } } diff --git a/backend/ent/schema/useridentity.go b/backend/ent/schema/useridentity.go new file mode 100644 index 0000000..caa5930 --- /dev/null +++ b/backend/ent/schema/useridentity.go @@ -0,0 +1,49 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/consts" +) + +// UserIdentity holds the schema definition for the UserIdentity entity. +type UserIdentity struct { + ent.Schema +} + +func (UserIdentity) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "user_identities", + }, + } +} + +// Fields of the UserIdentity. +func (UserIdentity) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("user_id", uuid.UUID{}).Optional(), + field.String("platform").GoType(consts.UserPlatform("")).Default(string(consts.UserPlatformEmail)), + field.String("identity_id"), + field.String("union_id").Optional(), + field.String("nickname").Optional(), + field.String("email").Optional(), + field.String("avatar_url").Optional(), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the UserIdentity. +func (UserIdentity) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("user", User.Type).Ref("identities").Field("user_id").Unique(), + } +} diff --git a/backend/errcode/errcode.go b/backend/errcode/errcode.go index 780bd1b..a825b9c 100644 --- a/backend/errcode/errcode.go +++ b/backend/errcode/errcode.go @@ -15,4 +15,5 @@ var ( ErrPassword = web.NewBadRequestErr("err-password") ErrInviteCodeInvalid = web.NewBadRequestErr("err-invite-code-invalid") ErrEmailInvalid = web.NewBadRequestErr("err-email-invalid") + ErrOAuthStateInvalid = web.NewBadRequestErr("err-oauth-state-invalid") ) diff --git a/backend/errcode/locale.zh.toml b/backend/errcode/locale.zh.toml index 7e0eb8e..5423c71 100644 --- a/backend/errcode/locale.zh.toml +++ b/backend/errcode/locale.zh.toml @@ -11,4 +11,7 @@ other = "密码错误" other = "邀请码无效" [err-email-invalid] -other = "邮箱格式错误" \ No newline at end of file +other = "邮箱格式错误" + +[err-oauth-state-invalid] +other = "OAuth 状态无效" \ No newline at end of file diff --git a/backend/internal/user/handler/v1/user.go b/backend/internal/user/handler/v1/user.go index 40bec4d..725c4de 100644 --- a/backend/internal/user/handler/v1/user.go +++ b/backend/internal/user/handler/v1/user.go @@ -44,9 +44,9 @@ func NewUserHandler( // admin admin := w.Group("/api/v1/admin") admin.POST("/login", web.BindHandler(u.AdminLogin)) + admin.GET("/setting", web.BaseHandler(u.GetSetting)) admin.Use(auth.Auth()) - admin.GET("/setting", web.BaseHandler(u.GetSetting)) admin.PUT("/setting", web.BindHandler(u.UpdateSetting)) admin.POST("/create", web.BindHandler(u.CreateAdmin)) admin.GET("/list", web.BaseHandler(u.AdminList, web.WithPage())) @@ -54,6 +54,8 @@ func NewUserHandler( admin.DELETE("/delete", web.BaseHandler(u.DeleteAdmin)) g := w.Group("/api/v1/user") + g.GET("/oauth/signup-or-in", web.BindHandler(u.OAuthSignUpOrIn)) + g.GET("/oauth/callback", web.BindHandler(u.OAuthCallback)) g.POST("/register", web.BindHandler(u.Register)) g.POST("/login", web.BindHandler(u.Login)) @@ -369,6 +371,45 @@ func (h *UserHandler) UpdateSetting(c *web.Context, req domain.UpdateSettingReq) return c.Success(resp) } +// OAuthSignUpOrIn 用户 OAuth 登录或注册 +// +// @Tags User +// @Summary 用户 OAuth 登录或注册 +// @Description 用户 OAuth 登录或注册 +// @ID user-oauth-signup-or-in +// @Accept json +// @Produce json +// @Param req query domain.OAuthSignUpOrInReq true "param" +// @Success 200 {object} web.Resp{data=domain.OAuthURLResp} +// @Router /api/v1/user/oauth/signup-or-in [get] +func (h *UserHandler) OAuthSignUpOrIn(ctx *web.Context, req domain.OAuthSignUpOrInReq) error { + resp, err := h.usecase.OAuthSignUpOrIn(ctx.Request().Context(), &req) + if err != nil { + return err + } + return ctx.Success(resp) +} + +// OAuthCallback 用户 OAuth 回调 +// +// @Tags User +// @Summary 用户 OAuth 回调 +// @Description 用户 OAuth 回调 +// @ID user-oauth-callback +// @Accept json +// @Produce json +// @Param req query domain.OAuthCallbackReq true "param" +// @Success 200 {object} web.Resp{data=string} +// @Router /api/v1/user/oauth/callback [get] +func (h *UserHandler) OAuthCallback(ctx *web.Context, req domain.OAuthCallbackReq) error { + resp, err := h.usecase.OAuthCallback(ctx.Request().Context(), &req) + if err != nil { + return err + } + ctx.Redirect(http.StatusFound, resp) + return nil +} + func (h *UserHandler) InitAdmin() error { return h.usecase.InitAdmin(context.Background()) } diff --git a/backend/internal/user/repo/user.go b/backend/internal/user/repo/user.go index 5279f77..825306e 100644 --- a/backend/internal/user/repo/user.go +++ b/backend/internal/user/repo/user.go @@ -14,6 +14,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/pkg/entx" ) @@ -210,3 +211,45 @@ func (r *UserRepo) DeleteAdmin(ctx context.Context, id string) error { } return r.db.Admin.DeleteOne(admin).Exec(ctx) } + +func (r *UserRepo) SignUpOrIn(ctx context.Context, platform consts.UserPlatform, req *domain.OAuthUserInfo) (*db.User, error) { + var u *db.User + err := entx.WithTx(ctx, r.db, func(tx *db.Tx) error { + ui, err := tx.UserIdentity.Query(). + WithUser(). + Where(useridentity.Platform(platform), useridentity.IdentityID(req.ID)). + First(ctx) + if err == nil { + u = ui.Edges.User + return nil + } + if !db.IsNotFound(err) { + return err + } + user, err := tx.User.Create(). + SetUsername(req.Name). + SetEmail(req.Email). + SetAvatarURL(req.AvatarURL). + SetPlatform(platform). + SetStatus(consts.UserStatusActive). + Save(ctx) + if err != nil { + return err + } + _, err = tx.UserIdentity.Create(). + SetUserID(user.ID). + SetPlatform(platform). + SetIdentityID(req.ID). + SetUnionID(req.UnionID). + SetNickname(req.Name). + SetAvatarURL(req.AvatarURL). + SetEmail(req.Email). + Save(ctx) + if err != nil { + return err + } + u = user + return nil + }) + return u, err +} diff --git a/backend/internal/user/usecase/user.go b/backend/internal/user/usecase/user.go index a8e1e2c..aac64f1 100644 --- a/backend/internal/user/usecase/user.go +++ b/backend/internal/user/usecase/user.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log/slog" + "net/url" "strings" "time" @@ -13,7 +14,9 @@ import ( "golang.org/x/crypto/bcrypt" "github.com/GoYoko/web" + "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/oauth" "github.com/chaitin/MonkeyCode/backend/config" "github.com/chaitin/MonkeyCode/backend/db" @@ -151,15 +154,6 @@ func (u *UserUsecase) Register(ctx context.Context, req *domain.RegisterReq) (*d } func (u *UserUsecase) Login(ctx context.Context, req *domain.LoginReq) (*domain.LoginResp, error) { - s, err := u.redis.Get(ctx, fmt.Sprintf("vscode:session:%s", req.SessionID)).Result() - if err != nil { - return nil, err - } - session := &domain.VSCodeSession{} - if err := json.Unmarshal([]byte(s), session); err != nil { - return nil, err - } - user, err := u.repo.GetByName(ctx, req.Username) if err != nil { return nil, errcode.ErrUserNotFound.Wrap(err) @@ -173,12 +167,28 @@ func (u *UserUsecase) Login(ctx context.Context, req *domain.LoginReq) (*domain. return nil, err } - r := fmt.Sprintf("%s?state=%s&api_key=%s&expires_in=3600&username=%s", session.RedirectURI, session.State, apiKey.Key, user.Username) + r, err := u.getVSCodeURL(ctx, req.SessionID, apiKey.Key, user.Username) + if err != nil { + return nil, err + } return &domain.LoginResp{ RedirectURL: r, }, nil } +func (u *UserUsecase) getVSCodeURL(ctx context.Context, sessionID, apiKey, username string) (string, error) { + s, err := u.redis.Get(ctx, fmt.Sprintf("vscode:session:%s", sessionID)).Result() + if err != nil { + return "", err + } + session := &domain.VSCodeSession{} + if err := json.Unmarshal([]byte(s), session); err != nil { + return "", err + } + r := fmt.Sprintf("%s?state=%s&api_key=%s&expires_in=3600&username=%s", session.RedirectURI, session.State, apiKey, username) + return r, nil +} + func (u *UserUsecase) AdminLogin(ctx context.Context, req *domain.LoginReq) (*domain.AdminUser, error) { admin, err := u.repo.AdminByName(ctx, req.Username) if err != nil { @@ -249,6 +259,15 @@ func (u *UserUsecase) UpdateSetting(ctx context.Context, req *domain.UpdateSetti if req.DisablePasswordLogin != nil { s.SetDisablePasswordLogin(*req.DisablePasswordLogin) } + if req.EnableDingtalkOAuth != nil { + s.SetEnableDingtalkOauth(*req.EnableDingtalkOAuth) + } + if req.DingtalkClientID != nil { + s.SetDingtalkClientID(*req.DingtalkClientID) + } + if req.DingtalkClientSecret != nil { + s.SetDingtalkClientSecret(*req.DingtalkClientSecret) + } }) if err != nil { return nil, err @@ -283,3 +302,111 @@ func (u *UserUsecase) Delete(ctx context.Context, id string) error { func (u *UserUsecase) DeleteAdmin(ctx context.Context, id string) error { return u.repo.DeleteAdmin(ctx, id) } + +func (u *UserUsecase) OAuthSignUpOrIn(ctx context.Context, req *domain.OAuthSignUpOrInReq) (*domain.OAuthURLResp, error) { + setting, err := u.repo.GetSetting(ctx) + if err != nil { + return nil, err + } + cfg := domain.OAuthConfig{ + Debug: u.cfg.Debug, + Platform: req.Platform, + RedirectURI: fmt.Sprintf("%s/api/v1/user/oauth/callback", u.cfg.BaseUrl), + } + + switch req.Platform { + case consts.UserPlatformDingTalk: + cfg.ClientID = setting.DingtalkClientID + cfg.ClientSecret = setting.DingtalkClientSecret + } + + oauth, err := oauth.NewOAuther(cfg) + if err != nil { + return nil, err + } + state, url := oauth.GetAuthorizeURL() + + session := &domain.OAuthState{ + SessionID: req.SessionID, + Kind: consts.OAuthKindSignUpOrIn, + Platform: req.Platform, + RedirectURL: req.RedirectURL, + } + b, err := json.Marshal(session) + if err != nil { + return nil, err + } + if err := u.redis.Set(ctx, fmt.Sprintf("oauth:state:%s", state), b, 15*time.Minute).Err(); err != nil { + return nil, err + } + + return &domain.OAuthURLResp{ + URL: url, + }, nil +} + +func (u *UserUsecase) OAuthCallback(ctx context.Context, req *domain.OAuthCallbackReq) (string, error) { + b, err := u.redis.Get(ctx, fmt.Sprintf("oauth:state:%s", req.State)).Result() + if err != nil { + return "", err + } + var session domain.OAuthState + if err := json.Unmarshal([]byte(b), &session); err != nil { + return "", err + } + + switch session.Kind { + case consts.OAuthKindSignUpOrIn: + return u.OAuthSignUpOrInCallback(ctx, req, &session) + default: + return "", errcode.ErrOAuthStateInvalid + } +} + +func (u *UserUsecase) OAuthSignUpOrInCallback(ctx context.Context, req *domain.OAuthCallbackReq, session *domain.OAuthState) (string, error) { + setting, err := u.repo.GetSetting(ctx) + if err != nil { + return "", err + } + cfg := domain.OAuthConfig{ + Debug: u.cfg.Debug, + Platform: session.Platform, + } + switch session.Platform { + case consts.UserPlatformDingTalk: + cfg.ClientID = setting.DingtalkClientID + cfg.ClientSecret = setting.DingtalkClientSecret + } + + oauth, err := oauth.NewOAuther(cfg) + if err != nil { + return "", err + } + userInfo, err := oauth.GetUserInfo(req.Code) + if err != nil { + return "", err + } + + user, err := u.repo.SignUpOrIn(ctx, session.Platform, userInfo) + if err != nil { + return "", err + } + + apiKey, err := u.repo.GetOrCreateApiKey(ctx, user.ID.String()) + if err != nil { + return "", err + } + + redirect := session.RedirectURL + + if session.SessionID != "" { + r, err := u.getVSCodeURL(ctx, session.SessionID, apiKey.Key, user.Username) + if err != nil { + return "", err + } + redirect = fmt.Sprintf("%s?redirect_url=%s", redirect, url.QueryEscape(r)) + } + + u.logger.Debug("oauth callback", "redirect", redirect) + return redirect, nil +} diff --git a/backend/migration/000002_create_core_table.up.sql b/backend/migration/000002_create_core_table.up.sql index d356f2b..f93378a 100644 --- a/backend/migration/000002_create_core_table.up.sql +++ b/backend/migration/000002_create_core_table.up.sql @@ -18,18 +18,34 @@ CREATE TABLE IF NOT EXISTS invite_codes ( updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP ); --- 用户表 CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - username VARCHAR(255) UNIQUE NOT NULL, - password VARCHAR(255) NOT NULL, - email VARCHAR(255) UNIQUE, + username VARCHAR(255), + password VARCHAR(255), + email VARCHAR(255), + avatar_url VARCHAR(255), status VARCHAR(20) DEFAULT 'active', + platform VARCHAR(12), created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP ); -CREATE INDEX IF NOT EXISTS idx_users_username ON users (username); +CREATE UNIQUE INDEX IF NOT EXISTS unique_idx_users_username ON users (username) WHERE username IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS unique_idx_users_email ON users (email) WHERE email IS NOT NULL; + +CREATE TABLE IF NOT EXISTS user_identities ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v1(), + user_id UUID NOT NULL, + platform VARCHAR(12) NOT NULL, + identity_id VARCHAR(64) NOT NULL, + union_id VARCHAR(64), + nickname VARCHAR(255), + email VARCHAR(255), + avatar_url TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX IF NOT EXISTS unique_idx_user_identities_platform_identity_id ON user_identities (platform, identity_id); CREATE TABLE IF NOT EXISTS user_login_histories ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -143,6 +159,9 @@ CREATE TABLE IF NOT EXISTS settings ( enable_sso BOOLEAN DEFAULT FALSE, force_two_factor_auth BOOLEAN DEFAULT FALSE, disable_password_login BOOLEAN DEFAULT FALSE, + enable_dingtalk_oauth BOOLEAN DEFAULT FALSE, + dingtalk_client_id VARCHAR(255), + dingtalk_client_secret VARCHAR(255), created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP ); diff --git a/backend/pkg/oauth/dingtalk.go b/backend/pkg/oauth/dingtalk.go new file mode 100644 index 0000000..ecebcee --- /dev/null +++ b/backend/pkg/oauth/dingtalk.go @@ -0,0 +1,99 @@ +package oauth + +import ( + "fmt" + "time" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/pkg/request" +) + +type DingTalk struct { + ClientID string + ClientSecret string + RedirectURI string + client *request.Client +} + +var _ domain.OAuther = &DingTalk{} + +func NewDingTalk(config domain.OAuthConfig) *DingTalk { + client := request.NewClient("https", "api.dingtalk.com", 30*time.Second) + client.SetDebug(config.Debug) + return &DingTalk{ + ClientID: config.ClientID, + ClientSecret: config.ClientSecret, + RedirectURI: config.RedirectURI, + client: client, + } +} + +// GetUserInfo implements domain.OAuther. +func (d *DingTalk) GetUserInfo(code string) (*domain.OAuthUserInfo, error) { + accessToken, err := d.getAccessToken(code) + if err != nil { + return nil, err + } + return d.getUserInfo(accessToken) +} + +type dingtalkAccessTokenResp struct { + AccessToken string `json:"accessToken"` + ExpiresIn int `json:"expireIn"` + RefreshToken string `json:"refreshToken"` + CorpID string `json:"corpId"` +} + +type dingtalkAccessTokenReq struct { + ClientID string `json:"clientId"` + ClientSecret string `json:"clientSecret"` + Code string `json:"code"` + GrantType string `json:"grantType"` +} + +func (d *DingTalk) getAccessToken(code string) (string, error) { + resp, err := request.Post[dingtalkAccessTokenResp](d.client, "/v1.0/oauth2/userAccessToken", dingtalkAccessTokenReq{ + ClientID: d.ClientID, + ClientSecret: d.ClientSecret, + Code: code, + GrantType: "authorization_code", + }) + if err != nil { + return "", err + } + return resp.AccessToken, nil +} + +type dingtalkUserInfoResp struct { + Nick string `json:"nick"` + AvatarURL string `json:"avatarUrl"` + Mobile string `json:"mobile"` + OpenID string `json:"openId"` + UnionID string `json:"unionId"` + Email string `json:"email"` + StateCode string `json:"stateCode"` +} + +func (d *DingTalk) getUserInfo(accessToken string) (*domain.OAuthUserInfo, error) { + resp, err := request.Get[dingtalkUserInfoResp](d.client, "/v1.0/contact/users/me", request.WithHeader(request.Header{ + "x-acs-dingtalk-access-token": accessToken, + })) + if err != nil { + return nil, err + } + return &domain.OAuthUserInfo{ + ID: resp.OpenID, + UnionID: resp.UnionID, + Name: resp.Nick, + Email: resp.Email, + AvatarURL: resp.AvatarURL, + }, nil +} + +func (d *DingTalk) GetAuthorizeURL() (string, string) { + state := uuid.NewString() + url := fmt.Sprintf("https://login.dingtalk.com/oauth2/auth?response_type=code&scope=openid&client_id=%s&prompt=consent&state=%s&redirect_uri=%s", d.ClientID, state, d.RedirectURI) + return state, url +} diff --git a/backend/pkg/oauth/oauth.go b/backend/pkg/oauth/oauth.go new file mode 100644 index 0000000..16c83b4 --- /dev/null +++ b/backend/pkg/oauth/oauth.go @@ -0,0 +1,25 @@ +package oauth + +import ( + "fmt" + + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/domain" +) + +func NewOAuther(config domain.OAuthConfig) (domain.OAuther, error) { + switch config.Platform { + case consts.UserPlatformDingTalk: + return NewDingTalk(config), nil + default: + return nil, fmt.Errorf("unsupported platform: %s", config.Platform) + } +} + +type AccessTokenResponse struct { + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token"` + Scope string `json:"scope"` + UnionID string `json:"unionid"` +}