From 820acbc99106ca58dc2741c5ab5114a3f0d91676 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 14 Oct 2021 15:44:32 +0800 Subject: [PATCH 01/44] configs dir --- .gitignore | 4 ++-- README.md | 4 ++++ configs/config.yaml | 16 ++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 configs/config.yaml diff --git a/.gitignore b/.gitignore index 5a9c45d..9fa46c9 100644 --- a/.gitignore +++ b/.gitignore @@ -2,9 +2,9 @@ /.idea /.vscode *.exe -/storage/* -/configs/*.yaml + + /tmp .air.conf \ No newline at end of file diff --git a/README.md b/README.md index 7594832..c9355bc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # lin-cms-go ## 框架选型 fiber ent +### 生成ent对象 +``` +go generate ./internal/data/ent/ +``` lin-cms-go 不断更新。let's go diff --git a/configs/config.yaml b/configs/config.yaml new file mode 100644 index 0000000..4ff9968 --- /dev/null +++ b/configs/config.yaml @@ -0,0 +1,16 @@ +server: + http: + addr: 0.0.0.0:3000 + timeout: 1 + +data: + database: + driver: mysql + source: root:@tcp(127.0.0.1:3306)/lincms?charset=utf8mb4&parseTime=True + redis: + addr: 127.0.0.1:6379 + read_timeout: 0.2 + write_timeout: 0.2 + +log: + path: . \ No newline at end of file From 755ab2b3f724af3aab32b6f689b08edd4c1ea602 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 14 Oct 2021 15:55:06 +0800 Subject: [PATCH 02/44] register no auth --- docs/schema.sql | 2 +- internal/server/routes.go | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/schema.sql b/docs/schema.sql index 8ea799a..1d5af2f 100644 --- a/docs/schema.sql +++ b/docs/schema.sql @@ -187,7 +187,7 @@ VALUES (1, 'root', 'root'); INSERT INTO lin_user_identiy (id, user_id, identity_type, identifier, credential) VALUES (1, 1, 'USERNAME_PASSWORD', 'root', - 'sha1$c419e500$1$84869e5560ebf3de26b6690386484929456d6c07'); + '$2a$10$Subt/mCLem8axyivSN4BBeSLUtdPPEhDJJTWpGQVWJst1aVa9TzQq'); INSERT INTO lin_group(id, name, info, level) VALUES (1, 'root', '超级用户组', 1); diff --git a/internal/server/routes.go b/internal/server/routes.go index 7f90308..6a460bc 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -13,6 +13,7 @@ func InitRoute(app *fiber.App) { cms := app.Group("/cms") cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) + cms.Post("/user/register", api.Register) cms.Use(jwtware.New(jwtware.Config{ SigningKey: []byte("secret"), })) @@ -20,7 +21,7 @@ func InitRoute(app *fiber.App) { userRouter := cms.Group("/user") adminRouter := cms.Group("/admin") logRouter := cms.Group("/log") - userRouter.Post("/register", api.Register) + userRouter.Put("/", api.UpdateMe) userRouter.Put("/change_password", api.ChangeMyPassword) userRouter.Get("/permissions", api.GetMyPermissions) From 6d9c28c15a315f752937ed9b4bd3a25b74effa26 Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Fri, 15 Oct 2021 10:32:06 +0800 Subject: [PATCH 03/44] =?UTF-8?q?=E5=A2=9E=E5=8A=A0book=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/book.go | 53 +++++++++++++++++++++++++++++++++++++++ internal/biz/book.go | 48 +++++++++++++++++++++++++++++++++++ internal/data/book.go | 32 +++++++++++++++++++++++ internal/request/book.go | 20 +++++++++++++++ internal/server/routes.go | 11 ++++++++ pkg/errcode/message.go | 2 ++ 6 files changed, 166 insertions(+) create mode 100644 api/book.go create mode 100644 internal/biz/book.go create mode 100644 internal/data/book.go create mode 100644 internal/request/book.go diff --git a/api/book.go b/api/book.go new file mode 100644 index 0000000..0e1ce1e --- /dev/null +++ b/api/book.go @@ -0,0 +1,53 @@ +package api + +import ( + "github.com/gofiber/fiber/v2" + "lin-cms-go/internal/biz" + "lin-cms-go/internal/request" + "lin-cms-go/pkg/core" +) + +func GetBooks(c *fiber.Ctx) error { + data, err := biz.GetBookAll(c.Context()) + if err != nil { + return err + } + core.SetData(c, data) + return nil +} + +func UpdateBook(c *fiber.Ctx) error { + var req request.UpdateBook + if err := core.ParseRequest(c, &req); err != nil { + return err + } + err := biz.UpdateBook(c.Context(), req) + if err != nil { + return err + } + return core.SuccessResp(c) +} + +func CreateBook(c *fiber.Ctx) error { + var req request.CreateBook + if err := core.ParseRequest(c, &req); err != nil { + return err + } + err := biz.CreateBook(c.Context(), req) + if err != nil { + return err + } + return core.SuccessResp(c) +} + +func DeleteBook(c *fiber.Ctx) error { + var req request.DeleteBook + if err := core.ParseRequest(c, &req); err != nil { + return err + } + err := biz.DeleteBook(c.Context(), req) + if err != nil { + return err + } + return core.SuccessResp(c) +} diff --git a/internal/biz/book.go b/internal/biz/book.go new file mode 100644 index 0000000..2f71f04 --- /dev/null +++ b/internal/biz/book.go @@ -0,0 +1,48 @@ +package biz + +import ( + "context" + "lin-cms-go/internal/data" + "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/request" + "lin-cms-go/pkg/core" + "lin-cms-go/pkg/errcode" +) + +func GetBookAll(ctx context.Context) (res map[string]interface{}, err error) { + bookModel, err := data.GetBookAll(ctx) + if err != nil { + return + } + res = make(map[string]interface{}) + res["books"] = bookModel + return +} + +func UpdateBook(ctx context.Context, req request.UpdateBook) (err error) { + _, err = data.GetBookById(ctx, req.Id) + if ent.IsNotFound(err) { + err = core.NewErrorCode(errcode.BookNotFound) + return + } + if err != nil { + return + } + err = data.UpdateBook(ctx, req.Id, req.Title, req.Author, req.Summary, req.Image) + return +} + +func CreateBook(ctx context.Context, req request.CreateBook) (err error) { + err = data.CreateBook(ctx, req.Title, req.Author, req.Summary, req.Image) + return +} + +func DeleteBook(ctx context.Context, req request.DeleteBook) (err error) { + _, err = data.GetBookById(ctx, req.Id) + if ent.IsNotFound(err) { + err = core.NewErrorCode(errcode.BookNotFound) + return + } + err = data.DeleteBook(ctx, req.Id) + return +} diff --git a/internal/data/book.go b/internal/data/book.go new file mode 100644 index 0000000..ab9b78a --- /dev/null +++ b/internal/data/book.go @@ -0,0 +1,32 @@ +package data + +import ( + "context" + "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/data/ent/book" +) + +func GetBookAll(ctx context.Context) (model []*ent.Book, err error) { + model, err = GetDB().Book.Query().All(ctx) + return +} + +func GetBookById(ctx context.Context, id int) (model *ent.Book, err error) { + model, err = GetDB().Book.Query().Where(book.ID(id)).First(ctx) + return +} + +func UpdateBook(ctx context.Context, id int, title string, author string, summary string, image string) (err error) { + _, err = GetDB().Book.Update().Where(book.ID(id)).SetTitle(title).SetAuthor(author).SetSummary(summary).SetImage(image).Save(ctx) + return +} + +func CreateBook(ctx context.Context, title string, author string, summary string, image string) (err error) { + _, err = GetDB().Book.Create().SetTitle(title).SetAuthor(author).SetSummary(summary).SetImage(image).Save(ctx) + return +} + +func DeleteBook(ctx context.Context, id int) (err error) { + err = GetDB().Book.DeleteOneID(id).Exec(ctx) + return +} diff --git a/internal/request/book.go b/internal/request/book.go new file mode 100644 index 0000000..3710968 --- /dev/null +++ b/internal/request/book.go @@ -0,0 +1,20 @@ +package request + +type UpdateBook struct { + Id int `json:"id" validate:"required" comment:"书籍id"` + Title string `json:"title" validate:"required" comment:"书籍标题"` + Author string `json:"author" validate:"required" comment:"书籍作者"` + Summary string `json:"summary" validate:"required" comment:"书籍简介"` + Image string `json:"image" validate:"required" comment:"书籍封面图"` +} + +type CreateBook struct { + Title string `json:"title" validate:"required" comment:"书籍标题"` + Author string `json:"author" validate:"required" comment:"书籍作者"` + Summary string `json:"summary" validate:"required" comment:"书籍简介"` + Image string `json:"image" validate:"required" comment:"书籍封面图"` +} + +type DeleteBook struct { + Id int `json:"id" validate:"required" comment:"书籍id"` +} diff --git a/internal/server/routes.go b/internal/server/routes.go index 6a460bc..0a3958c 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -11,16 +11,22 @@ func InitRoute(app *fiber.App) { app.Static("/upload", "storage/upload") app.Get("/", api.Hello) cms := app.Group("/cms") + v1 := app.Group("/v1") cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) cms.Post("/user/register", api.Register) cms.Use(jwtware.New(jwtware.Config{ SigningKey: []byte("secret"), })) + + v1.Use(jwtware.New(jwtware.Config{ + SigningKey: []byte("secret"), + })) { userRouter := cms.Group("/user") adminRouter := cms.Group("/admin") logRouter := cms.Group("/log") + bookRouter := v1.Group("/book") userRouter.Put("/", api.UpdateMe) userRouter.Put("/change_password", api.ChangeMyPassword) @@ -46,6 +52,11 @@ func InitRoute(app *fiber.App) { logRouter.Get("", api.GetLogs) logRouter.Get("/search", api.SearchLogs) logRouter.Get("/users", api.GetLogUsers) + + bookRouter.Get("", api.GetBooks) + bookRouter.Put("", api.UpdateBook) + bookRouter.Post("", api.CreateBook) + bookRouter.Delete("", api.DeleteBook) } } diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index bdfc77e..ed6e6f3 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -12,6 +12,7 @@ const ( ErrorPassWord UserFound UserNotFound + BookNotFound ) var MsgFlags = map[int]string{ @@ -25,6 +26,7 @@ var MsgFlags = map[int]string{ ErrorPassWord: "密码错误", UserFound: "用户已存在", UserNotFound: "用户不存在", + BookNotFound: "书籍不存在", } func GetMsg(code int) string { From f2a134616f6451010279e8087a68007a98c7177d Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Fri, 15 Oct 2021 16:54:04 +0800 Subject: [PATCH 04/44] feat: get book --- api/book.go | 41 ++++++++++++++++++++++++++++++++------ internal/biz/book.go | 42 +++++++++++++++++++++++++++++---------- internal/data/book.go | 14 +++++++++++-- internal/request/book.go | 7 +++---- internal/server/routes.go | 5 +++-- pkg/core/response.go | 2 +- pkg/errcode/message.go | 2 ++ 7 files changed, 88 insertions(+), 25 deletions(-) diff --git a/api/book.go b/api/book.go index 0e1ce1e..7f8344c 100644 --- a/api/book.go +++ b/api/book.go @@ -5,14 +5,26 @@ import ( "lin-cms-go/internal/biz" "lin-cms-go/internal/request" "lin-cms-go/pkg/core" + "lin-cms-go/pkg/utils" ) func GetBooks(c *fiber.Ctx) error { - data, err := biz.GetBookAll(c.Context()) + // TODO book 接口少了权限判断 + + size := core.GetSize(c) + page := core.GetPage(c) + data, err := biz.GetBookAll(c.Context(), page, size) if err != nil { return err } - core.SetData(c, data) + + total, err := biz.GetBookTotal(c.Context()) + if err != nil { + return err + } + + core.SetPage(c, data, total) + return nil } @@ -21,7 +33,11 @@ func UpdateBook(c *fiber.Ctx) error { if err := core.ParseRequest(c, &req); err != nil { return err } - err := biz.UpdateBook(c.Context(), req) + id, err := utils.StringToInt(c.Params("id")) + if err != nil { + return err + } + err = biz.UpdateBook(c.Context(), id, req) if err != nil { return err } @@ -41,13 +57,26 @@ func CreateBook(c *fiber.Ctx) error { } func DeleteBook(c *fiber.Ctx) error { - var req request.DeleteBook - if err := core.ParseRequest(c, &req); err != nil { + id, err := utils.StringToInt(c.Params("id")) + if err != nil { return err } - err := biz.DeleteBook(c.Context(), req) + err = biz.DeleteBook(c.Context(), id) if err != nil { return err } return core.SuccessResp(c) } + +func GetBook(c *fiber.Ctx) error { + id, err := utils.StringToInt(c.Params("id")) + if err != nil { + return err + } + data, err := biz.GetBook(c.Context(), id) + if err != nil { + return err + } + core.SetData(c, data) + return nil +} diff --git a/internal/biz/book.go b/internal/biz/book.go index 2f71f04..42dea70 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -9,18 +9,22 @@ import ( "lin-cms-go/pkg/errcode" ) -func GetBookAll(ctx context.Context) (res map[string]interface{}, err error) { - bookModel, err := data.GetBookAll(ctx) +func GetBookAll(ctx context.Context, page int, size int) (res interface{}, err error) { + bookModel, err := data.GetBookAll(ctx, page, size) if err != nil { return } - res = make(map[string]interface{}) - res["books"] = bookModel + res = bookModel return } -func UpdateBook(ctx context.Context, req request.UpdateBook) (err error) { - _, err = data.GetBookById(ctx, req.Id) +func GetBookTotal(ctx context.Context) (total int, err error) { + total, err = data.GetBookCount(ctx) + return +} + +func UpdateBook(ctx context.Context, id int, req request.UpdateBook) (err error) { + _, err = data.GetBookById(ctx, id) if ent.IsNotFound(err) { err = core.NewErrorCode(errcode.BookNotFound) return @@ -28,21 +32,39 @@ func UpdateBook(ctx context.Context, req request.UpdateBook) (err error) { if err != nil { return } - err = data.UpdateBook(ctx, req.Id, req.Title, req.Author, req.Summary, req.Image) + err = data.UpdateBook(ctx, id, req.Title, req.Author, req.Summary, req.Image) return } func CreateBook(ctx context.Context, req request.CreateBook) (err error) { + model, err := data.GetBookByTitle(ctx, req.Title) + if ent.MaskNotFound(err) != nil { + return err + } + if model != nil { + err = core.NewErrorCode(errcode.BookTitleRepetition) + return + } err = data.CreateBook(ctx, req.Title, req.Author, req.Summary, req.Image) return } -func DeleteBook(ctx context.Context, req request.DeleteBook) (err error) { - _, err = data.GetBookById(ctx, req.Id) +func DeleteBook(ctx context.Context, id int) (err error) { + _, err = data.GetBookById(ctx, id) + if ent.IsNotFound(err) { + err = core.NewErrorCode(errcode.BookNotFound) + return + } + err = data.DeleteBook(ctx, id) + return +} + +func GetBook(ctx context.Context, id int) (res interface{}, err error) { + model, err := data.GetBookById(ctx, id) if ent.IsNotFound(err) { err = core.NewErrorCode(errcode.BookNotFound) return } - err = data.DeleteBook(ctx, req.Id) + res = model return } diff --git a/internal/data/book.go b/internal/data/book.go index ab9b78a..7470ae2 100644 --- a/internal/data/book.go +++ b/internal/data/book.go @@ -6,8 +6,8 @@ import ( "lin-cms-go/internal/data/ent/book" ) -func GetBookAll(ctx context.Context) (model []*ent.Book, err error) { - model, err = GetDB().Book.Query().All(ctx) +func GetBookAll(ctx context.Context, page int, size int) (model []*ent.Book, err error) { + model, err = GetDB().Book.Query().Limit(size).Offset((page - 1) * size).All(ctx) return } @@ -16,6 +16,11 @@ func GetBookById(ctx context.Context, id int) (model *ent.Book, err error) { return } +func GetBookByTitle(ctx context.Context, title string) (model *ent.Book, err error) { + model, err = GetDB().Book.Query().Where(book.Title(title)).First(ctx) + return +} + func UpdateBook(ctx context.Context, id int, title string, author string, summary string, image string) (err error) { _, err = GetDB().Book.Update().Where(book.ID(id)).SetTitle(title).SetAuthor(author).SetSummary(summary).SetImage(image).Save(ctx) return @@ -30,3 +35,8 @@ func DeleteBook(ctx context.Context, id int) (err error) { err = GetDB().Book.DeleteOneID(id).Exec(ctx) return } + +func GetBookCount(ctx context.Context) (count int, err error) { + count, err = GetDB().Book.Query().Count(ctx) + return +} diff --git a/internal/request/book.go b/internal/request/book.go index 3710968..b226d5f 100644 --- a/internal/request/book.go +++ b/internal/request/book.go @@ -1,7 +1,6 @@ package request type UpdateBook struct { - Id int `json:"id" validate:"required" comment:"书籍id"` Title string `json:"title" validate:"required" comment:"书籍标题"` Author string `json:"author" validate:"required" comment:"书籍作者"` Summary string `json:"summary" validate:"required" comment:"书籍简介"` @@ -14,7 +13,7 @@ type CreateBook struct { Summary string `json:"summary" validate:"required" comment:"书籍简介"` Image string `json:"image" validate:"required" comment:"书籍封面图"` } - -type DeleteBook struct { - Id int `json:"id" validate:"required" comment:"书籍id"` +type GetBooks struct { + Size int `json:"size" binding:"required" comment:"数量"` + Page int `json:"page" binding:"required" comment:"页码"` } diff --git a/internal/server/routes.go b/internal/server/routes.go index 0a3958c..737e83d 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -54,9 +54,10 @@ func InitRoute(app *fiber.App) { logRouter.Get("/users", api.GetLogUsers) bookRouter.Get("", api.GetBooks) - bookRouter.Put("", api.UpdateBook) + bookRouter.Get("/:id", api.GetBook) + bookRouter.Put("/:id", api.UpdateBook) bookRouter.Post("", api.CreateBook) - bookRouter.Delete("", api.DeleteBook) + bookRouter.Delete("/:id", api.DeleteBook) } } diff --git a/pkg/core/response.go b/pkg/core/response.go index 34eb696..dfa3ae3 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -86,7 +86,7 @@ func SuccessResp(c *fiber.Ctx) error { Message: errcode.GetMsg(0), }) } -func SetData(c *fiber.Ctx, data map[string]interface{}) error { +func SetData(c *fiber.Ctx, data interface{}) error { return c.JSON(IError{ Code: 0, Message: errcode.GetMsg(0), diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index ed6e6f3..0d5ff74 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -13,6 +13,7 @@ const ( UserFound UserNotFound BookNotFound + BookTitleRepetition ) var MsgFlags = map[int]string{ @@ -27,6 +28,7 @@ var MsgFlags = map[int]string{ UserFound: "用户已存在", UserNotFound: "用户不存在", BookNotFound: "书籍不存在", + BookTitleRepetition: "书籍标题重复", } func GetMsg(code int) string { From 45478b55bf11606289a1781a3b9ae49ae08cefbb Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Fri, 15 Oct 2021 17:25:41 +0800 Subject: [PATCH 05/44] fix:route, get book --- api/book.go | 2 ++ internal/biz/book.go | 3 ++- internal/data/book.go | 4 ++-- internal/server/routes.go | 4 ++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/api/book.go b/api/book.go index 7f8344c..317a8c9 100644 --- a/api/book.go +++ b/api/book.go @@ -37,6 +37,7 @@ func UpdateBook(c *fiber.Ctx) error { if err != nil { return err } + err = biz.UpdateBook(c.Context(), id, req) if err != nil { return err @@ -57,6 +58,7 @@ func CreateBook(c *fiber.Ctx) error { } func DeleteBook(c *fiber.Ctx) error { + // TODO 没有软删除,ent默认没有软删除待加强 id, err := utils.StringToInt(c.Params("id")) if err != nil { return err diff --git a/internal/biz/book.go b/internal/biz/book.go index 42dea70..30808ac 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -10,7 +10,8 @@ import ( ) func GetBookAll(ctx context.Context, page int, size int) (res interface{}, err error) { - bookModel, err := data.GetBookAll(ctx, page, size) + offset := core.GetPageOffset(page, size) + bookModel, err := data.GetBookAll(ctx, offset, size) if err != nil { return } diff --git a/internal/data/book.go b/internal/data/book.go index 7470ae2..9de75a6 100644 --- a/internal/data/book.go +++ b/internal/data/book.go @@ -6,8 +6,8 @@ import ( "lin-cms-go/internal/data/ent/book" ) -func GetBookAll(ctx context.Context, page int, size int) (model []*ent.Book, err error) { - model, err = GetDB().Book.Query().Limit(size).Offset((page - 1) * size).All(ctx) +func GetBookAll(ctx context.Context, offset int, size int) (model []*ent.Book, err error) { + model, err = GetDB().Book.Query().Limit(size).Offset(offset).All(ctx) return } diff --git a/internal/server/routes.go b/internal/server/routes.go index 737e83d..df93e90 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -53,10 +53,10 @@ func InitRoute(app *fiber.App) { logRouter.Get("/search", api.SearchLogs) logRouter.Get("/users", api.GetLogUsers) - bookRouter.Get("", api.GetBooks) + bookRouter.Get("/", api.GetBooks) bookRouter.Get("/:id", api.GetBook) bookRouter.Put("/:id", api.UpdateBook) - bookRouter.Post("", api.CreateBook) + bookRouter.Post("/", api.CreateBook) bookRouter.Delete("/:id", api.DeleteBook) } From bdd8981247d900f619ebf2da05b800fefdfdd8ef Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 18 Oct 2021 11:34:30 +0800 Subject: [PATCH 06/44] fix: changeMyPassword, timemixin feat: custom ent template --- api/user.go | 5 +- internal/biz/admin.go | 6 +- internal/data/ent/generate.go | 2 +- internal/data/ent/schema/lin_user.go | 3 +- internal/data/ent/schema/lin_user_group.go | 18 +- internal/data/ent/tmpl/quey.tmpl | 623 +++++++++++++++++++++ 6 files changed, 631 insertions(+), 26 deletions(-) create mode 100644 internal/data/ent/tmpl/quey.tmpl diff --git a/api/user.go b/api/user.go index a3f8137..eae3943 100644 --- a/api/user.go +++ b/api/user.go @@ -60,10 +60,9 @@ func ChangeMyPassword(c *fiber.Ctx) error { if err := core.ParseRequest(c, &req); err != nil { return err } + user := biz.LocalUser(c) - var uid int - - err := biz.ChangeMyPassword(c.Context(), req, uid) + err := biz.ChangeMyPassword(c.Context(), req, user.ID) if err != nil { return err diff --git a/internal/biz/admin.go b/internal/biz/admin.go index a08576c..714d9a4 100644 --- a/internal/biz/admin.go +++ b/internal/biz/admin.go @@ -2,7 +2,6 @@ package biz import ( "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" ) func GetUsers(req request.GetUsers) (data map[string]interface{}, err error) { @@ -27,10 +26,7 @@ func ChangeUserPassword(req request.ChangeUserPassword) (err error) { return } func DeleteUser(id int) (err error) { - if id <= 0 { - err = core.NewInvalidParamsError("id cannot be negative") - return - } + return } func UpdateUser(req request.UpdateUser) (err error) { diff --git a/internal/data/ent/generate.go b/internal/data/ent/generate.go index 8d3fdfd..bef3464 100644 --- a/internal/data/ent/generate.go +++ b/internal/data/ent/generate.go @@ -1,3 +1,3 @@ package ent -//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema +//go:generate go run -mod=mod entgo.io/ent/cmd/ent --template glob=./tmpl/*.tmpl generate ./schema diff --git a/internal/data/ent/schema/lin_user.go b/internal/data/ent/schema/lin_user.go index 41faa30..6be21a0 100644 --- a/internal/data/ent/schema/lin_user.go +++ b/internal/data/ent/schema/lin_user.go @@ -6,7 +6,6 @@ import ( "entgo.io/ent/schema" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" - "entgo.io/ent/schema/mixin" ) type LinUser struct { @@ -20,7 +19,7 @@ func (LinUser) Annotations() []schema.Annotation { } func (LinUser) Mixin() []ent.Mixin { return []ent.Mixin{ - mixin.Time{}, + TimeMixin{}, } } func (LinUser) Fields() []ent.Field { diff --git a/internal/data/ent/schema/lin_user_group.go b/internal/data/ent/schema/lin_user_group.go index 714d18e..0457e54 100644 --- a/internal/data/ent/schema/lin_user_group.go +++ b/internal/data/ent/schema/lin_user_group.go @@ -3,6 +3,7 @@ package schema import ( "entgo.io/ent" "entgo.io/ent/schema/field" + "entgo.io/ent/schema/mixin" "time" ) @@ -21,20 +22,7 @@ func (TimeMixin) Fields() []ent.Field { field.Time("updated_time"). Default(time.Now). UpdateDefault(time.Now), + field.Time("delete_time"). + Default(nil), } } - -//type LinUserGroup struct { -// ent.Schema -//} -//func (LinUserGroup) Annotations() []schema.Annotation { -// return []schema.Annotation{ -// entsql.Annotation{Table: "lin_user_group"}, -// } -//} -//func (LinUserGroup) Fields() []ent.Field { -// return []ent.Field{ -// field.Int("user_id").Comment("用户id").Unique(), -// field.Int("group_id").Comment("分组id"), -// } -//} diff --git a/internal/data/ent/tmpl/quey.tmpl b/internal/data/ent/tmpl/quey.tmpl new file mode 100644 index 0000000..e8b0121 --- /dev/null +++ b/internal/data/ent/tmpl/quey.tmpl @@ -0,0 +1,623 @@ +{{/* +Copyright 2019-present Facebook Inc. All rights reserved. +This source code is licensed under the Apache 2.0 license found +in the LICENSE file in the root directory of this source tree. +*/}} + +{{/* gotype: entgo.io/ent/entc/gen.Type */}} + +{{ define "query" }} +{{ $pkg := base $.Config.Package }} + +{{ template "header" $ }} + +{{ template "import" $ }} + +import ( + {{- range $path := $.SiblingImports }} + "{{ $path }}" + {{- end }} +) + +{{ $builder := $.QueryName }} +{{ $receiver := receiver $builder }} + +// {{ $builder }} is the builder for querying {{ $.Name }} entities. +type {{ $builder }} struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.{{ $.Name }} + {{- with $.Edges }} + // eager-loading edges. + {{- range $e := . }} + {{ $e.EagerLoadField }} *{{ $e.Type.QueryName }} + {{- end }} + {{- end }} + {{- /* Additional fields to add to the builder. */}} + {{- $tmpl := printf "dialect/%s/query/fields" $.Storage }} + {{- if hasTemplate $tmpl }} + {{- xtemplate $tmpl . }} + {{- end }} + // intermediate query (i.e. traversal path). + {{ $.Storage }} {{ $.Storage.Builder }} + path func(context.Context) ({{ $.Storage.Builder }}, error) +} + +// Where adds a new predicate for the {{ $builder }} builder. +func ({{ $receiver }} *{{ $builder }}) Where(ps ...predicate.{{ $.Name }}) *{{ $builder }} { + {{ $receiver}}.predicates = append({{ $receiver }}.predicates, ps...) + return {{ $receiver }} +} + +// Limit adds a limit step to the query. +func ({{ $receiver }} *{{ $builder }}) Limit(limit int) *{{ $builder }} { + {{ $receiver }}.limit = &limit + return {{ $receiver }} +} + +// Offset adds an offset step to the query. +func ({{ $receiver }} *{{ $builder }}) Offset(offset int) *{{ $builder }} { + {{ $receiver }}.offset = &offset + return {{ $receiver }} +} + +// 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 ({{ $receiver }} *{{ $builder }}) Unique(unique bool) *{{ $builder }} { + {{ $receiver }}.unique = &unique + return {{ $receiver }} +} + +// Order adds an order step to the query. +func ({{ $receiver }} *{{ $builder }}) Order(o ...OrderFunc) *{{ $builder }} { + {{ $receiver }}.order = append({{ $receiver }}.order, o...) + return {{ $receiver }} +} + +{{/* this code has similarity with edge queries in client.tmpl */}} +{{ range $e := $.Edges }} + {{ $edge_builder := print (pascal $e.Type.Name) "Query" }} + // Query{{ pascal $e.Name }} chains the current query on the "{{ $e.Name }}" edge. + func ({{ $receiver }} *{{ $builder }}) Query{{ pascal $e.Name }}() *{{ $edge_builder }} { + query := &{{ $edge_builder }}{config: {{ $receiver }}.config} + query.path = func(ctx context.Context) (fromU {{ $.Storage.Builder }}, err error) { + if err := {{ $receiver }}.prepareQuery(ctx); err != nil { + return nil, err + } + {{- with extend $ "Receiver" $receiver "Edge" $e "Ident" "fromU" -}} + {{ $tmpl := printf "dialect/%s/query/path" $.Storage }} + {{- xtemplate $tmpl . }} + {{- end -}} + return fromU, nil + } + return query + } +{{ end }} + +// First returns the first {{ $.Name }} entity from the query. +// Returns a *NotFoundError when no {{ $.Name }} was found. +func ({{ $receiver }} *{{ $builder }}) First(ctx context.Context) (*{{ $.Name }}, error) { + nodes, err := {{ $receiver }}.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{ {{ $.Package }}.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) FirstX(ctx context.Context) *{{ $.Name }} { + node, err := {{ $receiver }}.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first {{ $.Name }} ID from the query. +// Returns a *NotFoundError when no {{ $.Name }} ID was found. +func ({{ $receiver }} *{{ $builder }}) FirstID(ctx context.Context) (id {{ $.ID.Type }}, err error) { + var ids []{{ $.ID.Type }} + if ids, err = {{ $receiver }}.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{ {{ $.Package }}.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) FirstIDX(ctx context.Context) {{ $.ID.Type }} { + id, err := {{ $receiver }}.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last {{ $.Name }} entity from the query. +// Returns a *NotFoundError when no {{ $.Name }} was found. +func ({{ $receiver }} *{{ $builder }}) Last(ctx context.Context) (*{{ $.Name }}, error) { + nodes, err := {{ $receiver }}.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{ {{ $.Package }}.Label} + } + return nodes[len(nodes)-1], nil +} +// LastX is like Last, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) LastX(ctx context.Context) *{{ $.Name }} { + node, err := {{ $receiver }}.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last {{ $.Name }} ID from the query. +// Returns a *NotFoundError when no {{ $.Name }} ID was found. +func ({{ $receiver }} *{{ $builder }}) LastID(ctx context.Context) (id {{ $.ID.Type }}, err error) { + var ids []{{ $.ID.Type }} + if ids, err = {{ $receiver }}.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{ {{ $.Package }}.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) LastIDX(ctx context.Context) {{ $.ID.Type }} { + id, err := {{ $receiver }}.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} +// Only returns a single {{ $.Name }} entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one {{ $.Name }} entity is not found. +// Returns a *NotFoundError when no {{ $.Name }} entities are found. +func ({{ $receiver }} *{{ $builder }}) Only(ctx context.Context) (*{{ $.Name }}, error) { + nodes, err := {{ $receiver }}.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{ {{ $.Package }}.Label} + default: + return nil, &NotSingularError{ {{ $.Package }}.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) OnlyX(ctx context.Context) *{{ $.Name }} { + node, err := {{ $receiver }}.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only {{ $.Name }} ID in the query. +// Returns a *NotSingularError when exactly one {{ $.Name }} ID is not found. +// Returns a *NotFoundError when no entities are found. +func ({{ $receiver }} *{{ $builder }}) OnlyID(ctx context.Context) (id {{ $.ID.Type }}, err error) { + var ids []{{ $.ID.Type }} + if ids, err = {{ $receiver }}.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{ {{ $.Package }}.Label} + default: + err = &NotSingularError{ {{ $.Package }}.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) OnlyIDX(ctx context.Context) {{ $.ID.Type }} { + id, err := {{ $receiver }}.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of {{ plural $.Name }}. +func ({{ $receiver }} *{{ $builder }}) All(ctx context.Context) ([]*{{ $.Name }}, error) { + if err := {{ $receiver }}.prepareQuery(ctx); err != nil { + return nil, err + } + return {{ $receiver }}.{{ $.Storage }}All(ctx) +} + +// AllX is like All, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) AllX(ctx context.Context) []*{{ $.Name }} { + nodes, err := {{ $receiver }}.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of {{ $.Name }} IDs. +func ({{ $receiver }} *{{ $builder }}) IDs(ctx context.Context) ([]{{ $.ID.Type }}, error) { + var ids []{{ $.ID.Type }} + if err := {{ $receiver }}.Select({{ $.Package }}.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) IDsX(ctx context.Context) []{{ $.ID.Type }} { + ids, err := {{ $receiver }}.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func ({{ $receiver }} *{{ $builder }}) Count(ctx context.Context) (int, error) { + if err := {{ $receiver }}.prepareQuery(ctx); err != nil { + return 0, err + } + return {{ $receiver }}.{{ $.Storage }}Count(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) CountX(ctx context.Context) int { + count, err := {{ $receiver }}.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func ({{ $receiver }} *{{ $builder }}) Exist(ctx context.Context) (bool, error) { + if err := {{ $receiver }}.prepareQuery(ctx); err != nil { + return false, err + } + return {{ $receiver }}.{{ $.Storage }}Exist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func ({{ $receiver }} *{{ $builder }}) ExistX(ctx context.Context) bool { + exist, err := {{ $receiver }}.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the {{ $builder }} builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func ({{ $receiver }} *{{ $builder }}) Clone() *{{ $builder }} { + if {{ $receiver }} == nil { + return nil + } + return &{{ $builder }}{ + config: {{ $receiver }}.config, + limit: {{ $receiver }}.limit, + offset: {{ $receiver }}.offset, + order: append([]OrderFunc{}, {{ $receiver }}.order...), + predicates: append([]predicate.{{ $.Name }}{}, {{ $receiver }}.predicates...), + {{- range $e := $.Edges }} + {{ $e.EagerLoadField }}: {{ $receiver }}.{{ $e.EagerLoadField }}.Clone(), + {{- end }} + // clone intermediate query. + {{ $.Storage }}: {{ $receiver }}.{{ $.Storage }}.Clone(), + path: {{ $receiver }}.path, + } +} + +{{- range $e := $.Edges }} + {{ $ebuilder := $e.Type.QueryName }} + // With{{ pascal $e.Name }} tells the query-builder to eager-load the nodes that are connected to + // the "{{ $e.Name }}" edge. The optional arguments are used to configure the query builder of the edge. + func ({{ $receiver }} *{{ $builder }}) With{{ pascal $e.Name }}(opts ...func(*{{ $ebuilder }})) *{{ $builder }} { + query := &{{ $ebuilder }}{config: {{ $receiver }}.config} + for _, opt := range opts { + opt(query) + } + {{ $receiver }}.{{ $e.EagerLoadField }} = query + return {{ $receiver }} + } +{{- end }} + +{{ $groupBuilder := pascal $.Name | printf "%sGroupBy" }} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: {{ join (keys aggregate) ", " }}. +{{- with len $.Fields }} +{{- $f := index $.Fields 0 }} +// +// Example: +// +// var v []struct { +// {{ $f.StructField }} {{ $f.Type }} `{{ $f.StructTag }}` +// Count int `json:"count,omitempty"` +// } +// +// client.{{ pascal $.Name }}.Query(). +// GroupBy({{ $.Package }}.{{ $f.Constant }}). +// Aggregate({{ $pkg }}.Count()). +// Scan(ctx, &v) +// +{{- end }} +func ({{ $receiver }} *{{ $builder }}) GroupBy(field string, fields ...string) *{{ $groupBuilder }} { + group := &{{ $groupBuilder }}{config: {{ $receiver }}.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev {{ $.Storage.Builder }}, err error) { + if err := {{ $receiver }}.prepareQuery(ctx); err != nil { + return nil, err + } + return {{ $receiver }}.{{ $.Storage }}Query(ctx), nil + } + return group +} + +{{ $selectBuilder := pascal $.Name | printf "%sSelect" }} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +{{- with len $.Fields }} +{{- $f := index $.Fields 0 }} +// +// Example: +// +// var v []struct { +// {{ $f.StructField }} {{ $f.Type }} `{{ $f.StructTag }}` +// } +// +// client.{{ pascal $.Name }}.Query(). +// Select({{ $.Package }}.{{ $f.Constant }}). +// Scan(ctx, &v) +// +{{- end }} +func ({{ $receiver }} *{{ $builder }}) Select(fields ...string) *{{ $selectBuilder }} { + {{ $receiver }}.fields = append({{ $receiver }}.fields, fields...) + return &{{ $selectBuilder }}{ {{ $builder }}: {{ $receiver }} } +} + +func ({{ $receiver }} *{{ $builder }}) prepareQuery(ctx context.Context) error { + {{- /* Optional prepare checks per dialect. */}} + {{- $tmpl = printf "dialect/%s/query/preparecheck" $.Storage }} + {{- if hasTemplate $tmpl }} + {{- with extend $ "Receiver" $receiver "Package" $pkg }} + {{- xtemplate $tmpl . }} + {{- end }} + {{- end }} + if {{ $receiver }}.path != nil { + prev, err := {{ $receiver }}.path(ctx) + if err != nil { + return err + } + {{ $receiver }}.{{ $.Storage }} = prev + } + {{- if $.NumPolicy }} + if {{ $.Package }}.Policy == nil { + return errors.New("{{ $pkg }}: uninitialized {{ $.Package }}.Policy (forgotten import {{ $pkg }}/runtime?)") + } + if err := {{ $.Package }}.Policy.EvalQuery(ctx, {{ $receiver }}); err != nil { + return err + } + {{- end }} + return nil +} + +{{ with extend $ "Builder" $builder "Package" $pkg }} + {{ $tmpl := printf "dialect/%s/query" $.Storage }} + {{ xtemplate $tmpl . }} +{{ end }} + +{{- /* Support adding query methods by global templates. In order to generate dialect-sepcific methods, + prefix this template with "dialect/{{ .Storage }}". For example: "dialect/sql/query/additional/*". */}} +{{- with $tmpls := matchTemplate "query/additional/*" }} + {{- range $tmpl := $tmpls }} + {{ xtemplate $tmpl $ }} + {{- end }} +{{- end }} + + +{{/* groupby builder */}} + +{{ $groupReceiver := receiver $groupBuilder }} + +// {{ $groupBuilder }} is the group-by builder for {{ $.Name }} entities. +type {{ $groupBuilder }} struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + {{ $.Storage }} {{ $.Storage.Builder }} + path func(context.Context) ({{ $.Storage.Builder }}, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func ({{ $groupReceiver }} *{{ $groupBuilder }}) Aggregate(fns ...AggregateFunc) *{{ $groupBuilder }} { + {{ $groupReceiver }}.fns = append({{ $groupReceiver }}.fns, fns...) + return {{ $groupReceiver }} +} + +// Scan applies the group-by query and scans the result into the given value. +func ({{ $groupReceiver }} *{{ $groupBuilder }}) Scan(ctx context.Context, v interface{}) error { + query, err := {{ $groupReceiver }}.path(ctx) + if err != nil { + return err + } + {{ $groupReceiver }}.{{ $.Storage }} = query + return {{ $groupReceiver }}.{{ $.Storage }}Scan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func ({{ $groupReceiver }} *{{ $groupBuilder }}) ScanX(ctx context.Context, v interface{}) { + if err := {{ $groupReceiver }}.Scan(ctx, v); err != nil { + panic(err) + } +} + +{{ range $t := primitives }} + {{ $plural := pascal $t | plural }} + // {{ $plural }} returns list of {{ plural $t }} from group-by. + // It is only allowed when executing a group-by query with one field. + func ({{ $groupReceiver }} *{{ $groupBuilder }}) {{ $plural }}(ctx context.Context) ([]{{ $t }}, error) { + if len({{ $groupReceiver }}.fields) > 1 { + return nil, errors.New("{{ $pkg }}: {{ $groupBuilder }}.{{ $plural }} is not achievable when grouping more than 1 field") + } + var v []{{ $t }} + if err := {{ $groupReceiver }}.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil + } + + // {{ $plural }}X is like {{ $plural }}, but panics if an error occurs. + func ({{ $groupReceiver }} *{{ $groupBuilder }}) {{ $plural }}X(ctx context.Context) []{{ $t }} { + v, err := {{ $groupReceiver }}.{{ $plural }}(ctx) + if err != nil { + panic(err) + } + return v + } + + {{ $singular := pascal $t -}} + // {{ $singular }} returns a single {{ $t }} from a group-by query. + // It is only allowed when executing a group-by query with one field. + func ({{ $groupReceiver }} *{{ $groupBuilder }}) {{ $singular }}(ctx context.Context) (_ {{ $t }}, err error) { + var v []{{ $t }} + if v, err = {{ $groupReceiver }}.{{ $plural }}(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{ {{ $.Package }}.Label} + default: + err = fmt.Errorf("{{ $pkg }}: {{ $groupBuilder }}.{{ $plural }} returned %d results when one was expected", len(v)) + } + return + } + + // {{ $singular }}X is like {{ $singular }}, but panics if an error occurs. + func ({{ $groupReceiver }} *{{ $groupBuilder }}) {{ $singular }}X(ctx context.Context) {{ $t }} { + v, err := {{ $groupReceiver }}.{{ $singular }}(ctx) + if err != nil { + panic(err) + } + return v + } +{{ end }} + +{{ with extend $ "Builder" $groupBuilder }} + {{ $tmpl := printf "dialect/%s/group" $.Storage }} + {{ xtemplate $tmpl . }} +{{ end }} + +{{/* select builder */}} + +{{ $selectReceiver := receiver $selectBuilder }} + +// {{ $selectBuilder }} is the builder for selecting fields of {{ pascal $.Name }} entities. +type {{ $selectBuilder }} struct { + *{{ $builder }} + // intermediate query (i.e. traversal path). + {{ $.Storage }} {{ $.Storage.Builder }} +} + + +// Scan applies the selector query and scans the result into the given value. +func ({{ $selectReceiver }} *{{ $selectBuilder }}) Scan(ctx context.Context, v interface{}) error { + if err := {{ $selectReceiver }}.prepareQuery(ctx); err != nil { + return err + } + {{ $selectReceiver }}.{{ $.Storage }} = {{ $selectReceiver }}.{{ $builder }}.{{ $.Storage }}Query(ctx) + return {{ $selectReceiver }}.{{ $.Storage }}Scan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func ({{ $selectReceiver }} *{{ $selectBuilder }}) ScanX(ctx context.Context, v interface{}) { + if err := {{ $selectReceiver }}.Scan(ctx, v); err != nil { + panic(err) + } +} + +{{ range $t := primitives }} + {{ $plural := pascal $t | plural }} + // {{ $plural }} returns list of {{ plural $t }} from a selector. It is only allowed when selecting one field. + func ({{ $selectReceiver }} *{{ $selectBuilder }}) {{ $plural }}(ctx context.Context) ([]{{ $t }}, error) { + if len({{ $selectReceiver }}.fields) > 1 { + return nil, errors.New("{{ $pkg }}: {{ $selectBuilder }}.{{ $plural }} is not achievable when selecting more than 1 field") + } + var v []{{ $t }} + if err := {{ $selectReceiver }}.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil + } + + // {{ $plural }}X is like {{ $plural }}, but panics if an error occurs. + func ({{ $selectReceiver }} *{{ $selectBuilder }}) {{ $plural }}X(ctx context.Context) []{{ $t }} { + v, err := {{ $selectReceiver }}.{{ $plural }}(ctx) + if err != nil { + panic(err) + } + return v + } + + {{ $singular := pascal $t -}} + // {{ $singular }} returns a single {{ $t }} from a selector. It is only allowed when selecting one field. + func ({{ $selectReceiver }} *{{ $selectBuilder }}) {{ $singular }}(ctx context.Context) (_ {{ $t }}, err error) { + var v []{{ $t }} + if v, err = {{ $selectReceiver }}.{{ $plural }}(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{ {{ $.Package }}.Label} + default: + err = fmt.Errorf("{{ $pkg }}: {{ $selectBuilder }}.{{ $plural }} returned %d results when one was expected", len(v)) + } + return + } + + // {{ $singular }}X is like {{ $singular }}, but panics if an error occurs. + func ({{ $selectReceiver }} *{{ $selectBuilder }}) {{ $singular }}X(ctx context.Context) {{ $t }} { + v, err := {{ $selectReceiver }}.{{ $singular }}(ctx) + if err != nil { + panic(err) + } + return v + } +{{ end }} + +{{ with extend $ "Builder" $selectBuilder }} + {{ $tmpl := printf "dialect/%s/select" $.Storage }} + {{ xtemplate $tmpl . }} +{{ end }} + +{{ end }} + From ea85503574f602811309d6c938d4b5beb0b0d956 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 18 Oct 2021 16:16:42 +0800 Subject: [PATCH 07/44] feat: zap logger middleware --- go.mod | 5 +- go.sum | 34 ++++++- internal/biz/user.go | 3 +- internal/server/routes.go | 2 +- internal/server/server.go | 7 -- main.go | 49 +++++----- pkg/core/response.go | 2 +- pkg/log/logger.go | 20 ++++ pkg/logger/logger.go | 198 -------------------------------------- 9 files changed, 81 insertions(+), 239 deletions(-) create mode 100644 pkg/log/logger.go delete mode 100644 pkg/logger/logger.go diff --git a/go.mod b/go.mod index 6895939..6d9dab8 100644 --- a/go.mod +++ b/go.mod @@ -8,11 +8,12 @@ require ( github.com/go-playground/universal-translator v0.17.0 github.com/go-playground/validator/v10 v10.2.0 github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae - github.com/gofiber/fiber/v2 v2.20.1 + github.com/gofiber/contrib/fiberzap v0.0.0-20211018071624-ed00d4b0c380 + github.com/gofiber/fiber/v2 v2.20.2 github.com/gofiber/jwt/v3 v3.1.2 github.com/golang-jwt/jwt/v4 v4.1.0 - github.com/google/wire v0.5.0 github.com/stretchr/testify v1.7.0 + go.uber.org/zap v1.19.1 golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a gopkg.in/yaml.v2 v2.4.0 diff --git a/go.sum b/go.sum index 487df58..026ef8d 100644 --- a/go.sum +++ b/go.sum @@ -22,9 +22,13 @@ github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/andybalholm/brotli v1.0.2 h1:JKnhI/XQ75uFBTiuzXpzFrUriDPiZjlOSzh6wXogP0E= github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/andybalholm/brotli v1.0.3 h1:fpcw+r1N1h0Poc1F/pHbW40cUm/lMEQslZtCkBQ0UnM= +github.com/andybalholm/brotli v1.0.3/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= @@ -69,8 +73,12 @@ github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GO github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae h1:L6V0ANsMIMdLgXly241UXhXNFWYgXbgjHupTAAURrV0= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gofiber/contrib/fiberzap v0.0.0-20211018071624-ed00d4b0c380 h1:ZLbgNlAX0MYYxI9Sv7V8Z9foTx9a/ZQYequUfhdJYyw= +github.com/gofiber/contrib/fiberzap v0.0.0-20211018071624-ed00d4b0c380/go.mod h1:P5ce3JdsGV4XP7QZUYNmR/vLG7N5A3JUMmpaqGklW60= github.com/gofiber/fiber/v2 v2.20.1 h1:p463gd/RI8YeYxP4WMGS+u1UtBS88yk8oLiPkEiDYx4= github.com/gofiber/fiber/v2 v2.20.1/go.mod h1:/LdZHMUXZvTTo7gU4+b1hclqCAdoQphNQ9bi9gutPyI= +github.com/gofiber/fiber/v2 v2.20.2 h1:dqizbjO1pCmH6K+b+kBk7TCJK4rmgjJXvX8/MZDbK60= +github.com/gofiber/fiber/v2 v2.20.2/go.mod h1:/LdZHMUXZvTTo7gU4+b1hclqCAdoQphNQ9bi9gutPyI= github.com/gofiber/jwt/v3 v3.1.2 h1:Gsp1BgkUWo3ZbZZSSBJs+IVE1t89m1n/pOe0P9sIG/c= github.com/gofiber/jwt/v3 v3.1.2/go.mod h1:Z05kGvvdRqbWMvb3uYmAPwfFyCV8/n/QVorzq4XjwvU= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= @@ -109,12 +117,9 @@ github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXi github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/wire v0.5.0 h1:I7ELFeVBr3yfPIcc8+MWvrjk+3VjbcSzoXm3JVa+jD8= -github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= @@ -156,6 +161,8 @@ github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQL github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.13.4 h1:0zhec2I8zGnjWcKyLl6i3gPqKANCCn5e9xmviEEeX6s= github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= @@ -194,6 +201,7 @@ github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6 github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -243,6 +251,8 @@ github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6Kllzaw github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.29.0 h1:F5GKpytwFk5OhCuRh6H+d4vZAcEeNAwPTdwQnm6IERY= github.com/valyala/fasthttp v1.29.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= +github.com/valyala/fasthttp v1.31.0 h1:lrauRLII19afgCs2fnWRJ4M5IkV0lo2FqA61uGkNBfE= +github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= @@ -251,9 +261,20 @@ go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11-0.20210813005559-691160354723 h1:sHOAIxRGBp443oHZIPB+HsUGaksVCXVQENPxwTfQdH4= +go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= +go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -276,6 +297,7 @@ golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= @@ -332,6 +354,8 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211013075003-97ac67df715c h1:taxlMj0D/1sOAuv/CbSD+MMDof2vbyPTqz5FNYKpXt8= +golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -350,7 +374,6 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -416,10 +439,13 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/internal/biz/user.go b/internal/biz/user.go index e659294..d843293 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -3,7 +3,6 @@ package biz import ( "context" "errors" - "github.com/golang-jwt/jwt/v4" "lin-cms-go/internal/data" "lin-cms-go/internal/data/ent" "lin-cms-go/internal/request" @@ -12,6 +11,8 @@ import ( "lin-cms-go/pkg/lib" "time" + "github.com/golang-jwt/jwt/v4" + "golang.org/x/crypto/bcrypt" ) diff --git a/internal/server/routes.go b/internal/server/routes.go index df93e90..1239df6 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -49,7 +49,7 @@ func InitRoute(app *fiber.App) { adminRouter.Post("/permissions/dispatch", api.DispatchPermissions) adminRouter.Post("/permissions/remove", api.RemovePermissions) - logRouter.Get("", api.GetLogs) + logRouter.Get("/", api.GetLogs) logRouter.Get("/search", api.SearchLogs) logRouter.Get("/users", api.GetLogUsers) diff --git a/internal/server/server.go b/internal/server/server.go index 29677a4..abb4e43 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1,8 +1 @@ package server - -import ( - "github.com/google/wire" -) - -// ProviderSet is server providers. -var ProviderSet = wire.NewSet(NewHTTPServer) diff --git a/main.go b/main.go index 731a397..d898ee2 100644 --- a/main.go +++ b/main.go @@ -1,38 +1,37 @@ package main import ( + "github.com/gofiber/contrib/fiberzap" + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/cors" + "github.com/gofiber/fiber/v2/middleware/recover" + "gopkg.in/yaml.v2" "io/ioutil" "lin-cms-go/internal/conf" "lin-cms-go/internal/data" "lin-cms-go/internal/server" "lin-cms-go/pkg/core" - "log" - - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/logger" - "github.com/gofiber/fiber/v2/middleware/recover" - "gopkg.in/yaml.v2" + "lin-cms-go/pkg/log" ) +func errorHandler(c *fiber.Ctx, err error) error { + // Status code defaults to 500 + if e, ok := err.(core.IError); ok { + if e.Err == nil { + return e.HttpError(c) + } + + } + + return core.ServerError(c, err) +} func initApp(c *conf.Config) *fiber.App { - app := fiber.New(fiber.Config{ - // Override default error handler - ErrorHandler: func(c *fiber.Ctx, err error) error { - // Status code defaults to 500 - if e, ok := err.(core.IError); ok { - if e.Err == nil { - return e.HttpError(c) - } - - } - if e, ok := err.(error); ok { - return core.InvalidParamsError(c, e.Error()) - - } - return core.ServerError(c, err) - - }}) - app.Use(recover.New(), logger.New()) + app := fiber.New(fiber.Config{ErrorHandler: errorHandler}) + app.Use(fiberzap.New(fiberzap.Config{ + Logger: log.Defaultlogger, + Fields: []string{"method", "url", "latency", "status", "reqbody", "body", "error"}, + })) + app.Use(recover.New(), cors.New()) data.NewDataSource(&c.Data) //TODO clean source @@ -54,5 +53,5 @@ func main() { } app := initApp(c) - log.Fatal(app.Listen(c.Server.Http.Addr)) + app.Listen(c.Server.Http.Addr) } diff --git a/pkg/core/response.go b/pkg/core/response.go index dfa3ae3..cf2f9f9 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -75,7 +75,7 @@ func InvalidParamsError(c *fiber.Ctx, msg string) error { return c.JSON(IError{ Code: errcode.InvalidParams, - Message: msg, + Message: errcode.GetMsg(errcode.InvalidParams), }) } diff --git a/pkg/log/logger.go b/pkg/log/logger.go new file mode 100644 index 0000000..b25bfa7 --- /dev/null +++ b/pkg/log/logger.go @@ -0,0 +1,20 @@ +package log + +import ( + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +var Defaultlogger *zap.Logger + +func init() { + + encoderConfig := zap.NewProductionEncoderConfig() + encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.00") + + config := zap.NewProductionConfig() + config.EncoderConfig = encoderConfig + + Defaultlogger, _ = config.Build() + +} diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go deleted file mode 100644 index eb3ffa2..0000000 --- a/pkg/logger/logger.go +++ /dev/null @@ -1,198 +0,0 @@ -package logger - -import ( - "context" - "encoding/json" - "fmt" - "io" - "log" - "runtime" - "time" -) - -type Level int8 - -type Fields map[string]interface{} - -const ( - LevelDebug Level = iota - LevelInfo - LevelWarn - LevelError - LevelFatal - LevelPanic -) - -func (l Level) String() string { - switch l { - case LevelDebug: - return "[DEBUG]" - case LevelInfo: - return "[INFO]" - case LevelWarn: - return "[WARN]" - case LevelError: - return "[ERROR]" - case LevelFatal: - return "[FATAL]" - case LevelPanic: - return "[PANIC]" - } - return "" -} - -type Logger struct { - newLogger *log.Logger - ctx context.Context - fields Fields - callers []string -} - -func NewLogger(w io.Writer, prefix string, flag int) *Logger { - l := log.New(w, prefix, flag) - return &Logger{newLogger: l} -} - -func (l *Logger) clone() *Logger { - nl := *l - return &nl -} - -func (l *Logger) WithFields(f Fields) *Logger { - ll := l.clone() - if ll.fields == nil { - ll.fields = make(Fields) - } - for k, v := range f { - ll.fields[k] = v - } - return ll -} - -func (l *Logger) WithContext(ctx context.Context) *Logger { - ll := l.clone() - ll.ctx = ctx - return ll -} - -func (l *Logger) WithCaller(skip int) *Logger { - ll := l.clone() - pc, file, line, ok := runtime.Caller(skip) - if ok { - f := runtime.FuncForPC(pc) - ll.callers = []string{fmt.Sprintf("%s: %d %s", file, line, f.Name())} - } - - return ll -} - -func (l *Logger) WithCallersFrames() *Logger { - maxCallerDepth := 25 - minCallerDepth := 1 - callers := []string{} - pcs := make([]uintptr, maxCallerDepth) - depth := runtime.Callers(minCallerDepth, pcs) - frames := runtime.CallersFrames(pcs[:depth]) - for frame, more := frames.Next(); more; frame, more = frames.Next() { - s := fmt.Sprintf("%s: %d %s", frame.File, frame.Line, frame.Function) - callers = append(callers, s) - if !more { - break - } - } - ll := l.clone() - ll.callers = callers - return ll -} - -func (l *Logger) WithTrace() *Logger { - return l.WithFields(Fields{ - "trace_id": "X-Trace-ID", - "span_id": "X-Span-ID", - }) -} - -func (l *Logger) JSONFormat(level Level, message string) map[string]interface{} { - data := make(Fields, len(l.fields)+4) - - data["time"] = time.Now().Local().Format("2006-01-02 15:04:05.0000") - data["message"] = message - data["callers"] = l.callers - if len(l.fields) > 0 { - for k, v := range l.fields { - if _, ok := data[k]; !ok { - data[k] = v - } - } - } - - return data -} - -func (l *Logger) Output(level Level, message string) { - body, _ := json.Marshal(l.JSONFormat(level, message)) - content := level.String() + string(body) - - switch level { - case LevelDebug: - l.newLogger.Print(content) - case LevelInfo: - l.newLogger.Print(content) - case LevelWarn: - l.newLogger.Print(content) - case LevelError: - l.newLogger.Print(content) - case LevelFatal: - l.newLogger.Fatal(content) - case LevelPanic: - l.newLogger.Panic(content) - } -} - -func (l *Logger) Debug(ctx context.Context, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelDebug, fmt.Sprint(v...)) -} - -func (l *Logger) Debugf(ctx context.Context, format string, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelDebug, fmt.Sprintf(format, v...)) -} - -func (l *Logger) Info(ctx context.Context, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelInfo, fmt.Sprint(v...)) -} - -func (l *Logger) Infof(ctx context.Context, format string, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelInfo, fmt.Sprintf(format, v...)) -} - -func (l *Logger) Warn(ctx context.Context, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelWarn, fmt.Sprint(v...)) -} - -func (l *Logger) Warnf(ctx context.Context, format string, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelWarn, fmt.Sprintf(format, v...)) -} - -func (l *Logger) Error(ctx context.Context, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelError, fmt.Sprint(v...)) -} - -func (l *Logger) Errorf(ctx context.Context, format string, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelError, fmt.Sprintf(format, v...)) -} - -func (l *Logger) Fatal(ctx context.Context, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelFatal, fmt.Sprint(v...)) -} - -func (l *Logger) Fatalf(ctx context.Context, format string, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelFatal, fmt.Sprintf(format, v...)) -} - -func (l *Logger) Panic(ctx context.Context, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelPanic, fmt.Sprint(v...)) -} - -func (l *Logger) Panicf(ctx context.Context, format string, v ...interface{}) { - l.WithContext(ctx).WithTrace().Output(LevelPanic, fmt.Sprintf(format, v...)) -} From 97b4a417effda903a22d48655856cdfe725c1bf1 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 18 Oct 2021 18:27:33 +0800 Subject: [PATCH 08/44] remove: zap logger middleware --- go.mod | 2 - main.go | 19 +++-- pkg/log/logger.go | 199 +++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 203 insertions(+), 17 deletions(-) diff --git a/go.mod b/go.mod index 6d9dab8..2e9d3a5 100644 --- a/go.mod +++ b/go.mod @@ -8,12 +8,10 @@ require ( github.com/go-playground/universal-translator v0.17.0 github.com/go-playground/validator/v10 v10.2.0 github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae - github.com/gofiber/contrib/fiberzap v0.0.0-20211018071624-ed00d4b0c380 github.com/gofiber/fiber/v2 v2.20.2 github.com/gofiber/jwt/v3 v3.1.2 github.com/golang-jwt/jwt/v4 v4.1.0 github.com/stretchr/testify v1.7.0 - go.uber.org/zap v1.19.1 golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a gopkg.in/yaml.v2 v2.4.0 diff --git a/main.go b/main.go index d898ee2..63dc288 100644 --- a/main.go +++ b/main.go @@ -1,9 +1,9 @@ package main import ( - "github.com/gofiber/contrib/fiberzap" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" + "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/recover" "gopkg.in/yaml.v2" "io/ioutil" @@ -12,6 +12,7 @@ import ( "lin-cms-go/internal/server" "lin-cms-go/pkg/core" "lin-cms-go/pkg/log" + "os" ) func errorHandler(c *fiber.Ctx, err error) error { @@ -27,11 +28,17 @@ func errorHandler(c *fiber.Ctx, err error) error { } func initApp(c *conf.Config) *fiber.App { app := fiber.New(fiber.Config{ErrorHandler: errorHandler}) - app.Use(fiberzap.New(fiberzap.Config{ - Logger: log.Defaultlogger, - Fields: []string{"method", "url", "latency", "status", "reqbody", "body", "error"}, - })) - app.Use(recover.New(), cors.New()) + + l := log.NewLogger(os.Stderr) + w, _ := os.Create("./app.log") + l.WithWriter(w).Debug("debug", "ssss") + l.Error("err", "e") + app.Use(recover.New(), + logger.New(logger.Config{ + TimeFormat: "2006-01-02 15:04:05.000", Format: "[${time}] ${method} ${path} - ${status} ${latency} \n ${body} \n ${resBody} \n ${error}", Output: os.Stderr, + }), + cors.New()) + data.NewDataSource(&c.Data) //TODO clean source diff --git a/pkg/log/logger.go b/pkg/log/logger.go index b25bfa7..eb74fdd 100644 --- a/pkg/log/logger.go +++ b/pkg/log/logger.go @@ -1,20 +1,201 @@ package log import ( - "go.uber.org/zap" - "go.uber.org/zap/zapcore" + "encoding/json" + "fmt" + "io" + "log" + + "runtime" +) + +//var Logger io.Writer +//func init() { +// var err error +// Logger,err = os.Create("./app.log") +// log.Println(err) +//} + +type Level int8 + +type Fields map[string]interface{} + +const ( + LevelDebug Level = iota + LevelInfo + LevelWarn + LevelError + LevelPanic ) -var Defaultlogger *zap.Logger +func (l Level) String() string { + switch l { + case LevelDebug: + return "[DEBUG]" + case LevelInfo: + return "[INFO]" + case LevelWarn: + return "[WARN]" + case LevelError: + return "[ERROR]" + + case LevelPanic: + return "[PANIC]" + } + return "" +} + +type Logger struct { + newLogger *log.Logger + + fields Fields + callers []string +} + +func NewLogger(w io.Writer) *Logger { + l := log.New(w, "", log.LstdFlags) + return &Logger{newLogger: l} +} + +func (l *Logger) clone() *Logger { + nl := *l + return &nl +} + +func (l *Logger) WithFields(f Fields) *Logger { + ll := l.clone() + if ll.fields == nil { + ll.fields = make(Fields) + } + for k, v := range f { + ll.fields[k] = v + } + return ll +} +func (l *Logger) WithWriter(w io.Writer) *Logger { + ll := l.clone() + ll.newLogger = log.New(w, "", log.LstdFlags) + return ll +} + +func (l *Logger) WithCaller(skip int) *Logger { + ll := l.clone() + pc, file, line, ok := runtime.Caller(skip) + if ok { + f := runtime.FuncForPC(pc) + ll.callers = []string{fmt.Sprintf("%s: %d %s", file, line, f.Name())} + } + + return ll +} + +func (l *Logger) WithCallersFrames() *Logger { + maxCallerDepth := 25 + minCallerDepth := 3 + callers := []string{} + pcs := make([]uintptr, maxCallerDepth) + depth := runtime.Callers(minCallerDepth, pcs) + frames := runtime.CallersFrames(pcs[:depth]) + for frame, more := frames.Next(); more; frame, more = frames.Next() { + s := fmt.Sprintf(` %s: %d %s `, frame.File, frame.Line, frame.Function) + + callers = append(callers, s) + if !more { + break + } + } + ll := l.clone() + ll.callers = callers + return ll +} + +func (l *Logger) WithTrace() *Logger { + return l.WithFields(Fields{ + "trace_id": "X-Trace-ID", + "span_id": "X-Span-ID", + }) +} + +func (l *Logger) JSONFormat() map[string]interface{} { + data := make(Fields, len(l.fields)+4) + + if len(l.callers) > 0 { + data["callers"] = l.callers + } + + if len(l.fields) > 0 { + for k, v := range l.fields { + if _, ok := data[k]; !ok { + data[k] = v + } + } + } + + return data +} + +func (l *Logger) Output(level Level) { + body, _ := json.Marshal(l.JSONFormat()) + content := level.String() + string(body) + + switch level { + case LevelDebug, LevelInfo, LevelWarn, LevelError: + l.newLogger.Println(fmt.Sprint(content)) + case LevelPanic: + l.newLogger.Panic(content) + } +} + +func (l *Logger) Debug(key string, v ...interface{}) { + fields := make(Fields, 1) + fields[key] = v + l.WithFields(fields).Output(LevelDebug) -func init() { +} - encoderConfig := zap.NewProductionEncoderConfig() - encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.00") +func (l *Logger) Debugf(format string, v ...interface{}) { + fields := make(Fields, 1) + fields[format] = fmt.Sprintf(format, v...) + l.WithFields(fields).Output(LevelDebug) +} - config := zap.NewProductionConfig() - config.EncoderConfig = encoderConfig +//func (l *Logger) Info( prefix string,v ...interface{}) { +// l.Output(LevelInfo, ,fmt.Sprint(v...)) +//} +// +//func (l *Logger) Infof( format string, v ...interface{}) { +// l.Output(LevelInfo, fmt.Sprintf(format, v...)) +//} +// +//func (l *Logger) Warn( v ...interface{}) { +// l.Output(LevelWarn, fmt.Sprint(v...)) +//} +// +//func (l *Logger) Warnf( format string, v ...interface{}) { +// l.Output(LevelWarn, fmt.Sprintf(format, v...)) +//} +// +func (l *Logger) Error(key string, v ...interface{}) { + fields := make(Fields, 1) + fields[key] = v + l.WithFields(fields).WithCallersFrames().Output(LevelError) - Defaultlogger, _ = config.Build() +} +// +func (l *Logger) Errorf(format string, v ...interface{}) { + fields := make(Fields, 1) + fields[format] = fmt.Sprintf(format, v) + + l.WithFields(fields).WithCallersFrames().Output(LevelError) } + +// +// +//func (l *Logger) Panic( v ...interface{}) { +// l.Output(LevelPanic, fmt.Sprint(v...)) +//} +// +//func (l *Logger) Panicf( format string, v ...interface{}) { +// l.Output(LevelPanic, fmt.Sprintf(format, v...)) +//} From 59278448ca9a1b3e5ab0d36bdf118570bd8a101f Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Wed, 20 Oct 2021 09:55:42 +0800 Subject: [PATCH 09/44] chore:log --- go.mod | 1 + go.sum | 27 +----- internal/data/init.go | 7 +- main.go | 32 ++++--- pkg/log/logger.go | 205 +++--------------------------------------- 5 files changed, 41 insertions(+), 231 deletions(-) diff --git a/go.mod b/go.mod index 2e9d3a5..498ee5d 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/gofiber/fiber/v2 v2.20.2 github.com/gofiber/jwt/v3 v3.1.2 github.com/golang-jwt/jwt/v4 v4.1.0 + github.com/grestful/logs v1.0.7 github.com/stretchr/testify v1.7.0 golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a gopkg.in/yaml.v2 v2.4.0 diff --git a/go.sum b/go.sum index 026ef8d..25b5195 100644 --- a/go.sum +++ b/go.sum @@ -22,13 +22,9 @@ github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/andybalholm/brotli v1.0.2 h1:JKnhI/XQ75uFBTiuzXpzFrUriDPiZjlOSzh6wXogP0E= github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= -github.com/andybalholm/brotli v1.0.3 h1:fpcw+r1N1h0Poc1F/pHbW40cUm/lMEQslZtCkBQ0UnM= -github.com/andybalholm/brotli v1.0.3/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= -github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= @@ -73,8 +69,6 @@ github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GO github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae h1:L6V0ANsMIMdLgXly241UXhXNFWYgXbgjHupTAAURrV0= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gofiber/contrib/fiberzap v0.0.0-20211018071624-ed00d4b0c380 h1:ZLbgNlAX0MYYxI9Sv7V8Z9foTx9a/ZQYequUfhdJYyw= -github.com/gofiber/contrib/fiberzap v0.0.0-20211018071624-ed00d4b0c380/go.mod h1:P5ce3JdsGV4XP7QZUYNmR/vLG7N5A3JUMmpaqGklW60= github.com/gofiber/fiber/v2 v2.20.1 h1:p463gd/RI8YeYxP4WMGS+u1UtBS88yk8oLiPkEiDYx4= github.com/gofiber/fiber/v2 v2.20.1/go.mod h1:/LdZHMUXZvTTo7gU4+b1hclqCAdoQphNQ9bi9gutPyI= github.com/gofiber/fiber/v2 v2.20.2 h1:dqizbjO1pCmH6K+b+kBk7TCJK4rmgjJXvX8/MZDbK60= @@ -124,6 +118,8 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grestful/logs v1.0.7 h1:uthHjp6p/ThXsouBvTy8pPyk2QFkJCZ72weIEavAJUg= +github.com/grestful/logs v1.0.7/go.mod h1:ybCulnhAgkMj5o32d09rMqeqeGEsqQiilOjZSoNlVZE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= @@ -161,8 +157,6 @@ github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQL github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.13.4 h1:0zhec2I8zGnjWcKyLl6i3gPqKANCCn5e9xmviEEeX6s= github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= -github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= @@ -247,12 +241,12 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07 h1:d/VUIMNTk65Xz69htmRPNfjypq2uNRqVsymcXQu6kKk= +github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07/go.mod h1:FbXpUxsx5in7z/OrWFDdhYetOy3/VGIJsVHN9G7RUPA= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.29.0 h1:F5GKpytwFk5OhCuRh6H+d4vZAcEeNAwPTdwQnm6IERY= github.com/valyala/fasthttp v1.29.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= -github.com/valyala/fasthttp v1.31.0 h1:lrauRLII19afgCs2fnWRJ4M5IkV0lo2FqA61uGkNBfE= -github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= @@ -263,18 +257,10 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.1.11-0.20210813005559-691160354723 h1:sHOAIxRGBp443oHZIPB+HsUGaksVCXVQENPxwTfQdH4= -go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= -go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -354,8 +340,6 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211013075003-97ac67df715c h1:taxlMj0D/1sOAuv/CbSD+MMDof2vbyPTqz5FNYKpXt8= -golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -439,13 +423,10 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/internal/data/init.go b/internal/data/init.go index 920de8a..53e388e 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -1,6 +1,7 @@ package data import ( + "github.com/grestful/logs" "lin-cms-go/internal/conf" "lin-cms-go/internal/data/ent" "sync" @@ -28,8 +29,10 @@ func NewDBClient(conf *conf.Data) (db *ent.Client) { var err error once.Do(func() { - opt := ent.Debug() - db, err = ent.Open(conf.Database.Driver, conf.Database.Source, opt) + + db, err = ent.Open(conf.Database.Driver, conf.Database.Source, ent.Debug(), ent.Log(func(i ...interface{}) { + logs.Debug("sql", i, 111111111111) + })) if err != nil { panic(err) } diff --git a/main.go b/main.go index 63dc288..a98ba06 100644 --- a/main.go +++ b/main.go @@ -5,13 +5,13 @@ import ( "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/recover" + log "github.com/grestful/logs" "gopkg.in/yaml.v2" "io/ioutil" "lin-cms-go/internal/conf" "lin-cms-go/internal/data" "lin-cms-go/internal/server" "lin-cms-go/pkg/core" - "lin-cms-go/pkg/log" "os" ) @@ -26,19 +26,27 @@ func errorHandler(c *fiber.Ctx, err error) error { return core.ServerError(c, err) } -func initApp(c *conf.Config) *fiber.App { - app := fiber.New(fiber.Config{ErrorHandler: errorHandler}) +func initLog(c *conf.Config) { + log.SetFile(log.FileConfig{ - l := log.NewLogger(os.Stderr) - w, _ := os.Create("./app.log") - l.WithWriter(w).Debug("debug", "ssss") - l.Error("err", "e") - app.Use(recover.New(), - logger.New(logger.Config{ - TimeFormat: "2006-01-02 15:04:05.000", Format: "[${time}] ${method} ${path} - ${status} ${latency} \n ${body} \n ${resBody} \n ${error}", Output: os.Stderr, - }), - cors.New()) + Category: "file", + Level: "DEBUG", + Filename: c.Log.Path + "/d.log", + Rotate: true, + Daily: true, + }) + writer := log.GetLogger("file") + log.SetDefaultLog(writer) +} +func initApp(c *conf.Config) *fiber.App { + app := fiber.New(fiber.Config{ErrorHandler: errorHandler}) + w, _ := os.Create(c.Log.Path + "/access.log") + app.Use(logger.New(logger.Config{ + TimeFormat: "2006-01-02 15:04:05.000", Format: "[${time}] ${method} ${path} - ${status} ${latency} \n ${body} \n ${resBody} \n ${error}", Output: w, + })) + app.Use(recover.New(), cors.New()) + initLog(c) data.NewDataSource(&c.Data) //TODO clean source diff --git a/pkg/log/logger.go b/pkg/log/logger.go index eb74fdd..94bc7b0 100644 --- a/pkg/log/logger.go +++ b/pkg/log/logger.go @@ -1,201 +1,18 @@ package log -import ( - "encoding/json" - "fmt" - "io" - "log" +import log "github.com/grestful/logs" - "runtime" -) +var SqlLogger log.Logger -//var Logger io.Writer -//func init() { -// var err error -// Logger,err = os.Create("./app.log") -// log.Println(err) -//} +func SetSqlLogger(path string) { + log.SetFile(log.FileConfig{ -type Level int8 - -type Fields map[string]interface{} - -const ( - LevelDebug Level = iota - LevelInfo - LevelWarn - LevelError - LevelPanic -) - -func (l Level) String() string { - switch l { - case LevelDebug: - return "[DEBUG]" - case LevelInfo: - return "[INFO]" - case LevelWarn: - return "[WARN]" - case LevelError: - return "[ERROR]" - - case LevelPanic: - return "[PANIC]" - } - return "" -} - -type Logger struct { - newLogger *log.Logger - - fields Fields - callers []string -} - -func NewLogger(w io.Writer) *Logger { - l := log.New(w, "", log.LstdFlags) - return &Logger{newLogger: l} -} - -func (l *Logger) clone() *Logger { - nl := *l - return &nl -} - -func (l *Logger) WithFields(f Fields) *Logger { - ll := l.clone() - if ll.fields == nil { - ll.fields = make(Fields) - } - for k, v := range f { - ll.fields[k] = v - } - return ll -} -func (l *Logger) WithWriter(w io.Writer) *Logger { - ll := l.clone() - ll.newLogger = log.New(w, "", log.LstdFlags) - return ll -} - -func (l *Logger) WithCaller(skip int) *Logger { - ll := l.clone() - pc, file, line, ok := runtime.Caller(skip) - if ok { - f := runtime.FuncForPC(pc) - ll.callers = []string{fmt.Sprintf("%s: %d %s", file, line, f.Name())} - } - - return ll -} - -func (l *Logger) WithCallersFrames() *Logger { - maxCallerDepth := 25 - minCallerDepth := 3 - callers := []string{} - pcs := make([]uintptr, maxCallerDepth) - depth := runtime.Callers(minCallerDepth, pcs) - frames := runtime.CallersFrames(pcs[:depth]) - for frame, more := frames.Next(); more; frame, more = frames.Next() { - s := fmt.Sprintf(` %s: %d %s `, frame.File, frame.Line, frame.Function) - - callers = append(callers, s) - if !more { - break - } - } - ll := l.clone() - ll.callers = callers - return ll -} - -func (l *Logger) WithTrace() *Logger { - return l.WithFields(Fields{ - "trace_id": "X-Trace-ID", - "span_id": "X-Span-ID", + Category: "file", + Level: "DEBUG", + Filename: path + "/sql.log", + Rotate: true, + Daily: true, }) + writer := log.GetLogger("file") + log.SetDefaultLog(writer) } - -func (l *Logger) JSONFormat() map[string]interface{} { - data := make(Fields, len(l.fields)+4) - - if len(l.callers) > 0 { - data["callers"] = l.callers - } - - if len(l.fields) > 0 { - for k, v := range l.fields { - if _, ok := data[k]; !ok { - data[k] = v - } - } - } - - return data -} - -func (l *Logger) Output(level Level) { - body, _ := json.Marshal(l.JSONFormat()) - content := level.String() + string(body) - - switch level { - case LevelDebug, LevelInfo, LevelWarn, LevelError: - l.newLogger.Println(fmt.Sprint(content)) - case LevelPanic: - l.newLogger.Panic(content) - } -} - -func (l *Logger) Debug(key string, v ...interface{}) { - fields := make(Fields, 1) - fields[key] = v - l.WithFields(fields).Output(LevelDebug) - -} - -func (l *Logger) Debugf(format string, v ...interface{}) { - fields := make(Fields, 1) - fields[format] = fmt.Sprintf(format, v...) - l.WithFields(fields).Output(LevelDebug) -} - -//func (l *Logger) Info( prefix string,v ...interface{}) { -// l.Output(LevelInfo, ,fmt.Sprint(v...)) -//} -// -//func (l *Logger) Infof( format string, v ...interface{}) { -// l.Output(LevelInfo, fmt.Sprintf(format, v...)) -//} -// -//func (l *Logger) Warn( v ...interface{}) { -// l.Output(LevelWarn, fmt.Sprint(v...)) -//} -// -//func (l *Logger) Warnf( format string, v ...interface{}) { -// l.Output(LevelWarn, fmt.Sprintf(format, v...)) -//} -// -func (l *Logger) Error(key string, v ...interface{}) { - fields := make(Fields, 1) - fields[key] = v - l.WithFields(fields).WithCallersFrames().Output(LevelError) - -} - -// -func (l *Logger) Errorf(format string, v ...interface{}) { - fields := make(Fields, 1) - fields[format] = fmt.Sprintf(format, v) - - l.WithFields(fields).WithCallersFrames().Output(LevelError) -} - -// -// -//func (l *Logger) Panic( v ...interface{}) { -// l.Output(LevelPanic, fmt.Sprint(v...)) -//} -// -//func (l *Logger) Panicf( format string, v ...interface{}) { -// l.Output(LevelPanic, fmt.Sprintf(format, v...)) -//} From 28109d4714625e222016f36a8697a095b630ccd0 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Wed, 20 Oct 2021 15:33:34 +0800 Subject: [PATCH 10/44] fix :sql --- internal/data/init.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/internal/data/init.go b/internal/data/init.go index 53e388e..98fb4de 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -1,7 +1,6 @@ package data import ( - "github.com/grestful/logs" "lin-cms-go/internal/conf" "lin-cms-go/internal/data/ent" "sync" @@ -30,9 +29,7 @@ func NewDBClient(conf *conf.Data) (db *ent.Client) { var err error once.Do(func() { - db, err = ent.Open(conf.Database.Driver, conf.Database.Source, ent.Debug(), ent.Log(func(i ...interface{}) { - logs.Debug("sql", i, 111111111111) - })) + db, err = ent.Open(conf.Database.Driver, conf.Database.Source, ent.Debug()) if err != nil { panic(err) } From 0f8c63d63389292f035fc4593da1e0dd2408c36b Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Wed, 20 Oct 2021 15:43:55 +0800 Subject: [PATCH 11/44] fix: create_time,update_time --- internal/data/ent/schema/lin_user_group.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/data/ent/schema/lin_user_group.go b/internal/data/ent/schema/lin_user_group.go index 0457e54..02011ec 100644 --- a/internal/data/ent/schema/lin_user_group.go +++ b/internal/data/ent/schema/lin_user_group.go @@ -16,10 +16,10 @@ type TimeMixin struct { func (TimeMixin) Fields() []ent.Field { return []ent.Field{ - field.Time("created_time"). + field.Time("create_time"). Immutable(). Default(time.Now), - field.Time("updated_time"). + field.Time("update_time"). Default(time.Now). UpdateDefault(time.Now), field.Time("delete_time"). From 89a8f9d97f52f2ec44d8c9cbf3aa94ff95139de8 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Wed, 20 Oct 2021 17:57:24 +0800 Subject: [PATCH 12/44] fear: page struct --- internal/data/book.go | 20 ++++++++++++++++++++ main.go | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/data/book.go b/internal/data/book.go index 9de75a6..0423c3c 100644 --- a/internal/data/book.go +++ b/internal/data/book.go @@ -4,6 +4,7 @@ import ( "context" "lin-cms-go/internal/data/ent" "lin-cms-go/internal/data/ent/book" + "lin-cms-go/pkg/core" ) func GetBookAll(ctx context.Context, offset int, size int) (model []*ent.Book, err error) { @@ -38,5 +39,24 @@ func DeleteBook(ctx context.Context, id int) (err error) { func GetBookCount(ctx context.Context) (count int, err error) { count, err = GetDB().Book.Query().Count(ctx) + + return +} + +type Paging struct { + Page int + Size int + Offset int +} + +func NewPaging(page, pageSize int) *Paging { + return &Paging{ + Page: page, + Size: pageSize, + Offset: core.GetPageOffset(page, pageSize), + } +} +func (p *Paging) ListBook(ctx context.Context) (model []*ent.Book, err error) { + model, err = GetDB().Book.Query().Limit(p.Size).Offset(p.Offset).All(ctx) return } diff --git a/main.go b/main.go index a98ba06..3dfef2c 100644 --- a/main.go +++ b/main.go @@ -16,7 +16,7 @@ import ( ) func errorHandler(c *fiber.Ctx, err error) error { - // Status code defaults to 500 + // response err handle if e, ok := err.(core.IError); ok { if e.Err == nil { return e.HttpError(c) From b78f8dd8d55cb0c2ad8e1811866fc7d920ce1e52 Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Thu, 21 Oct 2021 16:16:09 +0800 Subject: [PATCH 13/44] feat(biz,data/log):log --- api/book.go | 3 --- internal/biz/book.go | 5 ++--- internal/data/book.go | 20 -------------------- internal/data/init.go | 15 +++++++++++++++ pkg/utils/time.go | 5 +++++ 5 files changed, 22 insertions(+), 26 deletions(-) diff --git a/api/book.go b/api/book.go index 317a8c9..88d77ee 100644 --- a/api/book.go +++ b/api/book.go @@ -17,14 +17,11 @@ func GetBooks(c *fiber.Ctx) error { if err != nil { return err } - total, err := biz.GetBookTotal(c.Context()) if err != nil { return err } - core.SetPage(c, data, total) - return nil } diff --git a/internal/biz/book.go b/internal/biz/book.go index 30808ac..d6da46c 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -10,12 +10,11 @@ import ( ) func GetBookAll(ctx context.Context, page int, size int) (res interface{}, err error) { - offset := core.GetPageOffset(page, size) - bookModel, err := data.GetBookAll(ctx, offset, size) + books, err := data.NewPaging(page, size).ListBook(ctx) if err != nil { return } - res = bookModel + res = books return } diff --git a/internal/data/book.go b/internal/data/book.go index 0423c3c..7ace93b 100644 --- a/internal/data/book.go +++ b/internal/data/book.go @@ -4,14 +4,8 @@ import ( "context" "lin-cms-go/internal/data/ent" "lin-cms-go/internal/data/ent/book" - "lin-cms-go/pkg/core" ) -func GetBookAll(ctx context.Context, offset int, size int) (model []*ent.Book, err error) { - model, err = GetDB().Book.Query().Limit(size).Offset(offset).All(ctx) - return -} - func GetBookById(ctx context.Context, id int) (model *ent.Book, err error) { model, err = GetDB().Book.Query().Where(book.ID(id)).First(ctx) return @@ -39,23 +33,9 @@ func DeleteBook(ctx context.Context, id int) (err error) { func GetBookCount(ctx context.Context) (count int, err error) { count, err = GetDB().Book.Query().Count(ctx) - return } -type Paging struct { - Page int - Size int - Offset int -} - -func NewPaging(page, pageSize int) *Paging { - return &Paging{ - Page: page, - Size: pageSize, - Offset: core.GetPageOffset(page, pageSize), - } -} func (p *Paging) ListBook(ctx context.Context) (model []*ent.Book, err error) { model, err = GetDB().Book.Query().Limit(p.Size).Offset(p.Offset).All(ctx) return diff --git a/internal/data/init.go b/internal/data/init.go index 98fb4de..e30fb97 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -3,6 +3,7 @@ package data import ( "lin-cms-go/internal/conf" "lin-cms-go/internal/data/ent" + "lin-cms-go/pkg/core" "sync" _ "github.com/go-sql-driver/mysql" @@ -11,6 +12,20 @@ import ( var ds *DataSource var once sync.Once +type Paging struct { + Page int + Size int + Offset int +} + +func NewPaging(page, pageSize int) *Paging { + return &Paging{ + Page: page, + Size: pageSize, + Offset: core.GetPageOffset(page, pageSize), + } +} + // DataSource . type DataSource struct { Db map[string]*ent.Client diff --git a/pkg/utils/time.go b/pkg/utils/time.go index f1c9db9..6690f5a 100644 --- a/pkg/utils/time.go +++ b/pkg/utils/time.go @@ -25,3 +25,8 @@ func GetCurrentMilliUnix() int64 { func GetCurrentNanoUnix() int64 { return time.Now().UnixNano() } + +func String2time(dateString string) time.Time { + date, _ := time.Parse("2006-01-02 15:04:05", dateString) + return date +} From 2561e8be83c050676e5696bd2b6a34c330c0e413 Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Thu, 21 Oct 2021 16:20:13 +0800 Subject: [PATCH 14/44] feat(biz,data/log):log --- api/log.go | 17 ++++----- internal/biz/log.go | 42 +++++++++++++++++++---- internal/data/ent/schema/lin_log.go | 6 ++++ internal/data/log.go | 53 +++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 17 deletions(-) diff --git a/api/log.go b/api/log.go index 59322e3..44b4652 100644 --- a/api/log.go +++ b/api/log.go @@ -2,29 +2,26 @@ package api import ( "github.com/gofiber/fiber/v2" - "lin-cms-go/internal/request" "lin-cms-go/internal/biz" + "lin-cms-go/internal/request" "lin-cms-go/pkg/core" ) func Upload(c *fiber.Ctx) error { - return core.SuccessResp(c) } func GetLogs(c *fiber.Ctx) error { var req request.GetLogs if err := core.ParseRequest(c, &req); err != nil { - return err } - - data, err := biz.GetLogs(req) + data, total, err := biz.GetLogs(c.Context(), req) if err != nil { return err } - return core.SetData(c, data) - + return core.SetPage(c, data, total) } + func SearchLogs(c *fiber.Ctx) error { var req request.SearchLogs if err := core.ParseRequest(c, &req); err != nil { @@ -43,11 +40,9 @@ func GetLogUsers(c *fiber.Ctx) error { if err := core.ParseRequest(c, &req); err != nil { return err } - - data, err := biz.GetLogUsers(req) + data, total, err := biz.GetLogUsers(c.Context(), req) if err != nil { return err } - - return core.SetData(c, data) + return core.SetPage(c, data, total) } diff --git a/internal/biz/log.go b/internal/biz/log.go index 8731b47..03837b9 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -1,17 +1,47 @@ package biz -import "lin-cms-go/internal/request" +import ( + "context" + "lin-cms-go/internal/data" + "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/request" + "lin-cms-go/pkg/utils" +) -func Upload() { +func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total int, err error) { + var logs []*ent.LinLog + paging := data.NewPaging(req.Page, req.Count) + if req.Name == "" && req.Start == "" && req.End == "" { + logs, err = paging.GetLogAll(ctx) + total = data.GetLosTotal(ctx) + } + if req.Name != "" && req.Start == "" && req.End == "" { + logs, err = paging.FindLogsByUsername(ctx, req.Name) + total = data.GetLogsByUsernameTotal(ctx, req.Name) + } + if req.Name != "" && req.Start != "" && req.End != "" { + start := utils.String2time(req.Start) + end := utils.String2time(req.End) + logs, err = paging.FindLogsByUsernameAndRange(ctx, req.Name, start, end) + total = data.GetLogsByUsernameAndRangeTotal(ctx, req.Name, start, end) + } + if err != nil { + return + } + res = logs return } -func GetLogs(req request.GetLogs) (res map[string]interface{}, err error) { - return -} + func SearchLogs(req request.SearchLogs) (res map[string]interface{}, err error) { return } -func GetLogUsers(req request.GetLogUsers) (res map[string]interface{}, err error) { +func GetLogUsers(ctx context.Context, req request.GetLogUsers) (res interface{}, total int, err error) { + paging := data.NewPaging(req.Page, req.Count) + res, err = paging.GetLogUsers(ctx) + if err != nil { + return + } + total, _ = data.GetLogUsersTotal(ctx) return } diff --git a/internal/data/ent/schema/lin_log.go b/internal/data/ent/schema/lin_log.go index d918903..ba85067 100644 --- a/internal/data/ent/schema/lin_log.go +++ b/internal/data/ent/schema/lin_log.go @@ -16,6 +16,12 @@ func (LinLog) Annotations() []schema.Annotation { entsql.Annotation{Table: "lin_log"}, } } + +func (LinLog) Mixin() []ent.Mixin { + return []ent.Mixin{ + TimeMixin{}, + } +} func (LinLog) Fields() []ent.Field { return []ent.Field{ field.String("message").Comment(""), diff --git a/internal/data/log.go b/internal/data/log.go index 0ad59c2..27a366f 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -1 +1,54 @@ package data + +import ( + "context" + "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/data/ent/linlog" + "time" +) + +func (p *Paging) FindLogsByUsernameAndRange(ctx context.Context, name string, start time.Time, end time.Time) (model []*ent.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( + linlog.CreateTimeGT(start), + linlog.CreateTimeLT(end), + )).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) GetLogAll(ctx context.Context) (model []*ent.LinLog, err error) { + model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) FindLogsByUsername(ctx context.Context, name string) (model []*ent.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) GetLogUsers(ctx context.Context) (model []string, err error) { + model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).Select(linlog.FieldUsername).GroupBy("username").Strings(ctx) + return +} + +func GetLogUsersTotal(ctx context.Context) (total int, err error) { + // TODO sql有问题 + model, err := GetDB().LinLog.Query().Select(linlog.FieldUsername).GroupBy("username").Strings(ctx) + GetDB().LinLog.Query().GroupBy("username") + total = len(model) + return +} + +func GetLosTotal(ctx context.Context) (total int) { + total, _ = GetDB().LinLog.Query().Count(ctx) + return +} + +func GetLogsByUsernameTotal(ctx context.Context, name string) (total int) { + total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Count(ctx) + return +} + +func GetLogsByUsernameAndRangeTotal(ctx context.Context, name string, start time.Time, end time.Time) (total int) { + total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.CreateTimeGT(start)).Where(linlog.CreateTimeLT(end)).Count(ctx) + return +} From 41bf9e3ea2e28b2e04f4c413f4388d1adb60d19c Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 21 Oct 2021 16:55:07 +0800 Subject: [PATCH 15/44] fix: page, request validate tag --- api/log.go | 13 ++++++------- internal/biz/log.go | 4 ++-- internal/data/log.go | 7 ++----- internal/request/admin.go | 14 +++++++------- internal/request/book.go | 4 ++-- internal/request/permission.go | 12 ++++++------ internal/server/routes.go | 6 +++--- pkg/core/page.go | 4 ++-- pkg/core/response.go | 10 ++++++++++ 9 files changed, 40 insertions(+), 34 deletions(-) diff --git a/api/log.go b/api/log.go index 44b4652..d5c1187 100644 --- a/api/log.go +++ b/api/log.go @@ -12,9 +12,10 @@ func Upload(c *fiber.Ctx) error { } func GetLogs(c *fiber.Ctx) error { var req request.GetLogs - if err := core.ParseRequest(c, &req); err != nil { + if err := core.ParseQuery(c, &req); err != nil { return err } + data, total, err := biz.GetLogs(c.Context(), req) if err != nil { return err @@ -24,7 +25,7 @@ func GetLogs(c *fiber.Ctx) error { func SearchLogs(c *fiber.Ctx) error { var req request.SearchLogs - if err := core.ParseRequest(c, &req); err != nil { + if err := core.ParseQuery(c, &req); err != nil { return err } @@ -36,11 +37,9 @@ func SearchLogs(c *fiber.Ctx) error { return core.SetData(c, data) } func GetLogUsers(c *fiber.Ctx) error { - var req request.GetLogUsers - if err := core.ParseRequest(c, &req); err != nil { - return err - } - data, total, err := biz.GetLogUsers(c.Context(), req) + page := core.GetPage(c) + size := core.GetSize(c) + data, total, err := biz.GetLogUsers(c.Context(), page, size) if err != nil { return err } diff --git a/internal/biz/log.go b/internal/biz/log.go index 03837b9..c121aaa 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -36,8 +36,8 @@ func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total i func SearchLogs(req request.SearchLogs) (res map[string]interface{}, err error) { return } -func GetLogUsers(ctx context.Context, req request.GetLogUsers) (res interface{}, total int, err error) { - paging := data.NewPaging(req.Page, req.Count) +func GetLogUsers(ctx context.Context, page, size int) (res interface{}, total int, err error) { + paging := data.NewPaging(page, size) res, err = paging.GetLogUsers(ctx) if err != nil { return diff --git a/internal/data/log.go b/internal/data/log.go index 27a366f..8e0c31d 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -26,15 +26,12 @@ func (p *Paging) FindLogsByUsername(ctx context.Context, name string) (model []* } func (p *Paging) GetLogUsers(ctx context.Context) (model []string, err error) { - model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).Select(linlog.FieldUsername).GroupBy("username").Strings(ctx) + model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).GroupBy(linlog.FieldUsername).Strings(ctx) return } func GetLogUsersTotal(ctx context.Context) (total int, err error) { - // TODO sql有问题 - model, err := GetDB().LinLog.Query().Select(linlog.FieldUsername).GroupBy("username").Strings(ctx) - GetDB().LinLog.Query().GroupBy("username") - total = len(model) + total, err = GetDB().LinLog.Query().Select(linlog.FieldUsername).Count(ctx) return } diff --git a/internal/request/admin.go b/internal/request/admin.go index 8c6bcbc..042ddf5 100644 --- a/internal/request/admin.go +++ b/internal/request/admin.go @@ -1,21 +1,21 @@ package request type GetUsers struct { - GroupId int `json:"group_id" binding:"required"` + GroupId int `json:"group_id" validate:"required"` Pages } type Pages struct { - Count int `json:"count" binding:"required" comment:"数量"` - Page int `json:"page" binding:"required" comment:"页码"` + Count int `json:"count" validate:"required" comment:"数量"` + Page int `json:"page" validate:"required" comment:"页码"` } type ChangeUserPassword struct { Id int `json:"uid"` - NewPassword string `json:"new_password" binding:"required" comment:"新密码"` - ConfirmPassword string `json:"confirm_password" binding:"required,eqcsfield=NewPassword" comment:"确认密码"` + NewPassword string `json:"new_password" validate:"required" comment:"新密码"` + ConfirmPassword string `json:"confirm_password" validate:"required,eqcsfield=NewPassword" comment:"确认密码"` } type UpdateUser struct { - Id int `json:"id" binding:"required"` - GroupIds []int `json:"group_ids" binding:"required"` + Id int `json:"id" validate:"required"` + GroupIds []int `json:"group_ids" validate:"required"` } type CreateGroup struct { Name string `json:"name"` diff --git a/internal/request/book.go b/internal/request/book.go index b226d5f..4b4a3c8 100644 --- a/internal/request/book.go +++ b/internal/request/book.go @@ -14,6 +14,6 @@ type CreateBook struct { Image string `json:"image" validate:"required" comment:"书籍封面图"` } type GetBooks struct { - Size int `json:"size" binding:"required" comment:"数量"` - Page int `json:"page" binding:"required" comment:"页码"` + Size int `json:"size" validate:"required" comment:"数量"` + Page int `json:"page" validate:"required" comment:"页码"` } diff --git a/internal/request/permission.go b/internal/request/permission.go index 3764805..3ae0f0d 100644 --- a/internal/request/permission.go +++ b/internal/request/permission.go @@ -1,15 +1,15 @@ package request type DispatchPermissions struct { - GroupId int `json:"group_id" binding:"required"` - PermissionIds []int `json:"permission_ids" binding:"required"` + GroupId int `json:"group_id" validate:"required"` + PermissionIds []int `json:"permission_ids" validate:"required"` } type DispatchPermission struct { - GroupId int `json:"group_id" binding:"required"` - PermissionId int `json:"permission_id" binding:"required"` + GroupId int `json:"group_id" validate:"required"` + PermissionId int `json:"permission_id" validate:"required"` } type RemovePermissions struct { - GroupId int `json:"group_id" binding:"required"` - PermissionIds []int `json:"permission_ids" binding:"required"` + GroupId int `json:"group_id" validate:"required"` + PermissionIds []int `json:"permission_ids" validate:"required"` } diff --git a/internal/server/routes.go b/internal/server/routes.go index 1239df6..7969240 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -15,9 +15,9 @@ func InitRoute(app *fiber.App) { cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) cms.Post("/user/register", api.Register) - cms.Use(jwtware.New(jwtware.Config{ - SigningKey: []byte("secret"), - })) + //cms.Use(jwtware.New(jwtware.Config{ + // SigningKey: []byte("secret"), + //})) v1.Use(jwtware.New(jwtware.Config{ SigningKey: []byte("secret"), diff --git a/pkg/core/page.go b/pkg/core/page.go index 940c23c..dd35ae2 100644 --- a/pkg/core/page.go +++ b/pkg/core/page.go @@ -26,9 +26,9 @@ func GetPage(c *fiber.Ctx) int { } func GetSize(c *fiber.Ctx) int { - pageSize, _ := utils.StringToInt(c.Query("size")) + pageSize, _ := utils.StringToInt(c.Query("count")) if pageSize <= 0 { - return 20 + return 10 } return pageSize diff --git a/pkg/core/response.go b/pkg/core/response.go index cf2f9f9..920620e 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -48,6 +48,16 @@ func ValidateRequest(obj interface{}) error { } return nil } +func ParseQuery(c *fiber.Ctx, request interface{}) (err error) { + err = c.QueryParser(request) + + if err != nil { + return err + } + + err = ValidateRequest(request) + return +} func ParseRequest(c *fiber.Ctx, request interface{}) (err error) { err = c.BodyParser(request) From d476aa18ae53660ad5a5cb5b90c55abe5db35e13 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 21 Oct 2021 17:59:41 +0800 Subject: [PATCH 16/44] fix: changemypassword getmyinfomation --- api/user.go | 26 +++++++++++--------------- internal/biz/user.go | 13 +++++-------- internal/data/user.go | 9 +++++++-- internal/server/routes.go | 8 ++++---- 4 files changed, 27 insertions(+), 29 deletions(-) diff --git a/api/user.go b/api/user.go index eae3943..766e212 100644 --- a/api/user.go +++ b/api/user.go @@ -62,7 +62,7 @@ func ChangeMyPassword(c *fiber.Ctx) error { } user := biz.LocalUser(c) - err := biz.ChangeMyPassword(c.Context(), req, user.ID) + err := biz.ChangeMyPassword(c.Context(), req, user.Username) if err != nil { return err @@ -79,23 +79,19 @@ func GetMyPermissions(c *fiber.Ctx) error { return err } - core.SetData(c, data) - return nil + return core.SetData(c, data) + } func GetMyInfomation(c *fiber.Ctx) error { - //uid, err := uid(c) - //if err != nil { - // - // return err - //} - //data, err := biz.GetMyInfomation(uid) - //if err != nil { - // - // return err - //} - //return core.SetData(c, data) - return nil + user := biz.LocalUser(c) + data, err := biz.GetMyInfomation(c.Context(), user.ID) + if err != nil { + + return err + } + return core.SetData(c, data) + } //TODO 对cms意义并不大,先不实现 diff --git a/internal/biz/user.go b/internal/biz/user.go index d843293..a598bc7 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -79,9 +79,8 @@ func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { err = data.UpdateLinUser(ctx, uid, req.Avatar, req.Nickname, req.Email) return } -func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, uid int) (err error) { - var username string - //todo jwt username +func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, username string) (err error) { + userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, username) if err != nil { return err @@ -125,14 +124,12 @@ func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, //data["permissions"] = permissions return } -func GetMyInfomation(ctx context.Context, uid int) (res map[string]interface{}, err error) { - _, err = data.GetLinUserById(ctx, uid) +func GetMyInfomation(ctx context.Context, uid int) (res interface{}, err error) { + model, err := data.GetLinUserById(ctx, uid) if ent.IsNotFound(err) { err = core.NewErrorCode(errcode.UserNotFound) return } - if err != nil { - return - } + res = model return } diff --git a/internal/data/user.go b/internal/data/user.go index 40935ee..22fbecd 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -7,10 +7,15 @@ import ( "lin-cms-go/internal/data/ent/linuseridentiy" ) -func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (po *ent.LinUserIdentiy, err error) { +func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (model *ent.LinUserIdentiy, err error) { - po, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.Identifier(identifier)).First(ctx) + model, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.Identifier(identifier)).First(ctx) + return +} + +func GetLinUserIdentityByUserId(ctx context.Context, userId int) (model *ent.LinUserIdentiy, err error) { + model, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.UserID(userId)).First(ctx) return } func CreateLinUser(ctx context.Context, username, password, email string, groupId int) (err error) { diff --git a/internal/server/routes.go b/internal/server/routes.go index 7969240..339ee20 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -2,7 +2,6 @@ package server import ( "github.com/gofiber/fiber/v2" - jwtware "github.com/gofiber/jwt/v3" "lin-cms-go/api" ) @@ -15,13 +14,14 @@ func InitRoute(app *fiber.App) { cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) cms.Post("/user/register", api.Register) + // FIXME 开发阶段先注释jwt //cms.Use(jwtware.New(jwtware.Config{ // SigningKey: []byte("secret"), //})) - v1.Use(jwtware.New(jwtware.Config{ - SigningKey: []byte("secret"), - })) + //v1.Use(jwtware.New(jwtware.Config{ + // SigningKey: []byte("secret"), + //})) { userRouter := cms.Group("/user") adminRouter := cms.Group("/admin") From 1dfe4be2c43a11c8d641a1e014d99c6e8612b92a Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 21 Oct 2021 22:11:22 +0800 Subject: [PATCH 17/44] feat: move ent model to model dir --- internal/biz/biz.go | 4 ++-- internal/biz/book.go | 18 +++++++++--------- internal/biz/log.go | 4 ++-- internal/biz/user.go | 17 +++++++++-------- internal/data/book.go | 10 +++++----- internal/data/ent/generate.go | 2 +- internal/data/init.go | 15 ++++++++------- internal/data/log.go | 11 ++++++----- internal/data/user.go | 12 ++++++------ 9 files changed, 48 insertions(+), 45 deletions(-) diff --git a/internal/biz/biz.go b/internal/biz/biz.go index e580a53..2c367bc 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -3,11 +3,11 @@ package biz import ( "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v4" - "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/data/model" "lin-cms-go/pkg/utils" ) -func LocalUser(c *fiber.Ctx) (user ent.LinUser) { +func LocalUser(c *fiber.Ctx) (user model.LinUser) { jwtToken := c.Locals("user").(*jwt.Token) claims := jwtToken.Claims.(jwt.MapClaims) bytes, _ := utils.JSONEncode(claims["user"]) diff --git a/internal/biz/book.go b/internal/biz/book.go index d6da46c..69be703 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -3,7 +3,7 @@ package biz import ( "context" "lin-cms-go/internal/data" - "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" "lin-cms-go/pkg/core" "lin-cms-go/pkg/errcode" @@ -25,7 +25,7 @@ func GetBookTotal(ctx context.Context) (total int, err error) { func UpdateBook(ctx context.Context, id int, req request.UpdateBook) (err error) { _, err = data.GetBookById(ctx, id) - if ent.IsNotFound(err) { + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.BookNotFound) return } @@ -37,11 +37,11 @@ func UpdateBook(ctx context.Context, id int, req request.UpdateBook) (err error) } func CreateBook(ctx context.Context, req request.CreateBook) (err error) { - model, err := data.GetBookByTitle(ctx, req.Title) - if ent.MaskNotFound(err) != nil { + book, err := data.GetBookByTitle(ctx, req.Title) + if model.MaskNotFound(err) != nil { return err } - if model != nil { + if book != nil { err = core.NewErrorCode(errcode.BookTitleRepetition) return } @@ -51,7 +51,7 @@ func CreateBook(ctx context.Context, req request.CreateBook) (err error) { func DeleteBook(ctx context.Context, id int) (err error) { _, err = data.GetBookById(ctx, id) - if ent.IsNotFound(err) { + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.BookNotFound) return } @@ -60,11 +60,11 @@ func DeleteBook(ctx context.Context, id int) (err error) { } func GetBook(ctx context.Context, id int) (res interface{}, err error) { - model, err := data.GetBookById(ctx, id) - if ent.IsNotFound(err) { + book, err := data.GetBookById(ctx, id) + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.BookNotFound) return } - res = model + res = book return } diff --git a/internal/biz/log.go b/internal/biz/log.go index c121aaa..aaf5c0e 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -3,13 +3,13 @@ package biz import ( "context" "lin-cms-go/internal/data" - "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" "lin-cms-go/pkg/utils" ) func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total int, err error) { - var logs []*ent.LinLog + var logs []*model.LinLog paging := data.NewPaging(req.Page, req.Count) if req.Name == "" && req.Start == "" && req.End == "" { diff --git a/internal/biz/user.go b/internal/biz/user.go index a598bc7..7fccc6b 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -4,7 +4,8 @@ import ( "context" "errors" "lin-cms-go/internal/data" - "lin-cms-go/internal/data/ent" + "lin-cms-go/internal/data/model" + "lin-cms-go/internal/request" "lin-cms-go/pkg/core" "lin-cms-go/pkg/errcode" @@ -20,7 +21,7 @@ func Login(ctx context.Context, username, password string) (res map[string]inter // 正确密码验证 userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, username) - if ent.IsNotFound(err) { + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.UserNotFound) return } @@ -51,7 +52,7 @@ func Login(ctx context.Context, username, password string) (res map[string]inter } func Register(ctx context.Context, req request.Register) (err error) { userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, req.Username) - if ent.MaskNotFound(err) != nil { + if model.MaskNotFound(err) != nil { return err } if userIdentityModel != nil && userIdentityModel.ID > 0 { @@ -69,7 +70,7 @@ func Register(ctx context.Context, req request.Register) (err error) { } func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { _, err = data.GetLinUserById(ctx, uid) - if ent.IsNotFound(err) { + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.UserNotFound) return } @@ -103,7 +104,7 @@ func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, usernam } func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, err error) { user, err := data.GetLinUserById(ctx, uid) - if ent.IsNotFound(err) { + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.UserNotFound) return } @@ -125,11 +126,11 @@ func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, return } func GetMyInfomation(ctx context.Context, uid int) (res interface{}, err error) { - model, err := data.GetLinUserById(ctx, uid) - if ent.IsNotFound(err) { + usermodel, err := data.GetLinUserById(ctx, uid) + if model.IsNotFound(err) { err = core.NewErrorCode(errcode.UserNotFound) return } - res = model + res = usermodel return } diff --git a/internal/data/book.go b/internal/data/book.go index 7ace93b..5e41533 100644 --- a/internal/data/book.go +++ b/internal/data/book.go @@ -2,16 +2,16 @@ package data import ( "context" - "lin-cms-go/internal/data/ent" - "lin-cms-go/internal/data/ent/book" + "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/book" ) -func GetBookById(ctx context.Context, id int) (model *ent.Book, err error) { +func GetBookById(ctx context.Context, id int) (model *model.Book, err error) { model, err = GetDB().Book.Query().Where(book.ID(id)).First(ctx) return } -func GetBookByTitle(ctx context.Context, title string) (model *ent.Book, err error) { +func GetBookByTitle(ctx context.Context, title string) (model *model.Book, err error) { model, err = GetDB().Book.Query().Where(book.Title(title)).First(ctx) return } @@ -36,7 +36,7 @@ func GetBookCount(ctx context.Context) (count int, err error) { return } -func (p *Paging) ListBook(ctx context.Context) (model []*ent.Book, err error) { +func (p *Paging) ListBook(ctx context.Context) (model []*model.Book, err error) { model, err = GetDB().Book.Query().Limit(p.Size).Offset(p.Offset).All(ctx) return } diff --git a/internal/data/ent/generate.go b/internal/data/ent/generate.go index bef3464..7ffc2a5 100644 --- a/internal/data/ent/generate.go +++ b/internal/data/ent/generate.go @@ -1,3 +1,3 @@ package ent -//go:generate go run -mod=mod entgo.io/ent/cmd/ent --template glob=./tmpl/*.tmpl generate ./schema +//go:generate go run -mod=mod entgo.io/ent/cmd/ent --template glob=./tmpl/*.tmpl --target ../model generate ./schema diff --git a/internal/data/init.go b/internal/data/init.go index e30fb97..3b0fa9e 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -2,7 +2,8 @@ package data import ( "lin-cms-go/internal/conf" - "lin-cms-go/internal/data/ent" + + "lin-cms-go/internal/data/model" "lin-cms-go/pkg/core" "sync" @@ -28,23 +29,23 @@ func NewPaging(page, pageSize int) *Paging { // DataSource . type DataSource struct { - Db map[string]*ent.Client + Db map[string]*model.Client } func NewDataSource(conf *conf.Data) { ds = &DataSource{ - Db: make(map[string]*ent.Client), + Db: make(map[string]*model.Client), } db := NewDBClient(conf) ds.Db["default"] = db } -func NewDBClient(conf *conf.Data) (db *ent.Client) { +func NewDBClient(conf *conf.Data) (db *model.Client) { var err error once.Do(func() { - db, err = ent.Open(conf.Database.Driver, conf.Database.Source, ent.Debug()) + db, err = model.Open(conf.Database.Driver, conf.Database.Source, model.Debug()) if err != nil { panic(err) } @@ -53,13 +54,13 @@ func NewDBClient(conf *conf.Data) (db *ent.Client) { return db } -func (d *DataSource) GetDb(name string) *ent.Client { +func (d *DataSource) GetDb(name string) *model.Client { if db, ok := d.Db[name]; ok { return db } panic(name + " db not exists") } -func GetDB() *ent.Client { +func GetDB() *model.Client { return ds.GetDb("default") } diff --git a/internal/data/log.go b/internal/data/log.go index 8e0c31d..1bad198 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -2,12 +2,13 @@ package data import ( "context" - "lin-cms-go/internal/data/ent" - "lin-cms-go/internal/data/ent/linlog" + + "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/linlog" "time" ) -func (p *Paging) FindLogsByUsernameAndRange(ctx context.Context, name string, start time.Time, end time.Time) (model []*ent.LinLog, err error) { +func (p *Paging) FindLogsByUsernameAndRange(ctx context.Context, name string, start time.Time, end time.Time) (model []*model.LinLog, err error) { model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( linlog.CreateTimeGT(start), linlog.CreateTimeLT(end), @@ -15,12 +16,12 @@ func (p *Paging) FindLogsByUsernameAndRange(ctx context.Context, name string, st return } -func (p *Paging) GetLogAll(ctx context.Context) (model []*ent.LinLog, err error) { +func (p *Paging) GetLogAll(ctx context.Context) (model []*model.LinLog, err error) { model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).All(ctx) return } -func (p *Paging) FindLogsByUsername(ctx context.Context, name string) (model []*ent.LinLog, err error) { +func (p *Paging) FindLogsByUsername(ctx context.Context, name string) (model []*model.LinLog, err error) { model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Limit(p.Size).Offset(p.Offset).All(ctx) return } diff --git a/internal/data/user.go b/internal/data/user.go index 22fbecd..b044c5f 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -2,18 +2,18 @@ package data import ( "context" - "lin-cms-go/internal/data/ent" - "lin-cms-go/internal/data/ent/linuser" - "lin-cms-go/internal/data/ent/linuseridentiy" + "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" ) -func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (model *ent.LinUserIdentiy, err error) { +func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (model *model.LinUserIdentiy, err error) { model, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.Identifier(identifier)).First(ctx) return } -func GetLinUserIdentityByUserId(ctx context.Context, userId int) (model *ent.LinUserIdentiy, err error) { +func GetLinUserIdentityByUserId(ctx context.Context, userId int) (model *model.LinUserIdentiy, err error) { model, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.UserID(userId)).First(ctx) return @@ -38,7 +38,7 @@ func CreateLinUser(ctx context.Context, username, password, email string, groupI return } -func GetLinUserById(ctx context.Context, uid int) (model *ent.LinUser, err error) { +func GetLinUserById(ctx context.Context, uid int) (model *model.LinUser, err error) { model, err = GetDB().LinUser.Query().Where(linuser.ID(uid)).First(ctx) return From d1b82b9cf372b01adfa0051e1e19c9c4a57c4457 Mon Sep 17 00:00:00 2001 From: wangxuancheng <1768177868@qq.com> Date: Thu, 21 Oct 2021 22:12:25 +0800 Subject: [PATCH 18/44] .gitignore --- internal/data/ent/.gitignore | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 internal/data/ent/.gitignore diff --git a/internal/data/ent/.gitignore b/internal/data/ent/.gitignore new file mode 100644 index 0000000..c1f813b --- /dev/null +++ b/internal/data/ent/.gitignore @@ -0,0 +1,3 @@ +*.go +!generate.go +!.gitignore \ No newline at end of file From 387ee5d8167d1355d15b9646d00eaa9454dd3f65 Mon Sep 17 00:00:00 2001 From: wangxuancheng <1768177868@qq.com> Date: Fri, 22 Oct 2021 01:07:26 +0800 Subject: [PATCH 19/44] Dockerfile --- Dockerfile | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9a529ae --- /dev/null +++ b/Dockerfile @@ -0,0 +1,32 @@ +FROM golang:alpine AS build + +# 设置环境变量 +ENV CGO_ENABLED 0 +ENV GOOS linux +ENV GOPROXY https://goproxy.cn,direct + +# 项目代码存放的目录 +WORKDIR /home/www/lin-cms-go + +ADD go.mod . +ADD go.sum . + +COPY . . + +# 编译成二进制可执行文件名 app +RUN go build -o app . + + +FROM alpine AS prod + +COPY --from=build /home/www/lin-cms-go/ . +COPY --from=build /home/www/lin-cms-go/configs/config.yaml ./configs/ + +# 端口 +EXPOSE 3000 + +CMD ["./app"] + + +# docker build -t lin-cms:v1 -f Dockerfile . +# docker run -it -p 8080:3000 lin-cms:v1 \ No newline at end of file From eb13016bde125607e36e373adf8e3e2feb7a4c67 Mon Sep 17 00:00:00 2001 From: wangxuancheng <1768177868@qq.com> Date: Fri, 22 Oct 2021 14:31:15 +0800 Subject: [PATCH 20/44] .dockerignore --- .dockerignore | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..79bc918 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +**/.git +**/.gitignore +**/.vscode +**/*.sql +**/*.log +README.md From cb10233ded3885fd74782e3e8f14d59c45f2fed5 Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Fri, 22 Oct 2021 15:24:14 +0800 Subject: [PATCH 21/44] feat:log --- api/log.go | 7 +--- internal/biz/log.go | 44 +++++++++++++++++++++- internal/data/log.go | 82 +++++++++++++++++++++++++++++++++++++++++ internal/request/log.go | 1 - 4 files changed, 127 insertions(+), 7 deletions(-) diff --git a/api/log.go b/api/log.go index d5c1187..60d8318 100644 --- a/api/log.go +++ b/api/log.go @@ -15,7 +15,6 @@ func GetLogs(c *fiber.Ctx) error { if err := core.ParseQuery(c, &req); err != nil { return err } - data, total, err := biz.GetLogs(c.Context(), req) if err != nil { return err @@ -28,13 +27,11 @@ func SearchLogs(c *fiber.Ctx) error { if err := core.ParseQuery(c, &req); err != nil { return err } - - data, err := biz.SearchLogs(req) + data, total, err := biz.SearchLogs(c.Context(), req) if err != nil { return err } - - return core.SetData(c, data) + return core.SetPage(c, data, total) } func GetLogUsers(c *fiber.Ctx) error { page := core.GetPage(c) diff --git a/internal/biz/log.go b/internal/biz/log.go index aaf5c0e..9ce1cad 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -6,6 +6,7 @@ import ( "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" "lin-cms-go/pkg/utils" + "time" ) func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total int, err error) { @@ -33,7 +34,48 @@ func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total i return } -func SearchLogs(req request.SearchLogs) (res map[string]interface{}, err error) { +func SearchLogs(ctx context.Context, req request.SearchLogs) (res interface{}, total int, err error) { + var logs []*model.LinLog + var start time.Time + var end time.Time + paging := data.NewPaging(req.Page, req.Count) + if req.Start != "" && req.End != "" { + start = utils.String2time(req.Start) + end = utils.String2time(req.End) + } + if req.Name != "" && req.Start != "" && req.End != "" && req.Keyword != "" { + logs, err = paging.FindLogsByUsernameAndRangeAndKeyword(ctx, req.Name, req.Keyword, start, end) + total = data.GetLogsByUsernameAndRangeAndKeywordTotal(ctx, req.Name, req.Keyword, start, end) + } + if req.Name == "" && req.Start == "" && req.End == "" && req.Keyword == "" { + logs, err = paging.GetLogAll(ctx) + total = data.GetLosTotal(ctx) + } + if req.Keyword != "" && req.Start != "" && req.End != "" && req.Name == "" { + logs, err = paging.FindLogsByRangeAndKeyword(ctx, req.Keyword, start, end) + total = data.GetLogsByRangeAndKeywordTotal(ctx, req.Keyword, start, end) + } + if req.Keyword != "" && req.Name != "" && req.Start == "" && req.End == "" { + logs, err = paging.FindLogsByUsernameAndKeyword(ctx, req.Name, req.Keyword) + total = data.GetLogsByUsernameAndKeywordTotal(ctx, req.Name, req.Keyword) + } + if req.Keyword != "" && req.Name == "" && req.Start == "" && req.End == "" { + logs, err = paging.FindLogsByKeyword(ctx, req.Keyword) + total = data.GetLogsByKeywordTotal(ctx, req.Keyword) + } + if req.Keyword == "" && req.Name == "" && req.Start != "" && req.End != "" { + logs, err = paging.FindLogsByRange(ctx, start, end) + total = data.GetLogsByRangeTotal(ctx, start, end) + } + if req.Keyword == "" && req.Name != "" && req.Start == "" && req.End == "" { + logs, err = paging.FindLogsByUsername(ctx, req.Name) + total = data.GetLogsByUsernameTotal(ctx, req.Name) + } + if req.Keyword == "" && req.Name != "" && req.Start != "" && req.End != "" { + logs, err = paging.FindLogsByUsernameAndRange(ctx, req.Name, start, end) + total = data.GetLogsByUsernameAndRangeTotal(ctx, req.Name, start, end) + } + res = logs return } func GetLogUsers(ctx context.Context, page, size int) (res interface{}, total int, err error) { diff --git a/internal/data/log.go b/internal/data/log.go index 1bad198..712106c 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -2,6 +2,7 @@ package data import ( "context" + "entgo.io/ent/dialect/sql" "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/linlog" @@ -26,6 +27,48 @@ func (p *Paging) FindLogsByUsername(ctx context.Context, name string) (model []* return } +func (p *Paging) FindLogsByRange(ctx context.Context, start time.Time, end time.Time) (model []*model.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(linlog.And( + linlog.CreateTimeGT(start), + linlog.CreateTimeLT(end), + )).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) FindLogsByUsernameAndRangeAndKeyword(ctx context.Context, name string, keyword string, start time.Time, end time.Time) (model []*model.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( + linlog.CreateTimeGT(start), + linlog.CreateTimeLT(end), + )).Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) FindLogsByKeyword(ctx context.Context, keyword string) (model []*model.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) FindLogsByUsernameAndKeyword(ctx context.Context, username string, keyword string) (model []*model.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(linlog.Username(username)).Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) FindLogsByRangeAndKeyword(ctx context.Context, keyword string, start time.Time, end time.Time) (model []*model.LinLog, err error) { + model, err = GetDB().LinLog.Query().Where(linlog.And( + linlog.CreateTimeGT(start), + linlog.CreateTimeLT(end), + )).Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + func (p *Paging) GetLogUsers(ctx context.Context) (model []string, err error) { model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).GroupBy(linlog.FieldUsername).Strings(ctx) return @@ -50,3 +93,42 @@ func GetLogsByUsernameAndRangeTotal(ctx context.Context, name string, start time total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.CreateTimeGT(start)).Where(linlog.CreateTimeLT(end)).Count(ctx) return } + +func GetLogsByRangeTotal(ctx context.Context, start time.Time, end time.Time) (total int) { + total, _ = GetDB().LinLog.Query().Where(linlog.CreateTimeGT(start)).Where(linlog.CreateTimeLT(end)).Count(ctx) + return +} + +func GetLogsByUsernameAndRangeAndKeywordTotal(ctx context.Context, name string, keyword string, start time.Time, end time.Time) (total int) { + total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( + linlog.CreateTimeGT(start), + linlog.CreateTimeLT(end), + )).Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Count(ctx) + return +} + +func GetLogsByKeywordTotal(ctx context.Context, keyword string) (total int) { + total, _ = GetDB().LinLog.Query().Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Count(ctx) + return +} + +func GetLogsByUsernameAndKeywordTotal(ctx context.Context, username string, keyword string) (total int) { + total, _ = GetDB().LinLog.Query().Where(linlog.Username(username)).Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Count(ctx) + return +} + +func GetLogsByRangeAndKeywordTotal(ctx context.Context, keyword string, start time.Time, end time.Time) (total int) { + total, _ = GetDB().LinLog.Query().Where(linlog.And( + linlog.CreateTimeGT(start), + linlog.CreateTimeLT(end), + )).Where(func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + }).Count(ctx) + return +} diff --git a/internal/request/log.go b/internal/request/log.go index f1ec7d8..d129d07 100644 --- a/internal/request/log.go +++ b/internal/request/log.go @@ -10,7 +10,6 @@ type GetLogs struct { type SearchLogs struct { Keyword string `json:"keyword"` GetLogs - Pages } type GetLogUsers struct { Pages From 98e18bd4e23b22aa167c98631bdb21108b89ba8e Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Fri, 22 Oct 2021 17:09:38 +0800 Subject: [PATCH 22/44] refactor: searchlogs --- .gitignore | 3 +- internal/biz/log.go | 76 +++++++++++++++++++++--------------- internal/data/ent/.gitignore | 3 -- internal/data/log.go | 16 +++++++- pkg/core/response.go | 5 +-- 5 files changed, 63 insertions(+), 40 deletions(-) delete mode 100644 internal/data/ent/.gitignore diff --git a/.gitignore b/.gitignore index 9fa46c9..f674dda 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,7 @@ /.idea /.vscode *.exe - - +*.log /tmp diff --git a/internal/biz/log.go b/internal/biz/log.go index 9ce1cad..9554c39 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -4,6 +4,8 @@ import ( "context" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" "lin-cms-go/internal/request" "lin-cms-go/pkg/utils" "time" @@ -39,42 +41,54 @@ func SearchLogs(ctx context.Context, req request.SearchLogs) (res interface{}, t var start time.Time var end time.Time paging := data.NewPaging(req.Page, req.Count) + + var query []predicate.LinLog + if req.Name != "" { + query = append(query, data.WithUsername(req.Name)) + } if req.Start != "" && req.End != "" { start = utils.String2time(req.Start) end = utils.String2time(req.End) + q := linlog.And(linlog.CreateTimeGT(start), linlog.CreateTimeLT(end)) + query = append(query, q) } - if req.Name != "" && req.Start != "" && req.End != "" && req.Keyword != "" { - logs, err = paging.FindLogsByUsernameAndRangeAndKeyword(ctx, req.Name, req.Keyword, start, end) - total = data.GetLogsByUsernameAndRangeAndKeywordTotal(ctx, req.Name, req.Keyword, start, end) - } - if req.Name == "" && req.Start == "" && req.End == "" && req.Keyword == "" { - logs, err = paging.GetLogAll(ctx) - total = data.GetLosTotal(ctx) - } - if req.Keyword != "" && req.Start != "" && req.End != "" && req.Name == "" { - logs, err = paging.FindLogsByRangeAndKeyword(ctx, req.Keyword, start, end) - total = data.GetLogsByRangeAndKeywordTotal(ctx, req.Keyword, start, end) - } - if req.Keyword != "" && req.Name != "" && req.Start == "" && req.End == "" { - logs, err = paging.FindLogsByUsernameAndKeyword(ctx, req.Name, req.Keyword) - total = data.GetLogsByUsernameAndKeywordTotal(ctx, req.Name, req.Keyword) - } - if req.Keyword != "" && req.Name == "" && req.Start == "" && req.End == "" { - logs, err = paging.FindLogsByKeyword(ctx, req.Keyword) - total = data.GetLogsByKeywordTotal(ctx, req.Keyword) - } - if req.Keyword == "" && req.Name == "" && req.Start != "" && req.End != "" { - logs, err = paging.FindLogsByRange(ctx, start, end) - total = data.GetLogsByRangeTotal(ctx, start, end) - } - if req.Keyword == "" && req.Name != "" && req.Start == "" && req.End == "" { - logs, err = paging.FindLogsByUsername(ctx, req.Name) - total = data.GetLogsByUsernameTotal(ctx, req.Name) - } - if req.Keyword == "" && req.Name != "" && req.Start != "" && req.End != "" { - logs, err = paging.FindLogsByUsernameAndRange(ctx, req.Name, start, end) - total = data.GetLogsByUsernameAndRangeTotal(ctx, req.Name, start, end) + if req.Keyword != "" { + query = append(query, data.WithKeyword(req.Name)) } + logs, err = paging.Search(ctx, query) + + //if req.Name != "" && req.Start != "" && req.End != "" && req.Keyword != "" { + // logs, err = paging.FindLogsByUsernameAndRangeAndKeyword(ctx, req.Name, req.Keyword, start, end) + // total = data.GetLogsByUsernameAndRangeAndKeywordTotal(ctx, req.Name, req.Keyword, start, end) + //} + //if req.Name == "" && req.Start == "" && req.End == "" && req.Keyword == "" { + // logs, err = paging.GetLogAll(ctx) + // total = data.GetLosTotal(ctx) + //} + //if req.Keyword != "" && req.Start != "" && req.End != "" && req.Name == "" { + // logs, err = paging.FindLogsByRangeAndKeyword(ctx, req.Keyword, start, end) + // total = data.GetLogsByRangeAndKeywordTotal(ctx, req.Keyword, start, end) + //} + //if req.Keyword != "" && req.Name != "" && req.Start == "" && req.End == "" { + // logs, err = paging.FindLogsByUsernameAndKeyword(ctx, req.Name, req.Keyword) + // total = data.GetLogsByUsernameAndKeywordTotal(ctx, req.Name, req.Keyword) + //} + //if req.Keyword != "" && req.Name == "" && req.Start == "" && req.End == "" { + // logs, err = paging.FindLogsByKeyword(ctx, req.Keyword) + // total = data.GetLogsByKeywordTotal(ctx, req.Keyword) + //} + //if req.Keyword == "" && req.Name == "" && req.Start != "" && req.End != "" { + // logs, err = paging.FindLogsByRange(ctx, start, end) + // total = data.GetLogsByRangeTotal(ctx, start, end) + //} + //if req.Keyword == "" && req.Name != "" && req.Start == "" && req.End == "" { + // logs, err = paging.FindLogsByUsername(ctx, req.Name) + // total = data.GetLogsByUsernameTotal(ctx, req.Name) + //} + //if req.Keyword == "" && req.Name != "" && req.Start != "" && req.End != "" { + // logs, err = paging.FindLogsByUsernameAndRange(ctx, req.Name, start, end) + // total = data.GetLogsByUsernameAndRangeTotal(ctx, req.Name, start, end) + //} res = logs return } diff --git a/internal/data/ent/.gitignore b/internal/data/ent/.gitignore deleted file mode 100644 index c1f813b..0000000 --- a/internal/data/ent/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.go -!generate.go -!.gitignore \ No newline at end of file diff --git a/internal/data/log.go b/internal/data/log.go index 712106c..4412fb5 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -3,6 +3,7 @@ package data import ( "context" "entgo.io/ent/dialect/sql" + "lin-cms-go/internal/data/model/predicate" "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/linlog" @@ -34,7 +35,20 @@ func (p *Paging) FindLogsByRange(ctx context.Context, start time.Time, end time. )).Limit(p.Size).Offset(p.Offset).All(ctx) return } - +func WithKeyword(keyword string) func(s *sql.Selector) { + return func(s *sql.Selector) { + s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) + } +} +func WithUsername(name string) func(s *sql.Selector) { + return func(s *sql.Selector) { + s.Where(sql.EQ(linlog.FieldUsername, name)) + } +} +func (p *Paging) Search(ctx context.Context, query []predicate.LinLog) (logs []*model.LinLog, err error) { + logs, err = GetDB().LinLog.Query().Where(query...).Limit(p.Size).Offset(p.Offset).All(ctx) + return +} func (p *Paging) FindLogsByUsernameAndRangeAndKeyword(ctx context.Context, name string, keyword string, start time.Time, end time.Time) (model []*model.LinLog, err error) { model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( linlog.CreateTimeGT(start), diff --git a/pkg/core/response.go b/pkg/core/response.go index 920620e..533d3ad 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -1,7 +1,6 @@ package core import ( - "errors" "fmt" "github.com/go-playground/validator/v10" "github.com/gofiber/fiber/v2" @@ -44,7 +43,7 @@ func ValidateRequest(obj interface{}) error { if err != nil { s := Translate(err.(validator.ValidationErrors)) - return errors.New(s) + return NewInvalidParamsError(s) } return nil } @@ -127,6 +126,6 @@ func ServerError(c *fiber.Ctx, err error) error { func (err *IError) HttpError(c *fiber.Ctx) error { return c.JSON(IError{ Code: err.Code, - Message: errcode.GetMsg(err.Code), + Message: err.Message, }) } From 23876f3e0e24b011493f3403c05a4c5487e6123b Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Mon, 25 Oct 2021 10:54:02 +0800 Subject: [PATCH 23/44] refactor:log --- api/log.go | 10 +++- internal/biz/log.go | 68 +++++++------------------- internal/data/log.go | 112 +------------------------------------------ 3 files changed, 27 insertions(+), 163 deletions(-) diff --git a/api/log.go b/api/log.go index 60d8318..03cd5c1 100644 --- a/api/log.go +++ b/api/log.go @@ -12,10 +12,12 @@ func Upload(c *fiber.Ctx) error { } func GetLogs(c *fiber.Ctx) error { var req request.GetLogs + page := core.GetPage(c) + size := core.GetSize(c) if err := core.ParseQuery(c, &req); err != nil { return err } - data, total, err := biz.GetLogs(c.Context(), req) + data, total, err := biz.GetLogs(c.Context(), req, page, size) if err != nil { return err } @@ -27,12 +29,16 @@ func SearchLogs(c *fiber.Ctx) error { if err := core.ParseQuery(c, &req); err != nil { return err } - data, total, err := biz.SearchLogs(c.Context(), req) + page := core.GetPage(c) + size := core.GetSize(c) + + data, total, err := biz.SearchLogs(c.Context(), req, page, size) if err != nil { return err } return core.SetPage(c, data, total) } + func GetLogUsers(c *fiber.Ctx) error { page := core.GetPage(c) size := core.GetSize(c) diff --git a/internal/biz/log.go b/internal/biz/log.go index 9554c39..eb28b18 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -11,24 +11,23 @@ import ( "time" ) -func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total int, err error) { +func GetLogs(ctx context.Context, req request.GetLogs, page int, size int) (res interface{}, total int, err error) { var logs []*model.LinLog - paging := data.NewPaging(req.Page, req.Count) - - if req.Name == "" && req.Start == "" && req.End == "" { - logs, err = paging.GetLogAll(ctx) - total = data.GetLosTotal(ctx) - } - if req.Name != "" && req.Start == "" && req.End == "" { - logs, err = paging.FindLogsByUsername(ctx, req.Name) - total = data.GetLogsByUsernameTotal(ctx, req.Name) + var start time.Time + var end time.Time + paging := data.NewPaging(page, size) + var query []predicate.LinLog + if req.Name != "" { + query = append(query, data.WithUsername(req.Name)) } - if req.Name != "" && req.Start != "" && req.End != "" { - start := utils.String2time(req.Start) - end := utils.String2time(req.End) - logs, err = paging.FindLogsByUsernameAndRange(ctx, req.Name, start, end) - total = data.GetLogsByUsernameAndRangeTotal(ctx, req.Name, start, end) + if req.Start != "" && req.End != "" { + start = utils.String2time(req.Start) + end = utils.String2time(req.End) + q := linlog.And(linlog.CreateTimeGT(start), linlog.CreateTimeLT(end)) + query = append(query, q) } + logs, err = paging.Search(ctx, query) + total = data.GetSearchTotal(ctx, query) if err != nil { return } @@ -36,12 +35,11 @@ func GetLogs(ctx context.Context, req request.GetLogs) (res interface{}, total i return } -func SearchLogs(ctx context.Context, req request.SearchLogs) (res interface{}, total int, err error) { +func SearchLogs(ctx context.Context, req request.SearchLogs, page int, size int) (res interface{}, total int, err error) { var logs []*model.LinLog var start time.Time var end time.Time - paging := data.NewPaging(req.Page, req.Count) - + paging := data.NewPaging(page, size) var query []predicate.LinLog if req.Name != "" { query = append(query, data.WithUsername(req.Name)) @@ -56,39 +54,7 @@ func SearchLogs(ctx context.Context, req request.SearchLogs) (res interface{}, t query = append(query, data.WithKeyword(req.Name)) } logs, err = paging.Search(ctx, query) - - //if req.Name != "" && req.Start != "" && req.End != "" && req.Keyword != "" { - // logs, err = paging.FindLogsByUsernameAndRangeAndKeyword(ctx, req.Name, req.Keyword, start, end) - // total = data.GetLogsByUsernameAndRangeAndKeywordTotal(ctx, req.Name, req.Keyword, start, end) - //} - //if req.Name == "" && req.Start == "" && req.End == "" && req.Keyword == "" { - // logs, err = paging.GetLogAll(ctx) - // total = data.GetLosTotal(ctx) - //} - //if req.Keyword != "" && req.Start != "" && req.End != "" && req.Name == "" { - // logs, err = paging.FindLogsByRangeAndKeyword(ctx, req.Keyword, start, end) - // total = data.GetLogsByRangeAndKeywordTotal(ctx, req.Keyword, start, end) - //} - //if req.Keyword != "" && req.Name != "" && req.Start == "" && req.End == "" { - // logs, err = paging.FindLogsByUsernameAndKeyword(ctx, req.Name, req.Keyword) - // total = data.GetLogsByUsernameAndKeywordTotal(ctx, req.Name, req.Keyword) - //} - //if req.Keyword != "" && req.Name == "" && req.Start == "" && req.End == "" { - // logs, err = paging.FindLogsByKeyword(ctx, req.Keyword) - // total = data.GetLogsByKeywordTotal(ctx, req.Keyword) - //} - //if req.Keyword == "" && req.Name == "" && req.Start != "" && req.End != "" { - // logs, err = paging.FindLogsByRange(ctx, start, end) - // total = data.GetLogsByRangeTotal(ctx, start, end) - //} - //if req.Keyword == "" && req.Name != "" && req.Start == "" && req.End == "" { - // logs, err = paging.FindLogsByUsername(ctx, req.Name) - // total = data.GetLogsByUsernameTotal(ctx, req.Name) - //} - //if req.Keyword == "" && req.Name != "" && req.Start != "" && req.End != "" { - // logs, err = paging.FindLogsByUsernameAndRange(ctx, req.Name, start, end) - // total = data.GetLogsByUsernameAndRangeTotal(ctx, req.Name, start, end) - //} + total = data.GetSearchTotal(ctx, query) res = logs return } diff --git a/internal/data/log.go b/internal/data/log.go index 4412fb5..112a21a 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -7,34 +7,8 @@ import ( "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/linlog" - "time" ) -func (p *Paging) FindLogsByUsernameAndRange(ctx context.Context, name string, start time.Time, end time.Time) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( - linlog.CreateTimeGT(start), - linlog.CreateTimeLT(end), - )).Limit(p.Size).Offset(p.Offset).All(ctx) - return -} - -func (p *Paging) GetLogAll(ctx context.Context) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Limit(p.Size).Offset(p.Offset).All(ctx) - return -} - -func (p *Paging) FindLogsByUsername(ctx context.Context, name string) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Limit(p.Size).Offset(p.Offset).All(ctx) - return -} - -func (p *Paging) FindLogsByRange(ctx context.Context, start time.Time, end time.Time) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(linlog.And( - linlog.CreateTimeGT(start), - linlog.CreateTimeLT(end), - )).Limit(p.Size).Offset(p.Offset).All(ctx) - return -} func WithKeyword(keyword string) func(s *sql.Selector) { return func(s *sql.Selector) { s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) @@ -49,37 +23,9 @@ func (p *Paging) Search(ctx context.Context, query []predicate.LinLog) (logs []* logs, err = GetDB().LinLog.Query().Where(query...).Limit(p.Size).Offset(p.Offset).All(ctx) return } -func (p *Paging) FindLogsByUsernameAndRangeAndKeyword(ctx context.Context, name string, keyword string, start time.Time, end time.Time) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( - linlog.CreateTimeGT(start), - linlog.CreateTimeLT(end), - )).Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Limit(p.Size).Offset(p.Offset).All(ctx) - return -} -func (p *Paging) FindLogsByKeyword(ctx context.Context, keyword string) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Limit(p.Size).Offset(p.Offset).All(ctx) - return -} - -func (p *Paging) FindLogsByUsernameAndKeyword(ctx context.Context, username string, keyword string) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(linlog.Username(username)).Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Limit(p.Size).Offset(p.Offset).All(ctx) - return -} - -func (p *Paging) FindLogsByRangeAndKeyword(ctx context.Context, keyword string, start time.Time, end time.Time) (model []*model.LinLog, err error) { - model, err = GetDB().LinLog.Query().Where(linlog.And( - linlog.CreateTimeGT(start), - linlog.CreateTimeLT(end), - )).Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Limit(p.Size).Offset(p.Offset).All(ctx) +func GetSearchTotal(ctx context.Context, query []predicate.LinLog) (total int) { + total, _ = GetDB().LinLog.Query().Where(query...).Count(ctx) return } @@ -92,57 +38,3 @@ func GetLogUsersTotal(ctx context.Context) (total int, err error) { total, err = GetDB().LinLog.Query().Select(linlog.FieldUsername).Count(ctx) return } - -func GetLosTotal(ctx context.Context) (total int) { - total, _ = GetDB().LinLog.Query().Count(ctx) - return -} - -func GetLogsByUsernameTotal(ctx context.Context, name string) (total int) { - total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Count(ctx) - return -} - -func GetLogsByUsernameAndRangeTotal(ctx context.Context, name string, start time.Time, end time.Time) (total int) { - total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.CreateTimeGT(start)).Where(linlog.CreateTimeLT(end)).Count(ctx) - return -} - -func GetLogsByRangeTotal(ctx context.Context, start time.Time, end time.Time) (total int) { - total, _ = GetDB().LinLog.Query().Where(linlog.CreateTimeGT(start)).Where(linlog.CreateTimeLT(end)).Count(ctx) - return -} - -func GetLogsByUsernameAndRangeAndKeywordTotal(ctx context.Context, name string, keyword string, start time.Time, end time.Time) (total int) { - total, _ = GetDB().LinLog.Query().Where(linlog.Username(name)).Where(linlog.And( - linlog.CreateTimeGT(start), - linlog.CreateTimeLT(end), - )).Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Count(ctx) - return -} - -func GetLogsByKeywordTotal(ctx context.Context, keyword string) (total int) { - total, _ = GetDB().LinLog.Query().Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Count(ctx) - return -} - -func GetLogsByUsernameAndKeywordTotal(ctx context.Context, username string, keyword string) (total int) { - total, _ = GetDB().LinLog.Query().Where(linlog.Username(username)).Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Count(ctx) - return -} - -func GetLogsByRangeAndKeywordTotal(ctx context.Context, keyword string, start time.Time, end time.Time) (total int) { - total, _ = GetDB().LinLog.Query().Where(linlog.And( - linlog.CreateTimeGT(start), - linlog.CreateTimeLT(end), - )).Where(func(s *sql.Selector) { - s.Where(sql.Like(linlog.FieldMessage, "%"+keyword+"%")) - }).Count(ctx) - return -} From d4097482d846778e81c1b08e1c216e509ee3a8d0 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Tue, 26 Oct 2021 17:14:59 +0800 Subject: [PATCH 24/44] docs, model --- README.md | 149 +- internal/data/model/book.go | 129 + internal/data/model/book/book.go | 39 + internal/data/model/book/where.go | 596 ++ internal/data/model/book_create.go | 271 + internal/data/model/book_delete.go | 111 + internal/data/model/book_query.go | 960 ++++ internal/data/model/book_update.go | 342 ++ internal/data/model/client.go | 972 ++++ internal/data/model/config.go | 66 + internal/data/model/context.go | 33 + internal/data/model/ent.go | 273 + internal/data/model/enttest/enttest.go | 77 + internal/data/model/hook/hook.go | 294 + internal/data/model/linfile.go | 151 + internal/data/model/linfile/linfile.go | 45 + internal/data/model/linfile/where.go | 762 +++ internal/data/model/linfile_create.go | 305 ++ internal/data/model/linfile_delete.go | 111 + internal/data/model/linfile_query.go | 960 ++++ internal/data/model/linfile_update.go | 450 ++ internal/data/model/lingroup.go | 164 + internal/data/model/lingroup/lingroup.go | 59 + internal/data/model/lingroup/where.go | 500 ++ internal/data/model/lingroup_create.go | 324 ++ internal/data/model/lingroup_delete.go | 111 + internal/data/model/lingroup_query.go | 1170 ++++ internal/data/model/lingroup_update.go | 706 +++ internal/data/model/lingrouppermission.go | 109 + .../lingrouppermission/lingrouppermission.go | 33 + .../data/model/lingrouppermission/where.go | 290 + .../data/model/lingrouppermission_create.go | 237 + .../data/model/lingrouppermission_delete.go | 111 + .../data/model/lingrouppermission_query.go | 960 ++++ .../data/model/lingrouppermission_update.go | 346 ++ internal/data/model/linlog.go | 192 + internal/data/model/linlog/linlog.go | 72 + internal/data/model/linlog/where.go | 1130 ++++ internal/data/model/linlog_create.go | 416 ++ internal/data/model/linlog_delete.go | 111 + internal/data/model/linlog_query.go | 960 ++++ internal/data/model/linlog_update.go | 563 ++ internal/data/model/linpermission.go | 148 + .../data/model/linpermission/linpermission.go | 49 + internal/data/model/linpermission/where.go | 472 ++ internal/data/model/linpermission_create.go | 289 + internal/data/model/linpermission_delete.go | 111 + internal/data/model/linpermission_query.go | 1068 ++++ internal/data/model/linpermission_update.go | 525 ++ internal/data/model/linuser.go | 208 + internal/data/model/linuser/linuser.go | 87 + internal/data/model/linuser/where.go | 903 ++++ internal/data/model/linuser_create.go | 447 ++ internal/data/model/linuser_delete.go | 111 + internal/data/model/linuser_query.go | 1134 ++++ internal/data/model/linuser_update.go | 807 +++ internal/data/model/linuseridentiy.go | 140 + .../model/linuseridentiy/linuseridentiy.go | 50 + internal/data/model/linuseridentiy/where.go | 561 ++ internal/data/model/linuseridentiy_create.go | 271 + internal/data/model/linuseridentiy_delete.go | 111 + internal/data/model/linuseridentiy_query.go | 965 ++++ internal/data/model/linuseridentiy_update.go | 370 ++ internal/data/model/migrate/migrate.go | 72 + internal/data/model/migrate/schema.go | 235 + internal/data/model/mutation.go | 4810 +++++++++++++++++ internal/data/model/predicate/predicate.go | 31 + internal/data/model/runtime.go | 58 + internal/data/model/runtime/runtime.go | 10 + internal/data/model/tx.go | 231 + test/log_test.go | 27 + 71 files changed, 29953 insertions(+), 8 deletions(-) create mode 100644 internal/data/model/book.go create mode 100644 internal/data/model/book/book.go create mode 100644 internal/data/model/book/where.go create mode 100644 internal/data/model/book_create.go create mode 100644 internal/data/model/book_delete.go create mode 100644 internal/data/model/book_query.go create mode 100644 internal/data/model/book_update.go create mode 100644 internal/data/model/client.go create mode 100644 internal/data/model/config.go create mode 100644 internal/data/model/context.go create mode 100644 internal/data/model/ent.go create mode 100644 internal/data/model/enttest/enttest.go create mode 100644 internal/data/model/hook/hook.go create mode 100644 internal/data/model/linfile.go create mode 100644 internal/data/model/linfile/linfile.go create mode 100644 internal/data/model/linfile/where.go create mode 100644 internal/data/model/linfile_create.go create mode 100644 internal/data/model/linfile_delete.go create mode 100644 internal/data/model/linfile_query.go create mode 100644 internal/data/model/linfile_update.go create mode 100644 internal/data/model/lingroup.go create mode 100644 internal/data/model/lingroup/lingroup.go create mode 100644 internal/data/model/lingroup/where.go create mode 100644 internal/data/model/lingroup_create.go create mode 100644 internal/data/model/lingroup_delete.go create mode 100644 internal/data/model/lingroup_query.go create mode 100644 internal/data/model/lingroup_update.go create mode 100644 internal/data/model/lingrouppermission.go create mode 100644 internal/data/model/lingrouppermission/lingrouppermission.go create mode 100644 internal/data/model/lingrouppermission/where.go create mode 100644 internal/data/model/lingrouppermission_create.go create mode 100644 internal/data/model/lingrouppermission_delete.go create mode 100644 internal/data/model/lingrouppermission_query.go create mode 100644 internal/data/model/lingrouppermission_update.go create mode 100644 internal/data/model/linlog.go create mode 100644 internal/data/model/linlog/linlog.go create mode 100644 internal/data/model/linlog/where.go create mode 100644 internal/data/model/linlog_create.go create mode 100644 internal/data/model/linlog_delete.go create mode 100644 internal/data/model/linlog_query.go create mode 100644 internal/data/model/linlog_update.go create mode 100644 internal/data/model/linpermission.go create mode 100644 internal/data/model/linpermission/linpermission.go create mode 100644 internal/data/model/linpermission/where.go create mode 100644 internal/data/model/linpermission_create.go create mode 100644 internal/data/model/linpermission_delete.go create mode 100644 internal/data/model/linpermission_query.go create mode 100644 internal/data/model/linpermission_update.go create mode 100644 internal/data/model/linuser.go create mode 100644 internal/data/model/linuser/linuser.go create mode 100644 internal/data/model/linuser/where.go create mode 100644 internal/data/model/linuser_create.go create mode 100644 internal/data/model/linuser_delete.go create mode 100644 internal/data/model/linuser_query.go create mode 100644 internal/data/model/linuser_update.go create mode 100644 internal/data/model/linuseridentiy.go create mode 100644 internal/data/model/linuseridentiy/linuseridentiy.go create mode 100644 internal/data/model/linuseridentiy/where.go create mode 100644 internal/data/model/linuseridentiy_create.go create mode 100644 internal/data/model/linuseridentiy_delete.go create mode 100644 internal/data/model/linuseridentiy_query.go create mode 100644 internal/data/model/linuseridentiy_update.go create mode 100644 internal/data/model/migrate/migrate.go create mode 100644 internal/data/model/migrate/schema.go create mode 100644 internal/data/model/mutation.go create mode 100644 internal/data/model/predicate/predicate.go create mode 100644 internal/data/model/runtime.go create mode 100644 internal/data/model/runtime/runtime.go create mode 100644 internal/data/model/tx.go create mode 100644 test/log_test.go diff --git a/README.md b/README.md index c9355bc..8ef3769 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,148 @@ -# lin-cms-go -## 框架选型 -fiber ent -### 生成ent对象 +

+ + +
+ lin-cms-go +

+ +

+ php version + fiber version + lisence +

+ +# 简介 + +## 预防针 + +* 本项目非官方团队出品,仅出于学习、研究目的丰富下官方项目的语言支持 +* 本项目采取后跟进官方团队功能的形式,即官方团队出什么功能,这边就跟进开发什么功能,开发者不必担心前端适配问题。 +* 在上一点的基础上,我们会尝试加入一些自己的想法并实现。 +* 局限于本人水平,有些地方还需重构,已经纳入了计划中,当然也会有我没考虑到的,希望有更多人参与进来一起完善。 + +## 专栏教程 (todo) + +* [《lin cms go&vue 教程》](https://github.com/xushuhui/lin-cms-go) 专栏教程连载更新中,通过实战开源前后端分离 cms——lin cms 全家桶(lin-cms-vue & lin-cms-go)为一个前端应用实现内容管理系统。一套教程入门上手 vue、fiber 两大框架,自用、工作、私单一次打通。 + +* 读者反馈:[《lin cms php&vue 教程》读者反馈贴](https://github.com/xushuhui/lin-cms-go/issues/47) + +## 线上文档地址(完善中) + +[https://github.com/xushuhui/lin-cms-go](https://github.com/xushuhui/lin-cms-go/) + +## 线上 demo + +可直接参考官方团队的线上 demo:[http://face.cms.talelin.com/](http://face.cms.talelin.com/),用户名:super,密码:123456 + +## 什么是 lin cms? + +> lin-cms 是林间有风团队经过大量项目实践所提炼出的一套**内容管理系统框架**。lin-cms 可以有效的帮助开发者提高 cms 的开发效率。 + +本项目是基于 fiber 5.1 的 lin cms 后端实现。 + +官方团队产品了解请访问 [talelin](https://github.com/talelin) + +## lin cms 的特点 + +lin cms 的构筑思想是有其自身特点的。下面我们阐述一些 lin 的主要特点。 + +**lin cms 是一个前后端分离的 cms 解决方案** + +这意味着,lin 既提供后台的支撑,也有一套对应的前端系统,当然双端分离的好处不仅仅在于此,我们会在后续提供 nodejs 和 php 版本的 lin。如果你心仪 lin,却又因为技术栈的原因无法即可使用,没关系,我们会在后续提供更多的语言版本。为什么 lin 要选择前后端分离的单页面架构呢? + +首先,传统的网站开发更多的是采用服务端渲染的方式,需用使用一种模板语言在服务端完成页面渲染:比如 jinja2、jade 等。 服务端渲染的好处在于可以比较好的支持 seo,但作为内部使用的 cms 管理系统,seo 并不重要。 + +但一个不可忽视的事实是,服务器渲染的页面到底是由前端开发者来完成,还是由服务器开发者来完成?其实都不太合适。现在已经没有多少前端开发者是了解这些服务端模板语言的,而服务器开发者本身是不太擅长开发页面的。那还是分开吧,前端用最熟悉的 vue 写 js 和 css,而服务器只关注自己的 api 即可。 + +其次,单页面应用程序的体验本身就要好于传统网站。 + +更多关于 lin cms 的介绍请访问 [lin cms 线上文档](http://doc.cms.talelin.com/) + +**框架本身已内置了 cms 常用的功能** + +lin 已经内置了 cms 中最为常见的需求:用户管理、权限管理、日志系统等。开发者只需要集中精力开发自己的 cms 业务即可 + +## lin cms go 的特点 + +在当前项目的版本`(0.0.1)`中,特点更多来自于`fiber`框架本身带来的特点。通过充分利用框架的特性,实现高效的后端使用、开发,也就是说,只要你熟悉`fiber`框架,那么对于理解使用和二次开发本项目是没有难度的,即便对于框架的某些功能存在疑问也完全可以通过 fiber 官方的开发手册找到答案。当然我们更欢迎你通过 [issues](https://github.com/xushuhui/lin-cms-go/issues) 来向我们提问:) + +在下一个版本中`(>0.0.1)`, 我们会在框架的基础上融入一些自己的东西来增强或者优化框架的使用、开发体验。 + +## 所需基础 + +由于 lin 采用的是前后端分离的架构,所以你至少需要熟悉 go 和 vue。 + +lin 的服务端框架是基于 fiber2.20 的,所以如果你比较熟悉 fiber 的开发模式,那将可以更好的使用本项目。但如果你并不熟悉 fiber,我们认为也没有太大的关系,因为框架本身已经提供了一套完整的开发机制,你只需要在框架下用 go 来编写自己的业务代码即可。照葫芦画瓢应该就是这种感觉。 + +但前端不同,前端还是需要开发者比较熟悉 vue 的。但我想以 vue 在国内的普及程度,绝大多数的开发者是没有问题的。这也正是我们选择 vue 作为前端框架的原因。如果你喜欢 react or angular,那么加入我们,为 lin 开发一个对应的版本吧。 + +# 快速开始 + +## server 端必备环境 + +* 安装 mysql(version: 5.7+) + +* 安装 go 环境 (version: 1.14+) + +## 获取工程项目 + +```bash +git clone https://github.com/xushuhui/lin-cms-go.git +``` + +> 执行完毕后会生成 lin-cms-go 目录 + +## 安装依赖包 + +```bash +go mod tidy + ``` -go generate ./internal/data/ent/ + +## 数据库配置 + +lin 需要你自己在 mysql 中新建一个数据库,名字由你自己决定。例如,新建一个名为` lin-cms `的数据库。接着,我们需要在工程中进行一项简单的配置。使用编辑器打开 lin 工程根目录下`/configs/config.yaml`,找到如下配置项: + +```yaml +data: + datasource: + source: 用户名:密码@tcp(服务器地址)/数据库名?charset=utf8mb4&parseTime=True ``` -lin-cms-go 不断更新。let's go +**请务必根据自己的实际情况修改此配置项** + +## 导入数据 -## lin-cms 接口文档 -https://doc.cms.talelin.com/api/ +接下来使用你本机上任意一款数据库可视化工具,为已经创建好的`lin-cms`数据库运行 lin-cms-go 根目录下的`schema.sql`文件,这个 SQL 脚本文件将为为你生成一些基础的数据库表和数据。 + +## 运行 + +如果前面的过程一切顺利,项目所需的准备工作就已经全部完成,这时候你就可以试着让工程运行起来了。在工程的根目录打开命令行,输入: + +```bash +go build -o //启动 Web 服务器 +``` + +启动成功后会看到如下提示: + +```bash + Fiber v2.20.2 +http://127.0.0.1:3000/ + +``` + +打开浏览器,访问``http://127.0.0.1:3000``,你会看到一个欢迎界面,至此,lin-cms-go 部署完毕,可搭配 [lin-cms-vue](https://github.com/TaleLin/lin-cms-vue) 使用了。 + +## 更新日志 + +[查看日志](http://github.com/xushuhui/lin-cms-go//) + +## 常见问题 + +[查看常见问题](http://github.com/xushuhui/lin-cms-go/) + +## 讨论交流 ### 微信公众号 + ![扫码关注](https://tvax4.sinaimg.cn/large/a616b9a4gy1grl9d1rdpvj2076076wey.jpg) diff --git a/internal/data/model/book.go b/internal/data/model/book.go new file mode 100644 index 0000000..7714ba0 --- /dev/null +++ b/internal/data/model/book.go @@ -0,0 +1,129 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/book" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// Book is the model entity for the Book schema. +type Book struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // Author holds the value of the "author" field. + Author string `json:"author,omitempty"` + // Summary holds the value of the "summary" field. + Summary string `json:"summary,omitempty"` + // Image holds the value of the "image" field. + Image string `json:"image,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Book) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case book.FieldID: + values[i] = new(sql.NullInt64) + case book.FieldTitle, book.FieldAuthor, book.FieldSummary, book.FieldImage: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Book", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Book fields. +func (b *Book) assignValues(columns []string, values []interface{}) 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 book.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + b.ID = int(value.Int64) + case book.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + b.Title = value.String + } + case book.FieldAuthor: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field author", values[i]) + } else if value.Valid { + b.Author = value.String + } + case book.FieldSummary: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field summary", values[i]) + } else if value.Valid { + b.Summary = value.String + } + case book.FieldImage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field image", values[i]) + } else if value.Valid { + b.Image = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this Book. +// Note that you need to call Book.Unwrap() before calling this method if this Book +// was returned from a transaction, and the transaction was committed or rolled back. +func (b *Book) Update() *BookUpdateOne { + return (&BookClient{config: b.config}).UpdateOne(b) +} + +// Unwrap unwraps the Book 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 (b *Book) Unwrap() *Book { + tx, ok := b.config.driver.(*txDriver) + if !ok { + panic("model: Book is not a transactional entity") + } + b.config.driver = tx.drv + return b +} + +// String implements the fmt.Stringer. +func (b *Book) String() string { + var builder strings.Builder + builder.WriteString("Book(") + builder.WriteString(fmt.Sprintf("id=%v", b.ID)) + builder.WriteString(", title=") + builder.WriteString(b.Title) + builder.WriteString(", author=") + builder.WriteString(b.Author) + builder.WriteString(", summary=") + builder.WriteString(b.Summary) + builder.WriteString(", image=") + builder.WriteString(b.Image) + builder.WriteByte(')') + return builder.String() +} + +// Books is a parsable slice of Book. +type Books []*Book + +func (b Books) config(cfg config) { + for _i := range b { + b[_i].config = cfg + } +} diff --git a/internal/data/model/book/book.go b/internal/data/model/book/book.go new file mode 100644 index 0000000..040d81c --- /dev/null +++ b/internal/data/model/book/book.go @@ -0,0 +1,39 @@ +// Code generated by entc, DO NOT EDIT. + +package book + +const ( + // Label holds the string label denoting the book type in the database. + Label = "book" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldAuthor holds the string denoting the author field in the database. + FieldAuthor = "author" + // FieldSummary holds the string denoting the summary field in the database. + FieldSummary = "summary" + // FieldImage holds the string denoting the image field in the database. + FieldImage = "image" + // Table holds the table name of the book in the database. + Table = "book" +) + +// Columns holds all SQL columns for book fields. +var Columns = []string{ + FieldID, + FieldTitle, + FieldAuthor, + FieldSummary, + FieldImage, +} + +// 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 +} diff --git a/internal/data/model/book/where.go b/internal/data/model/book/where.go new file mode 100644 index 0000000..7812ed5 --- /dev/null +++ b/internal/data/model/book/where.go @@ -0,0 +1,596 @@ +// Code generated by entc, DO NOT EDIT. + +package book + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTitle), v)) + }) +} + +// Author applies equality check predicate on the "author" field. It's identical to AuthorEQ. +func Author(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAuthor), v)) + }) +} + +// Summary applies equality check predicate on the "summary" field. It's identical to SummaryEQ. +func Summary(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSummary), v)) + }) +} + +// Image applies equality check predicate on the "image" field. It's identical to ImageEQ. +func Image(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldImage), v)) + }) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTitle), v)) + }) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldTitle), v)) + }) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldTitle), v...)) + }) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldTitle), v...)) + }) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldTitle), v)) + }) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldTitle), v)) + }) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldTitle), v)) + }) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldTitle), v)) + }) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldTitle), v)) + }) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldTitle), v)) + }) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldTitle), v)) + }) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldTitle), v)) + }) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldTitle), v)) + }) +} + +// AuthorEQ applies the EQ predicate on the "author" field. +func AuthorEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAuthor), v)) + }) +} + +// AuthorNEQ applies the NEQ predicate on the "author" field. +func AuthorNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAuthor), v)) + }) +} + +// AuthorIn applies the In predicate on the "author" field. +func AuthorIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAuthor), v...)) + }) +} + +// AuthorNotIn applies the NotIn predicate on the "author" field. +func AuthorNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAuthor), v...)) + }) +} + +// AuthorGT applies the GT predicate on the "author" field. +func AuthorGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAuthor), v)) + }) +} + +// AuthorGTE applies the GTE predicate on the "author" field. +func AuthorGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAuthor), v)) + }) +} + +// AuthorLT applies the LT predicate on the "author" field. +func AuthorLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAuthor), v)) + }) +} + +// AuthorLTE applies the LTE predicate on the "author" field. +func AuthorLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAuthor), v)) + }) +} + +// AuthorContains applies the Contains predicate on the "author" field. +func AuthorContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldAuthor), v)) + }) +} + +// AuthorHasPrefix applies the HasPrefix predicate on the "author" field. +func AuthorHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldAuthor), v)) + }) +} + +// AuthorHasSuffix applies the HasSuffix predicate on the "author" field. +func AuthorHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldAuthor), v)) + }) +} + +// AuthorEqualFold applies the EqualFold predicate on the "author" field. +func AuthorEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldAuthor), v)) + }) +} + +// AuthorContainsFold applies the ContainsFold predicate on the "author" field. +func AuthorContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldAuthor), v)) + }) +} + +// SummaryEQ applies the EQ predicate on the "summary" field. +func SummaryEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSummary), v)) + }) +} + +// SummaryNEQ applies the NEQ predicate on the "summary" field. +func SummaryNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldSummary), v)) + }) +} + +// SummaryIn applies the In predicate on the "summary" field. +func SummaryIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldSummary), v...)) + }) +} + +// SummaryNotIn applies the NotIn predicate on the "summary" field. +func SummaryNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldSummary), v...)) + }) +} + +// SummaryGT applies the GT predicate on the "summary" field. +func SummaryGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldSummary), v)) + }) +} + +// SummaryGTE applies the GTE predicate on the "summary" field. +func SummaryGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldSummary), v)) + }) +} + +// SummaryLT applies the LT predicate on the "summary" field. +func SummaryLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldSummary), v)) + }) +} + +// SummaryLTE applies the LTE predicate on the "summary" field. +func SummaryLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldSummary), v)) + }) +} + +// SummaryContains applies the Contains predicate on the "summary" field. +func SummaryContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldSummary), v)) + }) +} + +// SummaryHasPrefix applies the HasPrefix predicate on the "summary" field. +func SummaryHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldSummary), v)) + }) +} + +// SummaryHasSuffix applies the HasSuffix predicate on the "summary" field. +func SummaryHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldSummary), v)) + }) +} + +// SummaryEqualFold applies the EqualFold predicate on the "summary" field. +func SummaryEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldSummary), v)) + }) +} + +// SummaryContainsFold applies the ContainsFold predicate on the "summary" field. +func SummaryContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldSummary), v)) + }) +} + +// ImageEQ applies the EQ predicate on the "image" field. +func ImageEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldImage), v)) + }) +} + +// ImageNEQ applies the NEQ predicate on the "image" field. +func ImageNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldImage), v)) + }) +} + +// ImageIn applies the In predicate on the "image" field. +func ImageIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldImage), v...)) + }) +} + +// ImageNotIn applies the NotIn predicate on the "image" field. +func ImageNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldImage), v...)) + }) +} + +// ImageGT applies the GT predicate on the "image" field. +func ImageGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldImage), v)) + }) +} + +// ImageGTE applies the GTE predicate on the "image" field. +func ImageGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldImage), v)) + }) +} + +// ImageLT applies the LT predicate on the "image" field. +func ImageLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldImage), v)) + }) +} + +// ImageLTE applies the LTE predicate on the "image" field. +func ImageLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldImage), v)) + }) +} + +// ImageContains applies the Contains predicate on the "image" field. +func ImageContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldImage), v)) + }) +} + +// ImageHasPrefix applies the HasPrefix predicate on the "image" field. +func ImageHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldImage), v)) + }) +} + +// ImageHasSuffix applies the HasSuffix predicate on the "image" field. +func ImageHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldImage), v)) + }) +} + +// ImageEqualFold applies the EqualFold predicate on the "image" field. +func ImageEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldImage), v)) + }) +} + +// ImageContainsFold applies the ContainsFold predicate on the "image" field. +func ImageContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldImage), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Book) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Book) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Book) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/book_create.go b/internal/data/model/book_create.go new file mode 100644 index 0000000..ba2bd4a --- /dev/null +++ b/internal/data/model/book_create.go @@ -0,0 +1,271 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookCreate is the builder for creating a Book entity. +type BookCreate struct { + config + mutation *BookMutation + hooks []Hook +} + +// SetTitle sets the "title" field. +func (bc *BookCreate) SetTitle(s string) *BookCreate { + bc.mutation.SetTitle(s) + return bc +} + +// SetAuthor sets the "author" field. +func (bc *BookCreate) SetAuthor(s string) *BookCreate { + bc.mutation.SetAuthor(s) + return bc +} + +// SetSummary sets the "summary" field. +func (bc *BookCreate) SetSummary(s string) *BookCreate { + bc.mutation.SetSummary(s) + return bc +} + +// SetImage sets the "image" field. +func (bc *BookCreate) SetImage(s string) *BookCreate { + bc.mutation.SetImage(s) + return bc +} + +// Mutation returns the BookMutation object of the builder. +func (bc *BookCreate) Mutation() *BookMutation { + return bc.mutation +} + +// Save creates the Book in the database. +func (bc *BookCreate) Save(ctx context.Context) (*Book, error) { + var ( + err error + node *Book + ) + if len(bc.hooks) == 0 { + if err = bc.check(); err != nil { + return nil, err + } + node, err = bc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = bc.check(); err != nil { + return nil, err + } + bc.mutation = mutation + if node, err = bc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(bc.hooks) - 1; i >= 0; i-- { + if bc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = bc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (bc *BookCreate) SaveX(ctx context.Context) *Book { + v, err := bc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bc *BookCreate) Exec(ctx context.Context) error { + _, err := bc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bc *BookCreate) ExecX(ctx context.Context) { + if err := bc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (bc *BookCreate) check() error { + if _, ok := bc.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`model: missing required field "title"`)} + } + if _, ok := bc.mutation.Author(); !ok { + return &ValidationError{Name: "author", err: errors.New(`model: missing required field "author"`)} + } + if _, ok := bc.mutation.Summary(); !ok { + return &ValidationError{Name: "summary", err: errors.New(`model: missing required field "summary"`)} + } + if _, ok := bc.mutation.Image(); !ok { + return &ValidationError{Name: "image", err: errors.New(`model: missing required field "image"`)} + } + return nil +} + +func (bc *BookCreate) sqlSave(ctx context.Context) (*Book, error) { + _node, _spec := bc.createSpec() + if err := sqlgraph.CreateNode(ctx, bc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (bc *BookCreate) createSpec() (*Book, *sqlgraph.CreateSpec) { + var ( + _node = &Book{config: bc.config} + _spec = &sqlgraph.CreateSpec{ + Table: book.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + } + ) + if value, ok := bc.mutation.Title(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldTitle, + }) + _node.Title = value + } + if value, ok := bc.mutation.Author(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldAuthor, + }) + _node.Author = value + } + if value, ok := bc.mutation.Summary(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldSummary, + }) + _node.Summary = value + } + if value, ok := bc.mutation.Image(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldImage, + }) + _node.Image = value + } + return _node, _spec +} + +// BookCreateBulk is the builder for creating many Book entities in bulk. +type BookCreateBulk struct { + config + builders []*BookCreate +} + +// Save creates the Book entities in the database. +func (bcb *BookCreateBulk) Save(ctx context.Context) ([]*Book, error) { + specs := make([]*sqlgraph.CreateSpec, len(bcb.builders)) + nodes := make([]*Book, len(bcb.builders)) + mutators := make([]Mutator, len(bcb.builders)) + for i := range bcb.builders { + func(i int, root context.Context) { + builder := bcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, bcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, bcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, bcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (bcb *BookCreateBulk) SaveX(ctx context.Context) []*Book { + v, err := bcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bcb *BookCreateBulk) Exec(ctx context.Context) error { + _, err := bcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bcb *BookCreateBulk) ExecX(ctx context.Context) { + if err := bcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/book_delete.go b/internal/data/model/book_delete.go new file mode 100644 index 0000000..6813e56 --- /dev/null +++ b/internal/data/model/book_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookDelete is the builder for deleting a Book entity. +type BookDelete struct { + config + hooks []Hook + mutation *BookMutation +} + +// Where appends a list predicates to the BookDelete builder. +func (bd *BookDelete) Where(ps ...predicate.Book) *BookDelete { + bd.mutation.Where(ps...) + return bd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (bd *BookDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(bd.hooks) == 0 { + affected, err = bd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + bd.mutation = mutation + affected, err = bd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(bd.hooks) - 1; i >= 0; i-- { + if bd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = bd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bd *BookDelete) ExecX(ctx context.Context) int { + n, err := bd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (bd *BookDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + } + if ps := bd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, bd.driver, _spec) +} + +// BookDeleteOne is the builder for deleting a single Book entity. +type BookDeleteOne struct { + bd *BookDelete +} + +// Exec executes the deletion query. +func (bdo *BookDeleteOne) Exec(ctx context.Context) error { + n, err := bdo.bd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{book.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (bdo *BookDeleteOne) ExecX(ctx context.Context) { + bdo.bd.ExecX(ctx) +} diff --git a/internal/data/model/book_query.go b/internal/data/model/book_query.go new file mode 100644 index 0000000..d27c9e7 --- /dev/null +++ b/internal/data/model/book_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookQuery is the builder for querying Book entities. +type BookQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Book + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the BookQuery builder. +func (bq *BookQuery) Where(ps ...predicate.Book) *BookQuery { + bq.predicates = append(bq.predicates, ps...) + return bq +} + +// Limit adds a limit step to the query. +func (bq *BookQuery) Limit(limit int) *BookQuery { + bq.limit = &limit + return bq +} + +// Offset adds an offset step to the query. +func (bq *BookQuery) Offset(offset int) *BookQuery { + bq.offset = &offset + return bq +} + +// 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 (bq *BookQuery) Unique(unique bool) *BookQuery { + bq.unique = &unique + return bq +} + +// Order adds an order step to the query. +func (bq *BookQuery) Order(o ...OrderFunc) *BookQuery { + bq.order = append(bq.order, o...) + return bq +} + +// First returns the first Book entity from the query. +// Returns a *NotFoundError when no Book was found. +func (bq *BookQuery) First(ctx context.Context) (*Book, error) { + nodes, err := bq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{book.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (bq *BookQuery) FirstX(ctx context.Context) *Book { + node, err := bq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Book ID from the query. +// Returns a *NotFoundError when no Book ID was found. +func (bq *BookQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{book.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (bq *BookQuery) FirstIDX(ctx context.Context) int { + id, err := bq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last Book entity from the query. +// Returns a *NotFoundError when no Book was found. +func (bq *BookQuery) Last(ctx context.Context) (*Book, error) { + nodes, err := bq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{book.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (bq *BookQuery) LastX(ctx context.Context) *Book { + node, err := bq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last Book ID from the query. +// Returns a *NotFoundError when no Book ID was found. +func (bq *BookQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{book.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (bq *BookQuery) LastIDX(ctx context.Context) int { + id, err := bq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Book entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one Book entity is not found. +// Returns a *NotFoundError when no Book entities are found. +func (bq *BookQuery) Only(ctx context.Context) (*Book, error) { + nodes, err := bq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{book.Label} + default: + return nil, &NotSingularError{book.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (bq *BookQuery) OnlyX(ctx context.Context) *Book { + node, err := bq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Book ID in the query. +// Returns a *NotSingularError when exactly one Book ID is not found. +// Returns a *NotFoundError when no entities are found. +func (bq *BookQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{book.Label} + default: + err = &NotSingularError{book.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (bq *BookQuery) OnlyIDX(ctx context.Context) int { + id, err := bq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Books. +func (bq *BookQuery) All(ctx context.Context) ([]*Book, error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + return bq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (bq *BookQuery) AllX(ctx context.Context) []*Book { + nodes, err := bq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Book IDs. +func (bq *BookQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := bq.Select(book.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (bq *BookQuery) IDsX(ctx context.Context) []int { + ids, err := bq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (bq *BookQuery) Count(ctx context.Context) (int, error) { + if err := bq.prepareQuery(ctx); err != nil { + return 0, err + } + return bq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (bq *BookQuery) CountX(ctx context.Context) int { + count, err := bq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (bq *BookQuery) Exist(ctx context.Context) (bool, error) { + if err := bq.prepareQuery(ctx); err != nil { + return false, err + } + return bq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (bq *BookQuery) ExistX(ctx context.Context) bool { + exist, err := bq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BookQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (bq *BookQuery) Clone() *BookQuery { + if bq == nil { + return nil + } + return &BookQuery{ + config: bq.config, + limit: bq.limit, + offset: bq.offset, + order: append([]OrderFunc{}, bq.order...), + predicates: append([]predicate.Book{}, bq.predicates...), + // clone intermediate query. + sql: bq.sql.Clone(), + path: bq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Title string `json:"title,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Book.Query(). +// GroupBy(book.FieldTitle). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (bq *BookQuery) GroupBy(field string, fields ...string) *BookGroupBy { + group := &BookGroupBy{config: bq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + return bq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Title string `json:"title,omitempty"` +// } +// +// client.Book.Query(). +// Select(book.FieldTitle). +// Scan(ctx, &v) +// +func (bq *BookQuery) Select(fields ...string) *BookSelect { + bq.fields = append(bq.fields, fields...) + return &BookSelect{BookQuery: bq} +} + +func (bq *BookQuery) prepareQuery(ctx context.Context) error { + for _, f := range bq.fields { + if !book.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if bq.path != nil { + prev, err := bq.path(ctx) + if err != nil { + return err + } + bq.sql = prev + } + return nil +} + +func (bq *BookQuery) sqlAll(ctx context.Context) ([]*Book, error) { + var ( + nodes = []*Book{} + _spec = bq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Book{config: bq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, bq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (bq *BookQuery) sqlCount(ctx context.Context) (int, error) { + _spec := bq.querySpec() + return sqlgraph.CountNodes(ctx, bq.driver, _spec) +} + +func (bq *BookQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := bq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (bq *BookQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + Columns: book.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + From: bq.sql, + Unique: true, + } + if unique := bq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := bq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, book.FieldID) + for i := range fields { + if fields[i] != book.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := bq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := bq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := bq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := bq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (bq *BookQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(bq.driver.Dialect()) + t1 := builder.Table(book.Table) + columns := bq.fields + if len(columns) == 0 { + columns = book.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if bq.sql != nil { + selector = bq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range bq.predicates { + p(selector) + } + for _, p := range bq.order { + p(selector) + } + if offset := bq.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 := bq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// BookGroupBy is the group-by builder for Book entities. +type BookGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (bgb *BookGroupBy) Aggregate(fns ...AggregateFunc) *BookGroupBy { + bgb.fns = append(bgb.fns, fns...) + return bgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (bgb *BookGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := bgb.path(ctx) + if err != nil { + return err + } + bgb.sql = query + return bgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (bgb *BookGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := bgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (bgb *BookGroupBy) StringsX(ctx context.Context) []string { + v, err := bgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = bgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (bgb *BookGroupBy) StringX(ctx context.Context) string { + v, err := bgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (bgb *BookGroupBy) IntsX(ctx context.Context) []int { + v, err := bgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = bgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (bgb *BookGroupBy) IntX(ctx context.Context) int { + v, err := bgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (bgb *BookGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := bgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = bgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (bgb *BookGroupBy) Float64X(ctx context.Context) float64 { + v, err := bgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (bgb *BookGroupBy) BoolsX(ctx context.Context) []bool { + v, err := bgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = bgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (bgb *BookGroupBy) BoolX(ctx context.Context) bool { + v, err := bgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (bgb *BookGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range bgb.fields { + if !book.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := bgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := bgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (bgb *BookGroupBy) sqlQuery() *sql.Selector { + selector := bgb.sql.Select() + aggregation := make([]string, 0, len(bgb.fns)) + for _, fn := range bgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(bgb.fields)+len(bgb.fns)) + for _, f := range bgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(bgb.fields...)...) +} + +// BookSelect is the builder for selecting fields of Book entities. +type BookSelect struct { + *BookQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (bs *BookSelect) Scan(ctx context.Context, v interface{}) error { + if err := bs.prepareQuery(ctx); err != nil { + return err + } + bs.sql = bs.BookQuery.sqlQuery(ctx) + return bs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (bs *BookSelect) ScanX(ctx context.Context, v interface{}) { + if err := bs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Strings(ctx context.Context) ([]string, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (bs *BookSelect) StringsX(ctx context.Context) []string { + v, err := bs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = bs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (bs *BookSelect) StringX(ctx context.Context) string { + v, err := bs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Ints(ctx context.Context) ([]int, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (bs *BookSelect) IntsX(ctx context.Context) []int { + v, err := bs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = bs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (bs *BookSelect) IntX(ctx context.Context) int { + v, err := bs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (bs *BookSelect) Float64sX(ctx context.Context) []float64 { + v, err := bs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = bs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (bs *BookSelect) Float64X(ctx context.Context) float64 { + v, err := bs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Bools(ctx context.Context) ([]bool, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (bs *BookSelect) BoolsX(ctx context.Context) []bool { + v, err := bs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = bs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (bs *BookSelect) BoolX(ctx context.Context) bool { + v, err := bs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (bs *BookSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := bs.sql.Query() + if err := bs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/book_update.go b/internal/data/model/book_update.go new file mode 100644 index 0000000..1d409aa --- /dev/null +++ b/internal/data/model/book_update.go @@ -0,0 +1,342 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookUpdate is the builder for updating Book entities. +type BookUpdate struct { + config + hooks []Hook + mutation *BookMutation +} + +// Where appends a list predicates to the BookUpdate builder. +func (bu *BookUpdate) Where(ps ...predicate.Book) *BookUpdate { + bu.mutation.Where(ps...) + return bu +} + +// SetTitle sets the "title" field. +func (bu *BookUpdate) SetTitle(s string) *BookUpdate { + bu.mutation.SetTitle(s) + return bu +} + +// SetAuthor sets the "author" field. +func (bu *BookUpdate) SetAuthor(s string) *BookUpdate { + bu.mutation.SetAuthor(s) + return bu +} + +// SetSummary sets the "summary" field. +func (bu *BookUpdate) SetSummary(s string) *BookUpdate { + bu.mutation.SetSummary(s) + return bu +} + +// SetImage sets the "image" field. +func (bu *BookUpdate) SetImage(s string) *BookUpdate { + bu.mutation.SetImage(s) + return bu +} + +// Mutation returns the BookMutation object of the builder. +func (bu *BookUpdate) Mutation() *BookMutation { + return bu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (bu *BookUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(bu.hooks) == 0 { + affected, err = bu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + bu.mutation = mutation + affected, err = bu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(bu.hooks) - 1; i >= 0; i-- { + if bu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = bu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (bu *BookUpdate) SaveX(ctx context.Context) int { + affected, err := bu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (bu *BookUpdate) Exec(ctx context.Context) error { + _, err := bu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bu *BookUpdate) ExecX(ctx context.Context) { + if err := bu.Exec(ctx); err != nil { + panic(err) + } +} + +func (bu *BookUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + Columns: book.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + } + if ps := bu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := bu.mutation.Title(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldTitle, + }) + } + if value, ok := bu.mutation.Author(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldAuthor, + }) + } + if value, ok := bu.mutation.Summary(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldSummary, + }) + } + if value, ok := bu.mutation.Image(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldImage, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, bu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{book.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// BookUpdateOne is the builder for updating a single Book entity. +type BookUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BookMutation +} + +// SetTitle sets the "title" field. +func (buo *BookUpdateOne) SetTitle(s string) *BookUpdateOne { + buo.mutation.SetTitle(s) + return buo +} + +// SetAuthor sets the "author" field. +func (buo *BookUpdateOne) SetAuthor(s string) *BookUpdateOne { + buo.mutation.SetAuthor(s) + return buo +} + +// SetSummary sets the "summary" field. +func (buo *BookUpdateOne) SetSummary(s string) *BookUpdateOne { + buo.mutation.SetSummary(s) + return buo +} + +// SetImage sets the "image" field. +func (buo *BookUpdateOne) SetImage(s string) *BookUpdateOne { + buo.mutation.SetImage(s) + return buo +} + +// Mutation returns the BookMutation object of the builder. +func (buo *BookUpdateOne) Mutation() *BookMutation { + return buo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (buo *BookUpdateOne) Select(field string, fields ...string) *BookUpdateOne { + buo.fields = append([]string{field}, fields...) + return buo +} + +// Save executes the query and returns the updated Book entity. +func (buo *BookUpdateOne) Save(ctx context.Context) (*Book, error) { + var ( + err error + node *Book + ) + if len(buo.hooks) == 0 { + node, err = buo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + buo.mutation = mutation + node, err = buo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(buo.hooks) - 1; i >= 0; i-- { + if buo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = buo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, buo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (buo *BookUpdateOne) SaveX(ctx context.Context) *Book { + node, err := buo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (buo *BookUpdateOne) Exec(ctx context.Context) error { + _, err := buo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (buo *BookUpdateOne) ExecX(ctx context.Context) { + if err := buo.Exec(ctx); err != nil { + panic(err) + } +} + +func (buo *BookUpdateOne) sqlSave(ctx context.Context) (_node *Book, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + Columns: book.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + } + id, ok := buo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Book.ID for update")} + } + _spec.Node.ID.Value = id + if fields := buo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, book.FieldID) + for _, f := range fields { + if !book.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != book.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := buo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := buo.mutation.Title(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldTitle, + }) + } + if value, ok := buo.mutation.Author(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldAuthor, + }) + } + if value, ok := buo.mutation.Summary(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldSummary, + }) + } + if value, ok := buo.mutation.Image(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldImage, + }) + } + _node = &Book{config: buo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, buo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{book.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/client.go b/internal/data/model/client.go new file mode 100644 index 0000000..98d1565 --- /dev/null +++ b/internal/data/model/client.go @@ -0,0 +1,972 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "log" + + "lin-cms-go/internal/data/model/migrate" + + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Book is the client for interacting with the Book builders. + Book *BookClient + // LinFile is the client for interacting with the LinFile builders. + LinFile *LinFileClient + // LinGroup is the client for interacting with the LinGroup builders. + LinGroup *LinGroupClient + // LinGroupPermission is the client for interacting with the LinGroupPermission builders. + LinGroupPermission *LinGroupPermissionClient + // LinLog is the client for interacting with the LinLog builders. + LinLog *LinLogClient + // LinPermission is the client for interacting with the LinPermission builders. + LinPermission *LinPermissionClient + // LinUser is the client for interacting with the LinUser builders. + LinUser *LinUserClient + // LinUserIdentiy is the client for interacting with the LinUserIdentiy builders. + LinUserIdentiy *LinUserIdentiyClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Book = NewBookClient(c.config) + c.LinFile = NewLinFileClient(c.config) + c.LinGroup = NewLinGroupClient(c.config) + c.LinGroupPermission = NewLinGroupPermissionClient(c.config) + c.LinLog = NewLinLogClient(c.config) + c.LinPermission = NewLinPermissionClient(c.config) + c.LinUser = NewLinUserClient(c.config) + c.LinUserIdentiy = NewLinUserIdentiyClient(c.config) +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("model: cannot start a transaction within a transaction") + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("model: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Book: NewBookClient(cfg), + LinFile: NewLinFileClient(cfg), + LinGroup: NewLinGroupClient(cfg), + LinGroupPermission: NewLinGroupPermissionClient(cfg), + LinLog: NewLinLogClient(cfg), + LinPermission: NewLinPermissionClient(cfg), + LinUser: NewLinUserClient(cfg), + LinUserIdentiy: NewLinUserIdentiyClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + config: cfg, + Book: NewBookClient(cfg), + LinFile: NewLinFileClient(cfg), + LinGroup: NewLinGroupClient(cfg), + LinGroupPermission: NewLinGroupPermissionClient(cfg), + LinLog: NewLinLogClient(cfg), + LinPermission: NewLinPermissionClient(cfg), + LinUser: NewLinUserClient(cfg), + LinUserIdentiy: NewLinUserIdentiyClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Book. +// Query(). +// Count(ctx) +// +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Book.Use(hooks...) + c.LinFile.Use(hooks...) + c.LinGroup.Use(hooks...) + c.LinGroupPermission.Use(hooks...) + c.LinLog.Use(hooks...) + c.LinPermission.Use(hooks...) + c.LinUser.Use(hooks...) + c.LinUserIdentiy.Use(hooks...) +} + +// BookClient is a client for the Book schema. +type BookClient struct { + config +} + +// NewBookClient returns a client for the Book from the given config. +func NewBookClient(c config) *BookClient { + return &BookClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `book.Hooks(f(g(h())))`. +func (c *BookClient) Use(hooks ...Hook) { + c.hooks.Book = append(c.hooks.Book, hooks...) +} + +// Create returns a create builder for Book. +func (c *BookClient) Create() *BookCreate { + mutation := newBookMutation(c.config, OpCreate) + return &BookCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Book entities. +func (c *BookClient) CreateBulk(builders ...*BookCreate) *BookCreateBulk { + return &BookCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Book. +func (c *BookClient) Update() *BookUpdate { + mutation := newBookMutation(c.config, OpUpdate) + return &BookUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BookClient) UpdateOne(b *Book) *BookUpdateOne { + mutation := newBookMutation(c.config, OpUpdateOne, withBook(b)) + return &BookUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BookClient) UpdateOneID(id int) *BookUpdateOne { + mutation := newBookMutation(c.config, OpUpdateOne, withBookID(id)) + return &BookUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Book. +func (c *BookClient) Delete() *BookDelete { + mutation := newBookMutation(c.config, OpDelete) + return &BookDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *BookClient) DeleteOne(b *Book) *BookDeleteOne { + return c.DeleteOneID(b.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *BookClient) DeleteOneID(id int) *BookDeleteOne { + builder := c.Delete().Where(book.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BookDeleteOne{builder} +} + +// Query returns a query builder for Book. +func (c *BookClient) Query() *BookQuery { + return &BookQuery{ + config: c.config, + } +} + +// Get returns a Book entity by its id. +func (c *BookClient) Get(ctx context.Context, id int) (*Book, error) { + return c.Query().Where(book.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BookClient) GetX(ctx context.Context, id int) *Book { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BookClient) Hooks() []Hook { + return c.hooks.Book +} + +// LinFileClient is a client for the LinFile schema. +type LinFileClient struct { + config +} + +// NewLinFileClient returns a client for the LinFile from the given config. +func NewLinFileClient(c config) *LinFileClient { + return &LinFileClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linfile.Hooks(f(g(h())))`. +func (c *LinFileClient) Use(hooks ...Hook) { + c.hooks.LinFile = append(c.hooks.LinFile, hooks...) +} + +// Create returns a create builder for LinFile. +func (c *LinFileClient) Create() *LinFileCreate { + mutation := newLinFileMutation(c.config, OpCreate) + return &LinFileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinFile entities. +func (c *LinFileClient) CreateBulk(builders ...*LinFileCreate) *LinFileCreateBulk { + return &LinFileCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinFile. +func (c *LinFileClient) Update() *LinFileUpdate { + mutation := newLinFileMutation(c.config, OpUpdate) + return &LinFileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinFileClient) UpdateOne(lf *LinFile) *LinFileUpdateOne { + mutation := newLinFileMutation(c.config, OpUpdateOne, withLinFile(lf)) + return &LinFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinFileClient) UpdateOneID(id int) *LinFileUpdateOne { + mutation := newLinFileMutation(c.config, OpUpdateOne, withLinFileID(id)) + return &LinFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinFile. +func (c *LinFileClient) Delete() *LinFileDelete { + mutation := newLinFileMutation(c.config, OpDelete) + return &LinFileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinFileClient) DeleteOne(lf *LinFile) *LinFileDeleteOne { + return c.DeleteOneID(lf.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinFileClient) DeleteOneID(id int) *LinFileDeleteOne { + builder := c.Delete().Where(linfile.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinFileDeleteOne{builder} +} + +// Query returns a query builder for LinFile. +func (c *LinFileClient) Query() *LinFileQuery { + return &LinFileQuery{ + config: c.config, + } +} + +// Get returns a LinFile entity by its id. +func (c *LinFileClient) Get(ctx context.Context, id int) (*LinFile, error) { + return c.Query().Where(linfile.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinFileClient) GetX(ctx context.Context, id int) *LinFile { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinFileClient) Hooks() []Hook { + return c.hooks.LinFile +} + +// LinGroupClient is a client for the LinGroup schema. +type LinGroupClient struct { + config +} + +// NewLinGroupClient returns a client for the LinGroup from the given config. +func NewLinGroupClient(c config) *LinGroupClient { + return &LinGroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `lingroup.Hooks(f(g(h())))`. +func (c *LinGroupClient) Use(hooks ...Hook) { + c.hooks.LinGroup = append(c.hooks.LinGroup, hooks...) +} + +// Create returns a create builder for LinGroup. +func (c *LinGroupClient) Create() *LinGroupCreate { + mutation := newLinGroupMutation(c.config, OpCreate) + return &LinGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinGroup entities. +func (c *LinGroupClient) CreateBulk(builders ...*LinGroupCreate) *LinGroupCreateBulk { + return &LinGroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinGroup. +func (c *LinGroupClient) Update() *LinGroupUpdate { + mutation := newLinGroupMutation(c.config, OpUpdate) + return &LinGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinGroupClient) UpdateOne(lg *LinGroup) *LinGroupUpdateOne { + mutation := newLinGroupMutation(c.config, OpUpdateOne, withLinGroup(lg)) + return &LinGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinGroupClient) UpdateOneID(id int) *LinGroupUpdateOne { + mutation := newLinGroupMutation(c.config, OpUpdateOne, withLinGroupID(id)) + return &LinGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinGroup. +func (c *LinGroupClient) Delete() *LinGroupDelete { + mutation := newLinGroupMutation(c.config, OpDelete) + return &LinGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinGroupClient) DeleteOne(lg *LinGroup) *LinGroupDeleteOne { + return c.DeleteOneID(lg.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinGroupClient) DeleteOneID(id int) *LinGroupDeleteOne { + builder := c.Delete().Where(lingroup.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinGroupDeleteOne{builder} +} + +// Query returns a query builder for LinGroup. +func (c *LinGroupClient) Query() *LinGroupQuery { + return &LinGroupQuery{ + config: c.config, + } +} + +// Get returns a LinGroup entity by its id. +func (c *LinGroupClient) Get(ctx context.Context, id int) (*LinGroup, error) { + return c.Query().Where(lingroup.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinGroupClient) GetX(ctx context.Context, id int) *LinGroup { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinUser queries the lin_user edge of a LinGroup. +func (c *LinGroupClient) QueryLinUser(lg *LinGroup) *LinUserQuery { + query := &LinUserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lg.ID + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, id), + sqlgraph.To(linuser.Table, linuser.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, lingroup.LinUserTable, lingroup.LinUserPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lg.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLinPermission queries the lin_permission edge of a LinGroup. +func (c *LinGroupClient) QueryLinPermission(lg *LinGroup) *LinPermissionQuery { + query := &LinPermissionQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lg.ID + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, id), + sqlgraph.To(linpermission.Table, linpermission.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, lingroup.LinPermissionTable, lingroup.LinPermissionPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lg.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinGroupClient) Hooks() []Hook { + return c.hooks.LinGroup +} + +// LinGroupPermissionClient is a client for the LinGroupPermission schema. +type LinGroupPermissionClient struct { + config +} + +// NewLinGroupPermissionClient returns a client for the LinGroupPermission from the given config. +func NewLinGroupPermissionClient(c config) *LinGroupPermissionClient { + return &LinGroupPermissionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `lingrouppermission.Hooks(f(g(h())))`. +func (c *LinGroupPermissionClient) Use(hooks ...Hook) { + c.hooks.LinGroupPermission = append(c.hooks.LinGroupPermission, hooks...) +} + +// Create returns a create builder for LinGroupPermission. +func (c *LinGroupPermissionClient) Create() *LinGroupPermissionCreate { + mutation := newLinGroupPermissionMutation(c.config, OpCreate) + return &LinGroupPermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinGroupPermission entities. +func (c *LinGroupPermissionClient) CreateBulk(builders ...*LinGroupPermissionCreate) *LinGroupPermissionCreateBulk { + return &LinGroupPermissionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinGroupPermission. +func (c *LinGroupPermissionClient) Update() *LinGroupPermissionUpdate { + mutation := newLinGroupPermissionMutation(c.config, OpUpdate) + return &LinGroupPermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinGroupPermissionClient) UpdateOne(lgp *LinGroupPermission) *LinGroupPermissionUpdateOne { + mutation := newLinGroupPermissionMutation(c.config, OpUpdateOne, withLinGroupPermission(lgp)) + return &LinGroupPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinGroupPermissionClient) UpdateOneID(id int) *LinGroupPermissionUpdateOne { + mutation := newLinGroupPermissionMutation(c.config, OpUpdateOne, withLinGroupPermissionID(id)) + return &LinGroupPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinGroupPermission. +func (c *LinGroupPermissionClient) Delete() *LinGroupPermissionDelete { + mutation := newLinGroupPermissionMutation(c.config, OpDelete) + return &LinGroupPermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinGroupPermissionClient) DeleteOne(lgp *LinGroupPermission) *LinGroupPermissionDeleteOne { + return c.DeleteOneID(lgp.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinGroupPermissionClient) DeleteOneID(id int) *LinGroupPermissionDeleteOne { + builder := c.Delete().Where(lingrouppermission.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinGroupPermissionDeleteOne{builder} +} + +// Query returns a query builder for LinGroupPermission. +func (c *LinGroupPermissionClient) Query() *LinGroupPermissionQuery { + return &LinGroupPermissionQuery{ + config: c.config, + } +} + +// Get returns a LinGroupPermission entity by its id. +func (c *LinGroupPermissionClient) Get(ctx context.Context, id int) (*LinGroupPermission, error) { + return c.Query().Where(lingrouppermission.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinGroupPermissionClient) GetX(ctx context.Context, id int) *LinGroupPermission { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinGroupPermissionClient) Hooks() []Hook { + return c.hooks.LinGroupPermission +} + +// LinLogClient is a client for the LinLog schema. +type LinLogClient struct { + config +} + +// NewLinLogClient returns a client for the LinLog from the given config. +func NewLinLogClient(c config) *LinLogClient { + return &LinLogClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linlog.Hooks(f(g(h())))`. +func (c *LinLogClient) Use(hooks ...Hook) { + c.hooks.LinLog = append(c.hooks.LinLog, hooks...) +} + +// Create returns a create builder for LinLog. +func (c *LinLogClient) Create() *LinLogCreate { + mutation := newLinLogMutation(c.config, OpCreate) + return &LinLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinLog entities. +func (c *LinLogClient) CreateBulk(builders ...*LinLogCreate) *LinLogCreateBulk { + return &LinLogCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinLog. +func (c *LinLogClient) Update() *LinLogUpdate { + mutation := newLinLogMutation(c.config, OpUpdate) + return &LinLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinLogClient) UpdateOne(ll *LinLog) *LinLogUpdateOne { + mutation := newLinLogMutation(c.config, OpUpdateOne, withLinLog(ll)) + return &LinLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinLogClient) UpdateOneID(id int) *LinLogUpdateOne { + mutation := newLinLogMutation(c.config, OpUpdateOne, withLinLogID(id)) + return &LinLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinLog. +func (c *LinLogClient) Delete() *LinLogDelete { + mutation := newLinLogMutation(c.config, OpDelete) + return &LinLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinLogClient) DeleteOne(ll *LinLog) *LinLogDeleteOne { + return c.DeleteOneID(ll.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinLogClient) DeleteOneID(id int) *LinLogDeleteOne { + builder := c.Delete().Where(linlog.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinLogDeleteOne{builder} +} + +// Query returns a query builder for LinLog. +func (c *LinLogClient) Query() *LinLogQuery { + return &LinLogQuery{ + config: c.config, + } +} + +// Get returns a LinLog entity by its id. +func (c *LinLogClient) Get(ctx context.Context, id int) (*LinLog, error) { + return c.Query().Where(linlog.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinLogClient) GetX(ctx context.Context, id int) *LinLog { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinLogClient) Hooks() []Hook { + return c.hooks.LinLog +} + +// LinPermissionClient is a client for the LinPermission schema. +type LinPermissionClient struct { + config +} + +// NewLinPermissionClient returns a client for the LinPermission from the given config. +func NewLinPermissionClient(c config) *LinPermissionClient { + return &LinPermissionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linpermission.Hooks(f(g(h())))`. +func (c *LinPermissionClient) Use(hooks ...Hook) { + c.hooks.LinPermission = append(c.hooks.LinPermission, hooks...) +} + +// Create returns a create builder for LinPermission. +func (c *LinPermissionClient) Create() *LinPermissionCreate { + mutation := newLinPermissionMutation(c.config, OpCreate) + return &LinPermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinPermission entities. +func (c *LinPermissionClient) CreateBulk(builders ...*LinPermissionCreate) *LinPermissionCreateBulk { + return &LinPermissionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinPermission. +func (c *LinPermissionClient) Update() *LinPermissionUpdate { + mutation := newLinPermissionMutation(c.config, OpUpdate) + return &LinPermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinPermissionClient) UpdateOne(lp *LinPermission) *LinPermissionUpdateOne { + mutation := newLinPermissionMutation(c.config, OpUpdateOne, withLinPermission(lp)) + return &LinPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinPermissionClient) UpdateOneID(id int) *LinPermissionUpdateOne { + mutation := newLinPermissionMutation(c.config, OpUpdateOne, withLinPermissionID(id)) + return &LinPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinPermission. +func (c *LinPermissionClient) Delete() *LinPermissionDelete { + mutation := newLinPermissionMutation(c.config, OpDelete) + return &LinPermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinPermissionClient) DeleteOne(lp *LinPermission) *LinPermissionDeleteOne { + return c.DeleteOneID(lp.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinPermissionClient) DeleteOneID(id int) *LinPermissionDeleteOne { + builder := c.Delete().Where(linpermission.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinPermissionDeleteOne{builder} +} + +// Query returns a query builder for LinPermission. +func (c *LinPermissionClient) Query() *LinPermissionQuery { + return &LinPermissionQuery{ + config: c.config, + } +} + +// Get returns a LinPermission entity by its id. +func (c *LinPermissionClient) Get(ctx context.Context, id int) (*LinPermission, error) { + return c.Query().Where(linpermission.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinPermissionClient) GetX(ctx context.Context, id int) *LinPermission { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinGroup queries the lin_group edge of a LinPermission. +func (c *LinPermissionClient) QueryLinGroup(lp *LinPermission) *LinGroupQuery { + query := &LinGroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lp.ID + step := sqlgraph.NewStep( + sqlgraph.From(linpermission.Table, linpermission.FieldID, id), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, linpermission.LinGroupTable, linpermission.LinGroupPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lp.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinPermissionClient) Hooks() []Hook { + return c.hooks.LinPermission +} + +// LinUserClient is a client for the LinUser schema. +type LinUserClient struct { + config +} + +// NewLinUserClient returns a client for the LinUser from the given config. +func NewLinUserClient(c config) *LinUserClient { + return &LinUserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linuser.Hooks(f(g(h())))`. +func (c *LinUserClient) Use(hooks ...Hook) { + c.hooks.LinUser = append(c.hooks.LinUser, hooks...) +} + +// Create returns a create builder for LinUser. +func (c *LinUserClient) Create() *LinUserCreate { + mutation := newLinUserMutation(c.config, OpCreate) + return &LinUserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinUser entities. +func (c *LinUserClient) CreateBulk(builders ...*LinUserCreate) *LinUserCreateBulk { + return &LinUserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinUser. +func (c *LinUserClient) Update() *LinUserUpdate { + mutation := newLinUserMutation(c.config, OpUpdate) + return &LinUserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinUserClient) UpdateOne(lu *LinUser) *LinUserUpdateOne { + mutation := newLinUserMutation(c.config, OpUpdateOne, withLinUser(lu)) + return &LinUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinUserClient) UpdateOneID(id int) *LinUserUpdateOne { + mutation := newLinUserMutation(c.config, OpUpdateOne, withLinUserID(id)) + return &LinUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinUser. +func (c *LinUserClient) Delete() *LinUserDelete { + mutation := newLinUserMutation(c.config, OpDelete) + return &LinUserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinUserClient) DeleteOne(lu *LinUser) *LinUserDeleteOne { + return c.DeleteOneID(lu.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinUserClient) DeleteOneID(id int) *LinUserDeleteOne { + builder := c.Delete().Where(linuser.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinUserDeleteOne{builder} +} + +// Query returns a query builder for LinUser. +func (c *LinUserClient) Query() *LinUserQuery { + return &LinUserQuery{ + config: c.config, + } +} + +// Get returns a LinUser entity by its id. +func (c *LinUserClient) Get(ctx context.Context, id int) (*LinUser, error) { + return c.Query().Where(linuser.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinUserClient) GetX(ctx context.Context, id int) *LinUser { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinUserIdentiy queries the lin_user_identiy edge of a LinUser. +func (c *LinUserClient) QueryLinUserIdentiy(lu *LinUser) *LinUserIdentiyQuery { + query := &LinUserIdentiyQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lu.ID + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, id), + sqlgraph.To(linuseridentiy.Table, linuseridentiy.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, linuser.LinUserIdentiyTable, linuser.LinUserIdentiyColumn), + ) + fromV = sqlgraph.Neighbors(lu.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLinGroup queries the lin_group edge of a LinUser. +func (c *LinUserClient) QueryLinGroup(lu *LinUser) *LinGroupQuery { + query := &LinGroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lu.ID + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, id), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, linuser.LinGroupTable, linuser.LinGroupPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lu.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinUserClient) Hooks() []Hook { + return c.hooks.LinUser +} + +// LinUserIdentiyClient is a client for the LinUserIdentiy schema. +type LinUserIdentiyClient struct { + config +} + +// NewLinUserIdentiyClient returns a client for the LinUserIdentiy from the given config. +func NewLinUserIdentiyClient(c config) *LinUserIdentiyClient { + return &LinUserIdentiyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linuseridentiy.Hooks(f(g(h())))`. +func (c *LinUserIdentiyClient) Use(hooks ...Hook) { + c.hooks.LinUserIdentiy = append(c.hooks.LinUserIdentiy, hooks...) +} + +// Create returns a create builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Create() *LinUserIdentiyCreate { + mutation := newLinUserIdentiyMutation(c.config, OpCreate) + return &LinUserIdentiyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinUserIdentiy entities. +func (c *LinUserIdentiyClient) CreateBulk(builders ...*LinUserIdentiyCreate) *LinUserIdentiyCreateBulk { + return &LinUserIdentiyCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Update() *LinUserIdentiyUpdate { + mutation := newLinUserIdentiyMutation(c.config, OpUpdate) + return &LinUserIdentiyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinUserIdentiyClient) UpdateOne(lui *LinUserIdentiy) *LinUserIdentiyUpdateOne { + mutation := newLinUserIdentiyMutation(c.config, OpUpdateOne, withLinUserIdentiy(lui)) + return &LinUserIdentiyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinUserIdentiyClient) UpdateOneID(id int) *LinUserIdentiyUpdateOne { + mutation := newLinUserIdentiyMutation(c.config, OpUpdateOne, withLinUserIdentiyID(id)) + return &LinUserIdentiyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Delete() *LinUserIdentiyDelete { + mutation := newLinUserIdentiyMutation(c.config, OpDelete) + return &LinUserIdentiyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinUserIdentiyClient) DeleteOne(lui *LinUserIdentiy) *LinUserIdentiyDeleteOne { + return c.DeleteOneID(lui.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinUserIdentiyClient) DeleteOneID(id int) *LinUserIdentiyDeleteOne { + builder := c.Delete().Where(linuseridentiy.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinUserIdentiyDeleteOne{builder} +} + +// Query returns a query builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Query() *LinUserIdentiyQuery { + return &LinUserIdentiyQuery{ + config: c.config, + } +} + +// Get returns a LinUserIdentiy entity by its id. +func (c *LinUserIdentiyClient) Get(ctx context.Context, id int) (*LinUserIdentiy, error) { + return c.Query().Where(linuseridentiy.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinUserIdentiyClient) GetX(ctx context.Context, id int) *LinUserIdentiy { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinUserIdentiyClient) Hooks() []Hook { + return c.hooks.LinUserIdentiy +} diff --git a/internal/data/model/config.go b/internal/data/model/config.go new file mode 100644 index 0000000..b0134f3 --- /dev/null +++ b/internal/data/model/config.go @@ -0,0 +1,66 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" +) + +// Option function to configure the client. +type Option func(*config) + +// Config is the configuration for the client and its builder. +type config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...interface{}) + // hooks to execute on mutations. + hooks *hooks +} + +// hooks per client, for fast access. +type hooks struct { + Book []ent.Hook + LinFile []ent.Hook + LinGroup []ent.Hook + LinGroupPermission []ent.Hook + LinLog []ent.Hook + LinPermission []ent.Hook + LinUser []ent.Hook + LinUserIdentiy []ent.Hook +} + +// Options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...interface{})) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} diff --git a/internal/data/model/context.go b/internal/data/model/context.go new file mode 100644 index 0000000..37c8e62 --- /dev/null +++ b/internal/data/model/context.go @@ -0,0 +1,33 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} diff --git a/internal/data/model/ent.go b/internal/data/model/ent.go new file mode 100644 index 0000000..0706d26 --- /dev/null +++ b/internal/data/model/ent.go @@ -0,0 +1,273 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +// OrderFunc applies an ordering on the sql selector. +type OrderFunc func(*sql.Selector) + +// columnChecker returns a function indicates if the column exists in the given column. +func columnChecker(table string) func(string) error { + checks := map[string]func(string) bool{ + book.Table: book.ValidColumn, + linfile.Table: linfile.ValidColumn, + lingroup.Table: lingroup.ValidColumn, + lingrouppermission.Table: lingrouppermission.ValidColumn, + linlog.Table: linlog.ValidColumn, + linpermission.Table: linpermission.ValidColumn, + linuser.Table: linuser.ValidColumn, + linuseridentiy.Table: linuseridentiy.ValidColumn, + } + check, ok := checks[table] + if !ok { + return func(string) error { + return fmt.Errorf("unknown table %q", table) + } + } + return func(column string) error { + if !check(column) { + return fmt.Errorf("unknown column %q for table %q", column, table) + } + return nil + } +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("model: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("model: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(model.As(model.Sum(field1), "sum_field1"), (model.As(model.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +// +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "model: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "model: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "model: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "model: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} diff --git a/internal/data/model/enttest/enttest.go b/internal/data/model/enttest/enttest.go new file mode 100644 index 0000000..ea44042 --- /dev/null +++ b/internal/data/model/enttest/enttest.go @@ -0,0 +1,77 @@ +// Code generated by entc, DO NOT EDIT. + +package enttest + +import ( + "context" + "lin-cms-go/internal/data/model" + // required by schema hooks. + _ "lin-cms-go/internal/data/model/runtime" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...interface{}) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []model.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...model.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls model.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *model.Client { + o := newOptions(opts) + c, err := model.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} + +// NewClient calls model.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *model.Client { + o := newOptions(opts) + c := model.NewClient(o.opts...) + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} diff --git a/internal/data/model/hook/hook.go b/internal/data/model/hook/hook.go new file mode 100644 index 0000000..518c5f2 --- /dev/null +++ b/internal/data/model/hook/hook.go @@ -0,0 +1,294 @@ +// Code generated by entc, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model" +) + +// The BookFunc type is an adapter to allow the use of ordinary +// function as Book mutator. +type BookFunc func(context.Context, *model.BookMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f BookFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.BookMutation", m) + } + return f(ctx, mv) +} + +// The LinFileFunc type is an adapter to allow the use of ordinary +// function as LinFile mutator. +type LinFileFunc func(context.Context, *model.LinFileMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinFileFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinFileMutation", m) + } + return f(ctx, mv) +} + +// The LinGroupFunc type is an adapter to allow the use of ordinary +// function as LinGroup mutator. +type LinGroupFunc func(context.Context, *model.LinGroupMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinGroupFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinGroupMutation", m) + } + return f(ctx, mv) +} + +// The LinGroupPermissionFunc type is an adapter to allow the use of ordinary +// function as LinGroupPermission mutator. +type LinGroupPermissionFunc func(context.Context, *model.LinGroupPermissionMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinGroupPermissionFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinGroupPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinGroupPermissionMutation", m) + } + return f(ctx, mv) +} + +// The LinLogFunc type is an adapter to allow the use of ordinary +// function as LinLog mutator. +type LinLogFunc func(context.Context, *model.LinLogMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinLogFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinLogMutation", m) + } + return f(ctx, mv) +} + +// The LinPermissionFunc type is an adapter to allow the use of ordinary +// function as LinPermission mutator. +type LinPermissionFunc func(context.Context, *model.LinPermissionMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinPermissionFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinPermissionMutation", m) + } + return f(ctx, mv) +} + +// The LinUserFunc type is an adapter to allow the use of ordinary +// function as LinUser mutator. +type LinUserFunc func(context.Context, *model.LinUserMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinUserFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinUserMutation", m) + } + return f(ctx, mv) +} + +// The LinUserIdentiyFunc type is an adapter to allow the use of ordinary +// function as LinUserIdentiy mutator. +type LinUserIdentiyFunc func(context.Context, *model.LinUserIdentiyMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinUserIdentiyFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinUserIdentiyMutation", m) + } + return f(ctx, mv) +} + +// Condition is a hook condition function. +type Condition func(context.Context, model.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m model.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m model.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m model.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op model.Op) Condition { + return func(_ context.Context, m model.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m model.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m model.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m model.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +// +func If(hk model.Hook, cond Condition) model.Hook { + return func(next model.Mutator) model.Mutator { + return model.MutateFunc(func(ctx context.Context, m model.Mutation) (model.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, model.Delete|model.Create) +// +func On(hk model.Hook, op model.Op) model.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, model.Update|model.UpdateOne) +// +func Unless(hk model.Hook, op model.Op) model.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) model.Hook { + return func(model.Mutator) model.Mutator { + return model.MutateFunc(func(context.Context, model.Mutation) (model.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []model.Hook { +// return []model.Hook{ +// Reject(model.Delete|model.Update), +// } +// } +// +func Reject(op model.Op) model.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []model.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...model.Hook) Chain { + return Chain{append([]model.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() model.Hook { + return func(mutator model.Mutator) model.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...model.Hook) Chain { + newHooks := make([]model.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/internal/data/model/linfile.go b/internal/data/model/linfile.go new file mode 100644 index 0000000..56803ca --- /dev/null +++ b/internal/data/model/linfile.go @@ -0,0 +1,151 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linfile" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinFile is the model entity for the LinFile schema. +type LinFile struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // Type holds the value of the "type" field. + // 1 LOCAL 本地,2 REMOTE 远程 + Type int8 `json:"type,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Extension holds the value of the "extension" field. + Extension string `json:"extension,omitempty"` + // Size holds the value of the "size" field. + Size int `json:"size,omitempty"` + // Md5 holds the value of the "md5" field. + // md5值,防止上传重复文件 + Md5 string `json:"md5,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinFile) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linfile.FieldID, linfile.FieldType, linfile.FieldSize: + values[i] = new(sql.NullInt64) + case linfile.FieldPath, linfile.FieldName, linfile.FieldExtension, linfile.FieldMd5: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type LinFile", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinFile fields. +func (lf *LinFile) assignValues(columns []string, values []interface{}) 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 linfile.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lf.ID = int(value.Int64) + case linfile.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + lf.Path = value.String + } + case linfile.FieldType: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + lf.Type = int8(value.Int64) + } + case linfile.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + lf.Name = value.String + } + case linfile.FieldExtension: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field extension", values[i]) + } else if value.Valid { + lf.Extension = value.String + } + case linfile.FieldSize: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field size", values[i]) + } else if value.Valid { + lf.Size = int(value.Int64) + } + case linfile.FieldMd5: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field md5", values[i]) + } else if value.Valid { + lf.Md5 = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this LinFile. +// Note that you need to call LinFile.Unwrap() before calling this method if this LinFile +// was returned from a transaction, and the transaction was committed or rolled back. +func (lf *LinFile) Update() *LinFileUpdateOne { + return (&LinFileClient{config: lf.config}).UpdateOne(lf) +} + +// Unwrap unwraps the LinFile 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 (lf *LinFile) Unwrap() *LinFile { + tx, ok := lf.config.driver.(*txDriver) + if !ok { + panic("model: LinFile is not a transactional entity") + } + lf.config.driver = tx.drv + return lf +} + +// String implements the fmt.Stringer. +func (lf *LinFile) String() string { + var builder strings.Builder + builder.WriteString("LinFile(") + builder.WriteString(fmt.Sprintf("id=%v", lf.ID)) + builder.WriteString(", path=") + builder.WriteString(lf.Path) + builder.WriteString(", type=") + builder.WriteString(fmt.Sprintf("%v", lf.Type)) + builder.WriteString(", name=") + builder.WriteString(lf.Name) + builder.WriteString(", extension=") + builder.WriteString(lf.Extension) + builder.WriteString(", size=") + builder.WriteString(fmt.Sprintf("%v", lf.Size)) + builder.WriteString(", md5=") + builder.WriteString(lf.Md5) + builder.WriteByte(')') + return builder.String() +} + +// LinFiles is a parsable slice of LinFile. +type LinFiles []*LinFile + +func (lf LinFiles) config(cfg config) { + for _i := range lf { + lf[_i].config = cfg + } +} diff --git a/internal/data/model/linfile/linfile.go b/internal/data/model/linfile/linfile.go new file mode 100644 index 0000000..a5da84e --- /dev/null +++ b/internal/data/model/linfile/linfile.go @@ -0,0 +1,45 @@ +// Code generated by entc, DO NOT EDIT. + +package linfile + +const ( + // Label holds the string label denoting the linfile type in the database. + Label = "lin_file" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldExtension holds the string denoting the extension field in the database. + FieldExtension = "extension" + // FieldSize holds the string denoting the size field in the database. + FieldSize = "size" + // FieldMd5 holds the string denoting the md5 field in the database. + FieldMd5 = "md5" + // Table holds the table name of the linfile in the database. + Table = "lin_file" +) + +// Columns holds all SQL columns for linfile fields. +var Columns = []string{ + FieldID, + FieldPath, + FieldType, + FieldName, + FieldExtension, + FieldSize, + FieldMd5, +} + +// 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 +} diff --git a/internal/data/model/linfile/where.go b/internal/data/model/linfile/where.go new file mode 100644 index 0000000..7d1c3b1 --- /dev/null +++ b/internal/data/model/linfile/where.go @@ -0,0 +1,762 @@ +// Code generated by entc, DO NOT EDIT. + +package linfile + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldType), v)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Extension applies equality check predicate on the "extension" field. It's identical to ExtensionEQ. +func Extension(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldExtension), v)) + }) +} + +// Size applies equality check predicate on the "size" field. It's identical to SizeEQ. +func Size(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSize), v)) + }) +} + +// Md5 applies equality check predicate on the "md5" field. It's identical to Md5EQ. +func Md5(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMd5), v)) + }) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPath), v)) + }) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPath), v...)) + }) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPath), v...)) + }) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPath), v)) + }) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPath), v)) + }) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPath), v)) + }) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPath), v)) + }) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldPath), v)) + }) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldPath), v)) + }) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldPath), v)) + }) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldPath), v)) + }) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldPath), v)) + }) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldType), v)) + }) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldType), v)) + }) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...int8) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldType), v...)) + }) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...int8) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldType), v...)) + }) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldType), v)) + }) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldType), v)) + }) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldType), v)) + }) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldType), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// ExtensionEQ applies the EQ predicate on the "extension" field. +func ExtensionEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldExtension), v)) + }) +} + +// ExtensionNEQ applies the NEQ predicate on the "extension" field. +func ExtensionNEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldExtension), v)) + }) +} + +// ExtensionIn applies the In predicate on the "extension" field. +func ExtensionIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldExtension), v...)) + }) +} + +// ExtensionNotIn applies the NotIn predicate on the "extension" field. +func ExtensionNotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldExtension), v...)) + }) +} + +// ExtensionGT applies the GT predicate on the "extension" field. +func ExtensionGT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldExtension), v)) + }) +} + +// ExtensionGTE applies the GTE predicate on the "extension" field. +func ExtensionGTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldExtension), v)) + }) +} + +// ExtensionLT applies the LT predicate on the "extension" field. +func ExtensionLT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldExtension), v)) + }) +} + +// ExtensionLTE applies the LTE predicate on the "extension" field. +func ExtensionLTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldExtension), v)) + }) +} + +// ExtensionContains applies the Contains predicate on the "extension" field. +func ExtensionContains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldExtension), v)) + }) +} + +// ExtensionHasPrefix applies the HasPrefix predicate on the "extension" field. +func ExtensionHasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldExtension), v)) + }) +} + +// ExtensionHasSuffix applies the HasSuffix predicate on the "extension" field. +func ExtensionHasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldExtension), v)) + }) +} + +// ExtensionEqualFold applies the EqualFold predicate on the "extension" field. +func ExtensionEqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldExtension), v)) + }) +} + +// ExtensionContainsFold applies the ContainsFold predicate on the "extension" field. +func ExtensionContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldExtension), v)) + }) +} + +// SizeEQ applies the EQ predicate on the "size" field. +func SizeEQ(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSize), v)) + }) +} + +// SizeNEQ applies the NEQ predicate on the "size" field. +func SizeNEQ(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldSize), v)) + }) +} + +// SizeIn applies the In predicate on the "size" field. +func SizeIn(vs ...int) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldSize), v...)) + }) +} + +// SizeNotIn applies the NotIn predicate on the "size" field. +func SizeNotIn(vs ...int) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldSize), v...)) + }) +} + +// SizeGT applies the GT predicate on the "size" field. +func SizeGT(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldSize), v)) + }) +} + +// SizeGTE applies the GTE predicate on the "size" field. +func SizeGTE(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldSize), v)) + }) +} + +// SizeLT applies the LT predicate on the "size" field. +func SizeLT(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldSize), v)) + }) +} + +// SizeLTE applies the LTE predicate on the "size" field. +func SizeLTE(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldSize), v)) + }) +} + +// Md5EQ applies the EQ predicate on the "md5" field. +func Md5EQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMd5), v)) + }) +} + +// Md5NEQ applies the NEQ predicate on the "md5" field. +func Md5NEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMd5), v)) + }) +} + +// Md5In applies the In predicate on the "md5" field. +func Md5In(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMd5), v...)) + }) +} + +// Md5NotIn applies the NotIn predicate on the "md5" field. +func Md5NotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMd5), v...)) + }) +} + +// Md5GT applies the GT predicate on the "md5" field. +func Md5GT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMd5), v)) + }) +} + +// Md5GTE applies the GTE predicate on the "md5" field. +func Md5GTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMd5), v)) + }) +} + +// Md5LT applies the LT predicate on the "md5" field. +func Md5LT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMd5), v)) + }) +} + +// Md5LTE applies the LTE predicate on the "md5" field. +func Md5LTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMd5), v)) + }) +} + +// Md5Contains applies the Contains predicate on the "md5" field. +func Md5Contains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldMd5), v)) + }) +} + +// Md5HasPrefix applies the HasPrefix predicate on the "md5" field. +func Md5HasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldMd5), v)) + }) +} + +// Md5HasSuffix applies the HasSuffix predicate on the "md5" field. +func Md5HasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldMd5), v)) + }) +} + +// Md5EqualFold applies the EqualFold predicate on the "md5" field. +func Md5EqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldMd5), v)) + }) +} + +// Md5ContainsFold applies the ContainsFold predicate on the "md5" field. +func Md5ContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldMd5), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinFile) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinFile) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinFile) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linfile_create.go b/internal/data/model/linfile_create.go new file mode 100644 index 0000000..617d719 --- /dev/null +++ b/internal/data/model/linfile_create.go @@ -0,0 +1,305 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linfile" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileCreate is the builder for creating a LinFile entity. +type LinFileCreate struct { + config + mutation *LinFileMutation + hooks []Hook +} + +// SetPath sets the "path" field. +func (lfc *LinFileCreate) SetPath(s string) *LinFileCreate { + lfc.mutation.SetPath(s) + return lfc +} + +// SetType sets the "type" field. +func (lfc *LinFileCreate) SetType(i int8) *LinFileCreate { + lfc.mutation.SetType(i) + return lfc +} + +// SetName sets the "name" field. +func (lfc *LinFileCreate) SetName(s string) *LinFileCreate { + lfc.mutation.SetName(s) + return lfc +} + +// SetExtension sets the "extension" field. +func (lfc *LinFileCreate) SetExtension(s string) *LinFileCreate { + lfc.mutation.SetExtension(s) + return lfc +} + +// SetSize sets the "size" field. +func (lfc *LinFileCreate) SetSize(i int) *LinFileCreate { + lfc.mutation.SetSize(i) + return lfc +} + +// SetMd5 sets the "md5" field. +func (lfc *LinFileCreate) SetMd5(s string) *LinFileCreate { + lfc.mutation.SetMd5(s) + return lfc +} + +// Mutation returns the LinFileMutation object of the builder. +func (lfc *LinFileCreate) Mutation() *LinFileMutation { + return lfc.mutation +} + +// Save creates the LinFile in the database. +func (lfc *LinFileCreate) Save(ctx context.Context) (*LinFile, error) { + var ( + err error + node *LinFile + ) + if len(lfc.hooks) == 0 { + if err = lfc.check(); err != nil { + return nil, err + } + node, err = lfc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lfc.check(); err != nil { + return nil, err + } + lfc.mutation = mutation + if node, err = lfc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lfc.hooks) - 1; i >= 0; i-- { + if lfc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lfc *LinFileCreate) SaveX(ctx context.Context) *LinFile { + v, err := lfc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lfc *LinFileCreate) Exec(ctx context.Context) error { + _, err := lfc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfc *LinFileCreate) ExecX(ctx context.Context) { + if err := lfc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lfc *LinFileCreate) check() error { + if _, ok := lfc.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`model: missing required field "path"`)} + } + if _, ok := lfc.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`model: missing required field "type"`)} + } + if _, ok := lfc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} + } + if _, ok := lfc.mutation.Extension(); !ok { + return &ValidationError{Name: "extension", err: errors.New(`model: missing required field "extension"`)} + } + if _, ok := lfc.mutation.Size(); !ok { + return &ValidationError{Name: "size", err: errors.New(`model: missing required field "size"`)} + } + if _, ok := lfc.mutation.Md5(); !ok { + return &ValidationError{Name: "md5", err: errors.New(`model: missing required field "md5"`)} + } + return nil +} + +func (lfc *LinFileCreate) sqlSave(ctx context.Context) (*LinFile, error) { + _node, _spec := lfc.createSpec() + if err := sqlgraph.CreateNode(ctx, lfc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lfc *LinFileCreate) createSpec() (*LinFile, *sqlgraph.CreateSpec) { + var ( + _node = &LinFile{config: lfc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linfile.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + } + ) + if value, ok := lfc.mutation.Path(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldPath, + }) + _node.Path = value + } + if value, ok := lfc.mutation.GetType(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + _node.Type = value + } + if value, ok := lfc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldName, + }) + _node.Name = value + } + if value, ok := lfc.mutation.Extension(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldExtension, + }) + _node.Extension = value + } + if value, ok := lfc.mutation.Size(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + _node.Size = value + } + if value, ok := lfc.mutation.Md5(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldMd5, + }) + _node.Md5 = value + } + return _node, _spec +} + +// LinFileCreateBulk is the builder for creating many LinFile entities in bulk. +type LinFileCreateBulk struct { + config + builders []*LinFileCreate +} + +// Save creates the LinFile entities in the database. +func (lfcb *LinFileCreateBulk) Save(ctx context.Context) ([]*LinFile, error) { + specs := make([]*sqlgraph.CreateSpec, len(lfcb.builders)) + nodes := make([]*LinFile, len(lfcb.builders)) + mutators := make([]Mutator, len(lfcb.builders)) + for i := range lfcb.builders { + func(i int, root context.Context) { + builder := lfcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lfcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lfcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lfcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lfcb *LinFileCreateBulk) SaveX(ctx context.Context) []*LinFile { + v, err := lfcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lfcb *LinFileCreateBulk) Exec(ctx context.Context) error { + _, err := lfcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfcb *LinFileCreateBulk) ExecX(ctx context.Context) { + if err := lfcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linfile_delete.go b/internal/data/model/linfile_delete.go new file mode 100644 index 0000000..f767b58 --- /dev/null +++ b/internal/data/model/linfile_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileDelete is the builder for deleting a LinFile entity. +type LinFileDelete struct { + config + hooks []Hook + mutation *LinFileMutation +} + +// Where appends a list predicates to the LinFileDelete builder. +func (lfd *LinFileDelete) Where(ps ...predicate.LinFile) *LinFileDelete { + lfd.mutation.Where(ps...) + return lfd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lfd *LinFileDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lfd.hooks) == 0 { + affected, err = lfd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lfd.mutation = mutation + affected, err = lfd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lfd.hooks) - 1; i >= 0; i-- { + if lfd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfd *LinFileDelete) ExecX(ctx context.Context) int { + n, err := lfd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lfd *LinFileDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + } + if ps := lfd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lfd.driver, _spec) +} + +// LinFileDeleteOne is the builder for deleting a single LinFile entity. +type LinFileDeleteOne struct { + lfd *LinFileDelete +} + +// Exec executes the deletion query. +func (lfdo *LinFileDeleteOne) Exec(ctx context.Context) error { + n, err := lfdo.lfd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linfile.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfdo *LinFileDeleteOne) ExecX(ctx context.Context) { + lfdo.lfd.ExecX(ctx) +} diff --git a/internal/data/model/linfile_query.go b/internal/data/model/linfile_query.go new file mode 100644 index 0000000..43a7c54 --- /dev/null +++ b/internal/data/model/linfile_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileQuery is the builder for querying LinFile entities. +type LinFileQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinFile + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinFileQuery builder. +func (lfq *LinFileQuery) Where(ps ...predicate.LinFile) *LinFileQuery { + lfq.predicates = append(lfq.predicates, ps...) + return lfq +} + +// Limit adds a limit step to the query. +func (lfq *LinFileQuery) Limit(limit int) *LinFileQuery { + lfq.limit = &limit + return lfq +} + +// Offset adds an offset step to the query. +func (lfq *LinFileQuery) Offset(offset int) *LinFileQuery { + lfq.offset = &offset + return lfq +} + +// 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 (lfq *LinFileQuery) Unique(unique bool) *LinFileQuery { + lfq.unique = &unique + return lfq +} + +// Order adds an order step to the query. +func (lfq *LinFileQuery) Order(o ...OrderFunc) *LinFileQuery { + lfq.order = append(lfq.order, o...) + return lfq +} + +// First returns the first LinFile entity from the query. +// Returns a *NotFoundError when no LinFile was found. +func (lfq *LinFileQuery) First(ctx context.Context) (*LinFile, error) { + nodes, err := lfq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linfile.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lfq *LinFileQuery) FirstX(ctx context.Context) *LinFile { + node, err := lfq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinFile ID from the query. +// Returns a *NotFoundError when no LinFile ID was found. +func (lfq *LinFileQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lfq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linfile.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lfq *LinFileQuery) FirstIDX(ctx context.Context) int { + id, err := lfq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinFile entity from the query. +// Returns a *NotFoundError when no LinFile was found. +func (lfq *LinFileQuery) Last(ctx context.Context) (*LinFile, error) { + nodes, err := lfq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linfile.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lfq *LinFileQuery) LastX(ctx context.Context) *LinFile { + node, err := lfq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinFile ID from the query. +// Returns a *NotFoundError when no LinFile ID was found. +func (lfq *LinFileQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lfq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linfile.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lfq *LinFileQuery) LastIDX(ctx context.Context) int { + id, err := lfq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinFile entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinFile entity is not found. +// Returns a *NotFoundError when no LinFile entities are found. +func (lfq *LinFileQuery) Only(ctx context.Context) (*LinFile, error) { + nodes, err := lfq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linfile.Label} + default: + return nil, &NotSingularError{linfile.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lfq *LinFileQuery) OnlyX(ctx context.Context) *LinFile { + node, err := lfq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinFile ID in the query. +// Returns a *NotSingularError when exactly one LinFile ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lfq *LinFileQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lfq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linfile.Label} + default: + err = &NotSingularError{linfile.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lfq *LinFileQuery) OnlyIDX(ctx context.Context) int { + id, err := lfq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinFiles. +func (lfq *LinFileQuery) All(ctx context.Context) ([]*LinFile, error) { + if err := lfq.prepareQuery(ctx); err != nil { + return nil, err + } + return lfq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lfq *LinFileQuery) AllX(ctx context.Context) []*LinFile { + nodes, err := lfq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinFile IDs. +func (lfq *LinFileQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lfq.Select(linfile.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lfq *LinFileQuery) IDsX(ctx context.Context) []int { + ids, err := lfq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lfq *LinFileQuery) Count(ctx context.Context) (int, error) { + if err := lfq.prepareQuery(ctx); err != nil { + return 0, err + } + return lfq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lfq *LinFileQuery) CountX(ctx context.Context) int { + count, err := lfq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lfq *LinFileQuery) Exist(ctx context.Context) (bool, error) { + if err := lfq.prepareQuery(ctx); err != nil { + return false, err + } + return lfq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lfq *LinFileQuery) ExistX(ctx context.Context) bool { + exist, err := lfq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinFileQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lfq *LinFileQuery) Clone() *LinFileQuery { + if lfq == nil { + return nil + } + return &LinFileQuery{ + config: lfq.config, + limit: lfq.limit, + offset: lfq.offset, + order: append([]OrderFunc{}, lfq.order...), + predicates: append([]predicate.LinFile{}, lfq.predicates...), + // clone intermediate query. + sql: lfq.sql.Clone(), + path: lfq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Path string `json:"path,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinFile.Query(). +// GroupBy(linfile.FieldPath). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lfq *LinFileQuery) GroupBy(field string, fields ...string) *LinFileGroupBy { + group := &LinFileGroupBy{config: lfq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lfq.prepareQuery(ctx); err != nil { + return nil, err + } + return lfq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Path string `json:"path,omitempty"` +// } +// +// client.LinFile.Query(). +// Select(linfile.FieldPath). +// Scan(ctx, &v) +// +func (lfq *LinFileQuery) Select(fields ...string) *LinFileSelect { + lfq.fields = append(lfq.fields, fields...) + return &LinFileSelect{LinFileQuery: lfq} +} + +func (lfq *LinFileQuery) prepareQuery(ctx context.Context) error { + for _, f := range lfq.fields { + if !linfile.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lfq.path != nil { + prev, err := lfq.path(ctx) + if err != nil { + return err + } + lfq.sql = prev + } + return nil +} + +func (lfq *LinFileQuery) sqlAll(ctx context.Context) ([]*LinFile, error) { + var ( + nodes = []*LinFile{} + _spec = lfq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinFile{config: lfq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lfq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (lfq *LinFileQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lfq.querySpec() + return sqlgraph.CountNodes(ctx, lfq.driver, _spec) +} + +func (lfq *LinFileQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lfq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lfq *LinFileQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + Columns: linfile.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + From: lfq.sql, + Unique: true, + } + if unique := lfq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lfq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linfile.FieldID) + for i := range fields { + if fields[i] != linfile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lfq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lfq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lfq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lfq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lfq *LinFileQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lfq.driver.Dialect()) + t1 := builder.Table(linfile.Table) + columns := lfq.fields + if len(columns) == 0 { + columns = linfile.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lfq.sql != nil { + selector = lfq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lfq.predicates { + p(selector) + } + for _, p := range lfq.order { + p(selector) + } + if offset := lfq.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 := lfq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinFileGroupBy is the group-by builder for LinFile entities. +type LinFileGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lfgb *LinFileGroupBy) Aggregate(fns ...AggregateFunc) *LinFileGroupBy { + lfgb.fns = append(lfgb.fns, fns...) + return lfgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lfgb *LinFileGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lfgb.path(ctx) + if err != nil { + return err + } + lfgb.sql = query + return lfgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lfgb *LinFileGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lfgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lfgb *LinFileGroupBy) StringsX(ctx context.Context) []string { + v, err := lfgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lfgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lfgb *LinFileGroupBy) StringX(ctx context.Context) string { + v, err := lfgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lfgb *LinFileGroupBy) IntsX(ctx context.Context) []int { + v, err := lfgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lfgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lfgb *LinFileGroupBy) IntX(ctx context.Context) int { + v, err := lfgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lfgb *LinFileGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lfgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lfgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lfgb *LinFileGroupBy) Float64X(ctx context.Context) float64 { + v, err := lfgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lfgb *LinFileGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lfgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lfgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lfgb *LinFileGroupBy) BoolX(ctx context.Context) bool { + v, err := lfgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lfgb *LinFileGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lfgb.fields { + if !linfile.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lfgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lfgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lfgb *LinFileGroupBy) sqlQuery() *sql.Selector { + selector := lfgb.sql.Select() + aggregation := make([]string, 0, len(lfgb.fns)) + for _, fn := range lfgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lfgb.fields)+len(lfgb.fns)) + for _, f := range lfgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lfgb.fields...)...) +} + +// LinFileSelect is the builder for selecting fields of LinFile entities. +type LinFileSelect struct { + *LinFileQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lfs *LinFileSelect) Scan(ctx context.Context, v interface{}) error { + if err := lfs.prepareQuery(ctx); err != nil { + return err + } + lfs.sql = lfs.LinFileQuery.sqlQuery(ctx) + return lfs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lfs *LinFileSelect) ScanX(ctx context.Context, v interface{}) { + if err := lfs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Strings(ctx context.Context) ([]string, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lfs *LinFileSelect) StringsX(ctx context.Context) []string { + v, err := lfs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lfs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lfs *LinFileSelect) StringX(ctx context.Context) string { + v, err := lfs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Ints(ctx context.Context) ([]int, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lfs *LinFileSelect) IntsX(ctx context.Context) []int { + v, err := lfs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lfs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lfs *LinFileSelect) IntX(ctx context.Context) int { + v, err := lfs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lfs *LinFileSelect) Float64sX(ctx context.Context) []float64 { + v, err := lfs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lfs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lfs *LinFileSelect) Float64X(ctx context.Context) float64 { + v, err := lfs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lfs *LinFileSelect) BoolsX(ctx context.Context) []bool { + v, err := lfs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lfs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lfs *LinFileSelect) BoolX(ctx context.Context) bool { + v, err := lfs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lfs *LinFileSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lfs.sql.Query() + if err := lfs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linfile_update.go b/internal/data/model/linfile_update.go new file mode 100644 index 0000000..d640e3a --- /dev/null +++ b/internal/data/model/linfile_update.go @@ -0,0 +1,450 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileUpdate is the builder for updating LinFile entities. +type LinFileUpdate struct { + config + hooks []Hook + mutation *LinFileMutation +} + +// Where appends a list predicates to the LinFileUpdate builder. +func (lfu *LinFileUpdate) Where(ps ...predicate.LinFile) *LinFileUpdate { + lfu.mutation.Where(ps...) + return lfu +} + +// SetPath sets the "path" field. +func (lfu *LinFileUpdate) SetPath(s string) *LinFileUpdate { + lfu.mutation.SetPath(s) + return lfu +} + +// SetType sets the "type" field. +func (lfu *LinFileUpdate) SetType(i int8) *LinFileUpdate { + lfu.mutation.ResetType() + lfu.mutation.SetType(i) + return lfu +} + +// AddType adds i to the "type" field. +func (lfu *LinFileUpdate) AddType(i int8) *LinFileUpdate { + lfu.mutation.AddType(i) + return lfu +} + +// SetName sets the "name" field. +func (lfu *LinFileUpdate) SetName(s string) *LinFileUpdate { + lfu.mutation.SetName(s) + return lfu +} + +// SetExtension sets the "extension" field. +func (lfu *LinFileUpdate) SetExtension(s string) *LinFileUpdate { + lfu.mutation.SetExtension(s) + return lfu +} + +// SetSize sets the "size" field. +func (lfu *LinFileUpdate) SetSize(i int) *LinFileUpdate { + lfu.mutation.ResetSize() + lfu.mutation.SetSize(i) + return lfu +} + +// AddSize adds i to the "size" field. +func (lfu *LinFileUpdate) AddSize(i int) *LinFileUpdate { + lfu.mutation.AddSize(i) + return lfu +} + +// SetMd5 sets the "md5" field. +func (lfu *LinFileUpdate) SetMd5(s string) *LinFileUpdate { + lfu.mutation.SetMd5(s) + return lfu +} + +// Mutation returns the LinFileMutation object of the builder. +func (lfu *LinFileUpdate) Mutation() *LinFileMutation { + return lfu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lfu *LinFileUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lfu.hooks) == 0 { + affected, err = lfu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lfu.mutation = mutation + affected, err = lfu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lfu.hooks) - 1; i >= 0; i-- { + if lfu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lfu *LinFileUpdate) SaveX(ctx context.Context) int { + affected, err := lfu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lfu *LinFileUpdate) Exec(ctx context.Context) error { + _, err := lfu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfu *LinFileUpdate) ExecX(ctx context.Context) { + if err := lfu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lfu *LinFileUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + Columns: linfile.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + } + if ps := lfu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lfu.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldPath, + }) + } + if value, ok := lfu.mutation.GetType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfu.mutation.AddedType(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldName, + }) + } + if value, ok := lfu.mutation.Extension(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldExtension, + }) + } + if value, ok := lfu.mutation.Size(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfu.mutation.AddedSize(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfu.mutation.Md5(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldMd5, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, lfu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linfile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinFileUpdateOne is the builder for updating a single LinFile entity. +type LinFileUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinFileMutation +} + +// SetPath sets the "path" field. +func (lfuo *LinFileUpdateOne) SetPath(s string) *LinFileUpdateOne { + lfuo.mutation.SetPath(s) + return lfuo +} + +// SetType sets the "type" field. +func (lfuo *LinFileUpdateOne) SetType(i int8) *LinFileUpdateOne { + lfuo.mutation.ResetType() + lfuo.mutation.SetType(i) + return lfuo +} + +// AddType adds i to the "type" field. +func (lfuo *LinFileUpdateOne) AddType(i int8) *LinFileUpdateOne { + lfuo.mutation.AddType(i) + return lfuo +} + +// SetName sets the "name" field. +func (lfuo *LinFileUpdateOne) SetName(s string) *LinFileUpdateOne { + lfuo.mutation.SetName(s) + return lfuo +} + +// SetExtension sets the "extension" field. +func (lfuo *LinFileUpdateOne) SetExtension(s string) *LinFileUpdateOne { + lfuo.mutation.SetExtension(s) + return lfuo +} + +// SetSize sets the "size" field. +func (lfuo *LinFileUpdateOne) SetSize(i int) *LinFileUpdateOne { + lfuo.mutation.ResetSize() + lfuo.mutation.SetSize(i) + return lfuo +} + +// AddSize adds i to the "size" field. +func (lfuo *LinFileUpdateOne) AddSize(i int) *LinFileUpdateOne { + lfuo.mutation.AddSize(i) + return lfuo +} + +// SetMd5 sets the "md5" field. +func (lfuo *LinFileUpdateOne) SetMd5(s string) *LinFileUpdateOne { + lfuo.mutation.SetMd5(s) + return lfuo +} + +// Mutation returns the LinFileMutation object of the builder. +func (lfuo *LinFileUpdateOne) Mutation() *LinFileMutation { + return lfuo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lfuo *LinFileUpdateOne) Select(field string, fields ...string) *LinFileUpdateOne { + lfuo.fields = append([]string{field}, fields...) + return lfuo +} + +// Save executes the query and returns the updated LinFile entity. +func (lfuo *LinFileUpdateOne) Save(ctx context.Context) (*LinFile, error) { + var ( + err error + node *LinFile + ) + if len(lfuo.hooks) == 0 { + node, err = lfuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lfuo.mutation = mutation + node, err = lfuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lfuo.hooks) - 1; i >= 0; i-- { + if lfuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lfuo *LinFileUpdateOne) SaveX(ctx context.Context) *LinFile { + node, err := lfuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lfuo *LinFileUpdateOne) Exec(ctx context.Context) error { + _, err := lfuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfuo *LinFileUpdateOne) ExecX(ctx context.Context) { + if err := lfuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lfuo *LinFileUpdateOne) sqlSave(ctx context.Context) (_node *LinFile, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + Columns: linfile.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + } + id, ok := lfuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinFile.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lfuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linfile.FieldID) + for _, f := range fields { + if !linfile.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linfile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lfuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lfuo.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldPath, + }) + } + if value, ok := lfuo.mutation.GetType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfuo.mutation.AddedType(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldName, + }) + } + if value, ok := lfuo.mutation.Extension(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldExtension, + }) + } + if value, ok := lfuo.mutation.Size(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfuo.mutation.AddedSize(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfuo.mutation.Md5(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldMd5, + }) + } + _node = &LinFile{config: lfuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lfuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linfile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/lingroup.go b/internal/data/model/lingroup.go new file mode 100644 index 0000000..6972969 --- /dev/null +++ b/internal/data/model/lingroup.go @@ -0,0 +1,164 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinGroup is the model entity for the LinGroup schema. +type LinGroup struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + // 分组名称,例如:搬砖者 + Name string `json:"name,omitempty"` + // Info holds the value of the "info" field. + // 分组信息:例如:搬砖的人 + Info string `json:"info,omitempty"` + // Level holds the value of the "level" field. + // 分组级别 1:root 2:guest 3:user(root、guest分组只能存在一个) + Level int8 `json:"level,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinGroupQuery when eager-loading is set. + Edges LinGroupEdges `json:"edges"` +} + +// LinGroupEdges holds the relations/edges for other nodes in the graph. +type LinGroupEdges struct { + // LinUser holds the value of the lin_user edge. + LinUser []*LinUser `json:"lin_user,omitempty"` + // LinPermission holds the value of the lin_permission edge. + LinPermission []*LinPermission `json:"lin_permission,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// LinUserOrErr returns the LinUser value or an error if the edge +// was not loaded in eager-loading. +func (e LinGroupEdges) LinUserOrErr() ([]*LinUser, error) { + if e.loadedTypes[0] { + return e.LinUser, nil + } + return nil, &NotLoadedError{edge: "lin_user"} +} + +// LinPermissionOrErr returns the LinPermission value or an error if the edge +// was not loaded in eager-loading. +func (e LinGroupEdges) LinPermissionOrErr() ([]*LinPermission, error) { + if e.loadedTypes[1] { + return e.LinPermission, nil + } + return nil, &NotLoadedError{edge: "lin_permission"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinGroup) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case lingroup.FieldID, lingroup.FieldLevel: + values[i] = new(sql.NullInt64) + case lingroup.FieldName, lingroup.FieldInfo: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type LinGroup", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinGroup fields. +func (lg *LinGroup) assignValues(columns []string, values []interface{}) 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 lingroup.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lg.ID = int(value.Int64) + case lingroup.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + lg.Name = value.String + } + case lingroup.FieldInfo: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field info", values[i]) + } else if value.Valid { + lg.Info = value.String + } + case lingroup.FieldLevel: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field level", values[i]) + } else if value.Valid { + lg.Level = int8(value.Int64) + } + } + } + return nil +} + +// QueryLinUser queries the "lin_user" edge of the LinGroup entity. +func (lg *LinGroup) QueryLinUser() *LinUserQuery { + return (&LinGroupClient{config: lg.config}).QueryLinUser(lg) +} + +// QueryLinPermission queries the "lin_permission" edge of the LinGroup entity. +func (lg *LinGroup) QueryLinPermission() *LinPermissionQuery { + return (&LinGroupClient{config: lg.config}).QueryLinPermission(lg) +} + +// Update returns a builder for updating this LinGroup. +// Note that you need to call LinGroup.Unwrap() before calling this method if this LinGroup +// was returned from a transaction, and the transaction was committed or rolled back. +func (lg *LinGroup) Update() *LinGroupUpdateOne { + return (&LinGroupClient{config: lg.config}).UpdateOne(lg) +} + +// Unwrap unwraps the LinGroup 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 (lg *LinGroup) Unwrap() *LinGroup { + tx, ok := lg.config.driver.(*txDriver) + if !ok { + panic("model: LinGroup is not a transactional entity") + } + lg.config.driver = tx.drv + return lg +} + +// String implements the fmt.Stringer. +func (lg *LinGroup) String() string { + var builder strings.Builder + builder.WriteString("LinGroup(") + builder.WriteString(fmt.Sprintf("id=%v", lg.ID)) + builder.WriteString(", name=") + builder.WriteString(lg.Name) + builder.WriteString(", info=") + builder.WriteString(lg.Info) + builder.WriteString(", level=") + builder.WriteString(fmt.Sprintf("%v", lg.Level)) + builder.WriteByte(')') + return builder.String() +} + +// LinGroups is a parsable slice of LinGroup. +type LinGroups []*LinGroup + +func (lg LinGroups) config(cfg config) { + for _i := range lg { + lg[_i].config = cfg + } +} diff --git a/internal/data/model/lingroup/lingroup.go b/internal/data/model/lingroup/lingroup.go new file mode 100644 index 0000000..5d25855 --- /dev/null +++ b/internal/data/model/lingroup/lingroup.go @@ -0,0 +1,59 @@ +// Code generated by entc, DO NOT EDIT. + +package lingroup + +const ( + // Label holds the string label denoting the lingroup type in the database. + Label = "lin_group" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldInfo holds the string denoting the info field in the database. + FieldInfo = "info" + // FieldLevel holds the string denoting the level field in the database. + FieldLevel = "level" + // EdgeLinUser holds the string denoting the lin_user edge name in mutations. + EdgeLinUser = "lin_user" + // EdgeLinPermission holds the string denoting the lin_permission edge name in mutations. + EdgeLinPermission = "lin_permission" + // Table holds the table name of the lingroup in the database. + Table = "lin_group" + // LinUserTable is the table that holds the lin_user relation/edge. The primary key declared below. + LinUserTable = "lin_user_group" + // LinUserInverseTable is the table name for the LinUser entity. + // It exists in this package in order to avoid circular dependency with the "linuser" package. + LinUserInverseTable = "lin_user" + // LinPermissionTable is the table that holds the lin_permission relation/edge. The primary key declared below. + LinPermissionTable = "lin_permission_lin_group" + // LinPermissionInverseTable is the table name for the LinPermission entity. + // It exists in this package in order to avoid circular dependency with the "linpermission" package. + LinPermissionInverseTable = "lin_permission" +) + +// Columns holds all SQL columns for lingroup fields. +var Columns = []string{ + FieldID, + FieldName, + FieldInfo, + FieldLevel, +} + +var ( + // LinUserPrimaryKey and LinUserColumn2 are the table columns denoting the + // primary key for the lin_user relation (M2M). + LinUserPrimaryKey = []string{"user_id", "group_id"} + // LinPermissionPrimaryKey and LinPermissionColumn2 are the table columns denoting the + // primary key for the lin_permission relation (M2M). + LinPermissionPrimaryKey = []string{"lin_permission_id", "lin_group_id"} +) + +// 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 +} diff --git a/internal/data/model/lingroup/where.go b/internal/data/model/lingroup/where.go new file mode 100644 index 0000000..d4c70dd --- /dev/null +++ b/internal/data/model/lingroup/where.go @@ -0,0 +1,500 @@ +// Code generated by entc, DO NOT EDIT. + +package lingroup + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Info applies equality check predicate on the "info" field. It's identical to InfoEQ. +func Info(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldInfo), v)) + }) +} + +// Level applies equality check predicate on the "level" field. It's identical to LevelEQ. +func Level(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldLevel), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// InfoEQ applies the EQ predicate on the "info" field. +func InfoEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldInfo), v)) + }) +} + +// InfoNEQ applies the NEQ predicate on the "info" field. +func InfoNEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldInfo), v)) + }) +} + +// InfoIn applies the In predicate on the "info" field. +func InfoIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldInfo), v...)) + }) +} + +// InfoNotIn applies the NotIn predicate on the "info" field. +func InfoNotIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldInfo), v...)) + }) +} + +// InfoGT applies the GT predicate on the "info" field. +func InfoGT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldInfo), v)) + }) +} + +// InfoGTE applies the GTE predicate on the "info" field. +func InfoGTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldInfo), v)) + }) +} + +// InfoLT applies the LT predicate on the "info" field. +func InfoLT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldInfo), v)) + }) +} + +// InfoLTE applies the LTE predicate on the "info" field. +func InfoLTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldInfo), v)) + }) +} + +// InfoContains applies the Contains predicate on the "info" field. +func InfoContains(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldInfo), v)) + }) +} + +// InfoHasPrefix applies the HasPrefix predicate on the "info" field. +func InfoHasPrefix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldInfo), v)) + }) +} + +// InfoHasSuffix applies the HasSuffix predicate on the "info" field. +func InfoHasSuffix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldInfo), v)) + }) +} + +// InfoEqualFold applies the EqualFold predicate on the "info" field. +func InfoEqualFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldInfo), v)) + }) +} + +// InfoContainsFold applies the ContainsFold predicate on the "info" field. +func InfoContainsFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldInfo), v)) + }) +} + +// LevelEQ applies the EQ predicate on the "level" field. +func LevelEQ(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldLevel), v)) + }) +} + +// LevelNEQ applies the NEQ predicate on the "level" field. +func LevelNEQ(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldLevel), v)) + }) +} + +// LevelIn applies the In predicate on the "level" field. +func LevelIn(vs ...int8) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldLevel), v...)) + }) +} + +// LevelNotIn applies the NotIn predicate on the "level" field. +func LevelNotIn(vs ...int8) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldLevel), v...)) + }) +} + +// LevelGT applies the GT predicate on the "level" field. +func LevelGT(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldLevel), v)) + }) +} + +// LevelGTE applies the GTE predicate on the "level" field. +func LevelGTE(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldLevel), v)) + }) +} + +// LevelLT applies the LT predicate on the "level" field. +func LevelLT(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldLevel), v)) + }) +} + +// LevelLTE applies the LTE predicate on the "level" field. +func LevelLTE(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldLevel), v)) + }) +} + +// HasLinUser applies the HasEdge predicate on the "lin_user" edge. +func HasLinUser() predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinUserTable, LinUserPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinUserWith applies the HasEdge predicate on the "lin_user" edge with a given conditions (other predicates). +func HasLinUserWith(preds ...predicate.LinUser) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinUserTable, LinUserPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasLinPermission applies the HasEdge predicate on the "lin_permission" edge. +func HasLinPermission() predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinPermissionTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinPermissionTable, LinPermissionPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinPermissionWith applies the HasEdge predicate on the "lin_permission" edge with a given conditions (other predicates). +func HasLinPermissionWith(preds ...predicate.LinPermission) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinPermissionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinPermissionTable, LinPermissionPrimaryKey...), + ) + 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.LinGroup) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinGroup) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinGroup) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/lingroup_create.go b/internal/data/model/lingroup_create.go new file mode 100644 index 0000000..9b3b354 --- /dev/null +++ b/internal/data/model/lingroup_create.go @@ -0,0 +1,324 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupCreate is the builder for creating a LinGroup entity. +type LinGroupCreate struct { + config + mutation *LinGroupMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (lgc *LinGroupCreate) SetName(s string) *LinGroupCreate { + lgc.mutation.SetName(s) + return lgc +} + +// SetInfo sets the "info" field. +func (lgc *LinGroupCreate) SetInfo(s string) *LinGroupCreate { + lgc.mutation.SetInfo(s) + return lgc +} + +// SetLevel sets the "level" field. +func (lgc *LinGroupCreate) SetLevel(i int8) *LinGroupCreate { + lgc.mutation.SetLevel(i) + return lgc +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. +func (lgc *LinGroupCreate) AddLinUserIDs(ids ...int) *LinGroupCreate { + lgc.mutation.AddLinUserIDs(ids...) + return lgc +} + +// AddLinUser adds the "lin_user" edges to the LinUser entity. +func (lgc *LinGroupCreate) AddLinUser(l ...*LinUser) *LinGroupCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgc.AddLinUserIDs(ids...) +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. +func (lgc *LinGroupCreate) AddLinPermissionIDs(ids ...int) *LinGroupCreate { + lgc.mutation.AddLinPermissionIDs(ids...) + return lgc +} + +// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. +func (lgc *LinGroupCreate) AddLinPermission(l ...*LinPermission) *LinGroupCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgc.AddLinPermissionIDs(ids...) +} + +// Mutation returns the LinGroupMutation object of the builder. +func (lgc *LinGroupCreate) Mutation() *LinGroupMutation { + return lgc.mutation +} + +// Save creates the LinGroup in the database. +func (lgc *LinGroupCreate) Save(ctx context.Context) (*LinGroup, error) { + var ( + err error + node *LinGroup + ) + if len(lgc.hooks) == 0 { + if err = lgc.check(); err != nil { + return nil, err + } + node, err = lgc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lgc.check(); err != nil { + return nil, err + } + lgc.mutation = mutation + if node, err = lgc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lgc.hooks) - 1; i >= 0; i-- { + if lgc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lgc *LinGroupCreate) SaveX(ctx context.Context) *LinGroup { + v, err := lgc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lgc *LinGroupCreate) Exec(ctx context.Context) error { + _, err := lgc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgc *LinGroupCreate) ExecX(ctx context.Context) { + if err := lgc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lgc *LinGroupCreate) check() error { + if _, ok := lgc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} + } + if _, ok := lgc.mutation.Info(); !ok { + return &ValidationError{Name: "info", err: errors.New(`model: missing required field "info"`)} + } + if _, ok := lgc.mutation.Level(); !ok { + return &ValidationError{Name: "level", err: errors.New(`model: missing required field "level"`)} + } + return nil +} + +func (lgc *LinGroupCreate) sqlSave(ctx context.Context) (*LinGroup, error) { + _node, _spec := lgc.createSpec() + if err := sqlgraph.CreateNode(ctx, lgc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lgc *LinGroupCreate) createSpec() (*LinGroup, *sqlgraph.CreateSpec) { + var ( + _node = &LinGroup{config: lgc.config} + _spec = &sqlgraph.CreateSpec{ + Table: lingroup.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + } + ) + if value, ok := lgc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldName, + }) + _node.Name = value + } + if value, ok := lgc.mutation.Info(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldInfo, + }) + _node.Info = value + } + if value, ok := lgc.mutation.Level(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + _node.Level = value + } + if nodes := lgc.mutation.LinUserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := lgc.mutation.LinPermissionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinGroupCreateBulk is the builder for creating many LinGroup entities in bulk. +type LinGroupCreateBulk struct { + config + builders []*LinGroupCreate +} + +// Save creates the LinGroup entities in the database. +func (lgcb *LinGroupCreateBulk) Save(ctx context.Context) ([]*LinGroup, error) { + specs := make([]*sqlgraph.CreateSpec, len(lgcb.builders)) + nodes := make([]*LinGroup, len(lgcb.builders)) + mutators := make([]Mutator, len(lgcb.builders)) + for i := range lgcb.builders { + func(i int, root context.Context) { + builder := lgcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lgcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lgcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lgcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lgcb *LinGroupCreateBulk) SaveX(ctx context.Context) []*LinGroup { + v, err := lgcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lgcb *LinGroupCreateBulk) Exec(ctx context.Context) error { + _, err := lgcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgcb *LinGroupCreateBulk) ExecX(ctx context.Context) { + if err := lgcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/lingroup_delete.go b/internal/data/model/lingroup_delete.go new file mode 100644 index 0000000..5e6e856 --- /dev/null +++ b/internal/data/model/lingroup_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupDelete is the builder for deleting a LinGroup entity. +type LinGroupDelete struct { + config + hooks []Hook + mutation *LinGroupMutation +} + +// Where appends a list predicates to the LinGroupDelete builder. +func (lgd *LinGroupDelete) Where(ps ...predicate.LinGroup) *LinGroupDelete { + lgd.mutation.Where(ps...) + return lgd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lgd *LinGroupDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lgd.hooks) == 0 { + affected, err = lgd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgd.mutation = mutation + affected, err = lgd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lgd.hooks) - 1; i >= 0; i-- { + if lgd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgd *LinGroupDelete) ExecX(ctx context.Context) int { + n, err := lgd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lgd *LinGroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + if ps := lgd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lgd.driver, _spec) +} + +// LinGroupDeleteOne is the builder for deleting a single LinGroup entity. +type LinGroupDeleteOne struct { + lgd *LinGroupDelete +} + +// Exec executes the deletion query. +func (lgdo *LinGroupDeleteOne) Exec(ctx context.Context) error { + n, err := lgdo.lgd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{lingroup.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgdo *LinGroupDeleteOne) ExecX(ctx context.Context) { + lgdo.lgd.ExecX(ctx) +} diff --git a/internal/data/model/lingroup_query.go b/internal/data/model/lingroup_query.go new file mode 100644 index 0000000..b9e8d72 --- /dev/null +++ b/internal/data/model/lingroup_query.go @@ -0,0 +1,1170 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupQuery is the builder for querying LinGroup entities. +type LinGroupQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinGroup + // eager-loading edges. + withLinUser *LinUserQuery + withLinPermission *LinPermissionQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinGroupQuery builder. +func (lgq *LinGroupQuery) Where(ps ...predicate.LinGroup) *LinGroupQuery { + lgq.predicates = append(lgq.predicates, ps...) + return lgq +} + +// Limit adds a limit step to the query. +func (lgq *LinGroupQuery) Limit(limit int) *LinGroupQuery { + lgq.limit = &limit + return lgq +} + +// Offset adds an offset step to the query. +func (lgq *LinGroupQuery) Offset(offset int) *LinGroupQuery { + lgq.offset = &offset + return lgq +} + +// 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 (lgq *LinGroupQuery) Unique(unique bool) *LinGroupQuery { + lgq.unique = &unique + return lgq +} + +// Order adds an order step to the query. +func (lgq *LinGroupQuery) Order(o ...OrderFunc) *LinGroupQuery { + lgq.order = append(lgq.order, o...) + return lgq +} + +// QueryLinUser chains the current query on the "lin_user" edge. +func (lgq *LinGroupQuery) QueryLinUser() *LinUserQuery { + query := &LinUserQuery{config: lgq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lgq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, selector), + sqlgraph.To(linuser.Table, linuser.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, lingroup.LinUserTable, lingroup.LinUserPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lgq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryLinPermission chains the current query on the "lin_permission" edge. +func (lgq *LinGroupQuery) QueryLinPermission() *LinPermissionQuery { + query := &LinPermissionQuery{config: lgq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lgq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, selector), + sqlgraph.To(linpermission.Table, linpermission.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, lingroup.LinPermissionTable, lingroup.LinPermissionPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lgq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LinGroup entity from the query. +// Returns a *NotFoundError when no LinGroup was found. +func (lgq *LinGroupQuery) First(ctx context.Context) (*LinGroup, error) { + nodes, err := lgq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{lingroup.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lgq *LinGroupQuery) FirstX(ctx context.Context) *LinGroup { + node, err := lgq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinGroup ID from the query. +// Returns a *NotFoundError when no LinGroup ID was found. +func (lgq *LinGroupQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{lingroup.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lgq *LinGroupQuery) FirstIDX(ctx context.Context) int { + id, err := lgq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinGroup entity from the query. +// Returns a *NotFoundError when no LinGroup was found. +func (lgq *LinGroupQuery) Last(ctx context.Context) (*LinGroup, error) { + nodes, err := lgq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{lingroup.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lgq *LinGroupQuery) LastX(ctx context.Context) *LinGroup { + node, err := lgq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinGroup ID from the query. +// Returns a *NotFoundError when no LinGroup ID was found. +func (lgq *LinGroupQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{lingroup.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lgq *LinGroupQuery) LastIDX(ctx context.Context) int { + id, err := lgq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinGroup entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinGroup entity is not found. +// Returns a *NotFoundError when no LinGroup entities are found. +func (lgq *LinGroupQuery) Only(ctx context.Context) (*LinGroup, error) { + nodes, err := lgq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{lingroup.Label} + default: + return nil, &NotSingularError{lingroup.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lgq *LinGroupQuery) OnlyX(ctx context.Context) *LinGroup { + node, err := lgq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinGroup ID in the query. +// Returns a *NotSingularError when exactly one LinGroup ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lgq *LinGroupQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = &NotSingularError{lingroup.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lgq *LinGroupQuery) OnlyIDX(ctx context.Context) int { + id, err := lgq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinGroups. +func (lgq *LinGroupQuery) All(ctx context.Context) ([]*LinGroup, error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + return lgq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lgq *LinGroupQuery) AllX(ctx context.Context) []*LinGroup { + nodes, err := lgq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinGroup IDs. +func (lgq *LinGroupQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lgq.Select(lingroup.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lgq *LinGroupQuery) IDsX(ctx context.Context) []int { + ids, err := lgq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lgq *LinGroupQuery) Count(ctx context.Context) (int, error) { + if err := lgq.prepareQuery(ctx); err != nil { + return 0, err + } + return lgq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lgq *LinGroupQuery) CountX(ctx context.Context) int { + count, err := lgq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lgq *LinGroupQuery) Exist(ctx context.Context) (bool, error) { + if err := lgq.prepareQuery(ctx); err != nil { + return false, err + } + return lgq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lgq *LinGroupQuery) ExistX(ctx context.Context) bool { + exist, err := lgq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinGroupQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lgq *LinGroupQuery) Clone() *LinGroupQuery { + if lgq == nil { + return nil + } + return &LinGroupQuery{ + config: lgq.config, + limit: lgq.limit, + offset: lgq.offset, + order: append([]OrderFunc{}, lgq.order...), + predicates: append([]predicate.LinGroup{}, lgq.predicates...), + withLinUser: lgq.withLinUser.Clone(), + withLinPermission: lgq.withLinPermission.Clone(), + // clone intermediate query. + sql: lgq.sql.Clone(), + path: lgq.path, + } +} + +// WithLinUser tells the query-builder to eager-load the nodes that are connected to +// the "lin_user" edge. The optional arguments are used to configure the query builder of the edge. +func (lgq *LinGroupQuery) WithLinUser(opts ...func(*LinUserQuery)) *LinGroupQuery { + query := &LinUserQuery{config: lgq.config} + for _, opt := range opts { + opt(query) + } + lgq.withLinUser = query + return lgq +} + +// WithLinPermission tells the query-builder to eager-load the nodes that are connected to +// the "lin_permission" edge. The optional arguments are used to configure the query builder of the edge. +func (lgq *LinGroupQuery) WithLinPermission(opts ...func(*LinPermissionQuery)) *LinGroupQuery { + query := &LinPermissionQuery{config: lgq.config} + for _, opt := range opts { + opt(query) + } + lgq.withLinPermission = query + return lgq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinGroup.Query(). +// GroupBy(lingroup.FieldName). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lgq *LinGroupQuery) GroupBy(field string, fields ...string) *LinGroupGroupBy { + group := &LinGroupGroupBy{config: lgq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + return lgq.sqlQuery(ctx), nil + } + return group +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.LinGroup.Query(). +// Select(lingroup.FieldName). +// Scan(ctx, &v) +// +func (lgq *LinGroupQuery) Select(fields ...string) *LinGroupSelect { + lgq.fields = append(lgq.fields, fields...) + return &LinGroupSelect{LinGroupQuery: lgq} +} + +func (lgq *LinGroupQuery) prepareQuery(ctx context.Context) error { + for _, f := range lgq.fields { + if !lingroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lgq.path != nil { + prev, err := lgq.path(ctx) + if err != nil { + return err + } + lgq.sql = prev + } + return nil +} + +func (lgq *LinGroupQuery) sqlAll(ctx context.Context) ([]*LinGroup, error) { + var ( + nodes = []*LinGroup{} + _spec = lgq.querySpec() + loadedTypes = [2]bool{ + lgq.withLinUser != nil, + lgq.withLinPermission != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinGroup{config: lgq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lgq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := lgq.withLinUser; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinGroup, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinUser = []*LinUser{} + } + var ( + edgeids []int + edges = make(map[int][]*LinGroup) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(lingroup.LinUserPrimaryKey[0], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, lgq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_user": %w`, err) + } + query.Where(linuser.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_user" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinUser = append(nodes[i].Edges.LinUser, n) + } + } + } + + if query := lgq.withLinPermission; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinGroup, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinPermission = []*LinPermission{} + } + var ( + edgeids []int + edges = make(map[int][]*LinGroup) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(lingroup.LinPermissionPrimaryKey[1], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, lgq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_permission": %w`, err) + } + query.Where(linpermission.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_permission" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinPermission = append(nodes[i].Edges.LinPermission, n) + } + } + } + + return nodes, nil +} + +func (lgq *LinGroupQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lgq.querySpec() + return sqlgraph.CountNodes(ctx, lgq.driver, _spec) +} + +func (lgq *LinGroupQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lgq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lgq *LinGroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + Columns: lingroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + From: lgq.sql, + Unique: true, + } + if unique := lgq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lgq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, lingroup.FieldID) + for i := range fields { + if fields[i] != lingroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lgq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lgq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lgq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lgq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lgq *LinGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lgq.driver.Dialect()) + t1 := builder.Table(lingroup.Table) + columns := lgq.fields + if len(columns) == 0 { + columns = lingroup.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lgq.sql != nil { + selector = lgq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lgq.predicates { + p(selector) + } + for _, p := range lgq.order { + p(selector) + } + if offset := lgq.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 := lgq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinGroupGroupBy is the group-by builder for LinGroup entities. +type LinGroupGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lggb *LinGroupGroupBy) Aggregate(fns ...AggregateFunc) *LinGroupGroupBy { + lggb.fns = append(lggb.fns, fns...) + return lggb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lggb *LinGroupGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lggb.path(ctx) + if err != nil { + return err + } + lggb.sql = query + return lggb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lggb *LinGroupGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lggb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lggb *LinGroupGroupBy) StringsX(ctx context.Context) []string { + v, err := lggb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lggb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lggb *LinGroupGroupBy) StringX(ctx context.Context) string { + v, err := lggb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lggb *LinGroupGroupBy) IntsX(ctx context.Context) []int { + v, err := lggb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lggb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lggb *LinGroupGroupBy) IntX(ctx context.Context) int { + v, err := lggb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lggb *LinGroupGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lggb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lggb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lggb *LinGroupGroupBy) Float64X(ctx context.Context) float64 { + v, err := lggb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lggb *LinGroupGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lggb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lggb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lggb *LinGroupGroupBy) BoolX(ctx context.Context) bool { + v, err := lggb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lggb *LinGroupGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lggb.fields { + if !lingroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lggb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lggb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lggb *LinGroupGroupBy) sqlQuery() *sql.Selector { + selector := lggb.sql.Select() + aggregation := make([]string, 0, len(lggb.fns)) + for _, fn := range lggb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lggb.fields)+len(lggb.fns)) + for _, f := range lggb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lggb.fields...)...) +} + +// LinGroupSelect is the builder for selecting fields of LinGroup entities. +type LinGroupSelect struct { + *LinGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lgs *LinGroupSelect) Scan(ctx context.Context, v interface{}) error { + if err := lgs.prepareQuery(ctx); err != nil { + return err + } + lgs.sql = lgs.LinGroupQuery.sqlQuery(ctx) + return lgs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lgs *LinGroupSelect) ScanX(ctx context.Context, v interface{}) { + if err := lgs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Strings(ctx context.Context) ([]string, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lgs *LinGroupSelect) StringsX(ctx context.Context) []string { + v, err := lgs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lgs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lgs *LinGroupSelect) StringX(ctx context.Context) string { + v, err := lgs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Ints(ctx context.Context) ([]int, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lgs *LinGroupSelect) IntsX(ctx context.Context) []int { + v, err := lgs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lgs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lgs *LinGroupSelect) IntX(ctx context.Context) int { + v, err := lgs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lgs *LinGroupSelect) Float64sX(ctx context.Context) []float64 { + v, err := lgs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lgs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lgs *LinGroupSelect) Float64X(ctx context.Context) float64 { + v, err := lgs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lgs *LinGroupSelect) BoolsX(ctx context.Context) []bool { + v, err := lgs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lgs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lgs *LinGroupSelect) BoolX(ctx context.Context) bool { + v, err := lgs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lgs *LinGroupSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lgs.sql.Query() + if err := lgs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/lingroup_update.go b/internal/data/model/lingroup_update.go new file mode 100644 index 0000000..09bd286 --- /dev/null +++ b/internal/data/model/lingroup_update.go @@ -0,0 +1,706 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupUpdate is the builder for updating LinGroup entities. +type LinGroupUpdate struct { + config + hooks []Hook + mutation *LinGroupMutation +} + +// Where appends a list predicates to the LinGroupUpdate builder. +func (lgu *LinGroupUpdate) Where(ps ...predicate.LinGroup) *LinGroupUpdate { + lgu.mutation.Where(ps...) + return lgu +} + +// SetName sets the "name" field. +func (lgu *LinGroupUpdate) SetName(s string) *LinGroupUpdate { + lgu.mutation.SetName(s) + return lgu +} + +// SetInfo sets the "info" field. +func (lgu *LinGroupUpdate) SetInfo(s string) *LinGroupUpdate { + lgu.mutation.SetInfo(s) + return lgu +} + +// SetLevel sets the "level" field. +func (lgu *LinGroupUpdate) SetLevel(i int8) *LinGroupUpdate { + lgu.mutation.ResetLevel() + lgu.mutation.SetLevel(i) + return lgu +} + +// AddLevel adds i to the "level" field. +func (lgu *LinGroupUpdate) AddLevel(i int8) *LinGroupUpdate { + lgu.mutation.AddLevel(i) + return lgu +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. +func (lgu *LinGroupUpdate) AddLinUserIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.AddLinUserIDs(ids...) + return lgu +} + +// AddLinUser adds the "lin_user" edges to the LinUser entity. +func (lgu *LinGroupUpdate) AddLinUser(l ...*LinUser) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.AddLinUserIDs(ids...) +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. +func (lgu *LinGroupUpdate) AddLinPermissionIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.AddLinPermissionIDs(ids...) + return lgu +} + +// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. +func (lgu *LinGroupUpdate) AddLinPermission(l ...*LinPermission) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.AddLinPermissionIDs(ids...) +} + +// Mutation returns the LinGroupMutation object of the builder. +func (lgu *LinGroupUpdate) Mutation() *LinGroupMutation { + return lgu.mutation +} + +// ClearLinUser clears all "lin_user" edges to the LinUser entity. +func (lgu *LinGroupUpdate) ClearLinUser() *LinGroupUpdate { + lgu.mutation.ClearLinUser() + return lgu +} + +// RemoveLinUserIDs removes the "lin_user" edge to LinUser entities by IDs. +func (lgu *LinGroupUpdate) RemoveLinUserIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.RemoveLinUserIDs(ids...) + return lgu +} + +// RemoveLinUser removes "lin_user" edges to LinUser entities. +func (lgu *LinGroupUpdate) RemoveLinUser(l ...*LinUser) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.RemoveLinUserIDs(ids...) +} + +// ClearLinPermission clears all "lin_permission" edges to the LinPermission entity. +func (lgu *LinGroupUpdate) ClearLinPermission() *LinGroupUpdate { + lgu.mutation.ClearLinPermission() + return lgu +} + +// RemoveLinPermissionIDs removes the "lin_permission" edge to LinPermission entities by IDs. +func (lgu *LinGroupUpdate) RemoveLinPermissionIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.RemoveLinPermissionIDs(ids...) + return lgu +} + +// RemoveLinPermission removes "lin_permission" edges to LinPermission entities. +func (lgu *LinGroupUpdate) RemoveLinPermission(l ...*LinPermission) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.RemoveLinPermissionIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lgu *LinGroupUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lgu.hooks) == 0 { + affected, err = lgu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgu.mutation = mutation + affected, err = lgu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lgu.hooks) - 1; i >= 0; i-- { + if lgu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lgu *LinGroupUpdate) SaveX(ctx context.Context) int { + affected, err := lgu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lgu *LinGroupUpdate) Exec(ctx context.Context) error { + _, err := lgu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgu *LinGroupUpdate) ExecX(ctx context.Context) { + if err := lgu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lgu *LinGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + Columns: lingroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + if ps := lgu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lgu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldName, + }) + } + if value, ok := lgu.mutation.Info(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldInfo, + }) + } + if value, ok := lgu.mutation.Level(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if value, ok := lgu.mutation.AddedLevel(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if lgu.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.RemovedLinUserIDs(); len(nodes) > 0 && !lgu.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.LinUserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if lgu.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.RemovedLinPermissionIDs(); len(nodes) > 0 && !lgu.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.LinPermissionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, lgu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{lingroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinGroupUpdateOne is the builder for updating a single LinGroup entity. +type LinGroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinGroupMutation +} + +// SetName sets the "name" field. +func (lguo *LinGroupUpdateOne) SetName(s string) *LinGroupUpdateOne { + lguo.mutation.SetName(s) + return lguo +} + +// SetInfo sets the "info" field. +func (lguo *LinGroupUpdateOne) SetInfo(s string) *LinGroupUpdateOne { + lguo.mutation.SetInfo(s) + return lguo +} + +// SetLevel sets the "level" field. +func (lguo *LinGroupUpdateOne) SetLevel(i int8) *LinGroupUpdateOne { + lguo.mutation.ResetLevel() + lguo.mutation.SetLevel(i) + return lguo +} + +// AddLevel adds i to the "level" field. +func (lguo *LinGroupUpdateOne) AddLevel(i int8) *LinGroupUpdateOne { + lguo.mutation.AddLevel(i) + return lguo +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. +func (lguo *LinGroupUpdateOne) AddLinUserIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.AddLinUserIDs(ids...) + return lguo +} + +// AddLinUser adds the "lin_user" edges to the LinUser entity. +func (lguo *LinGroupUpdateOne) AddLinUser(l ...*LinUser) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.AddLinUserIDs(ids...) +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. +func (lguo *LinGroupUpdateOne) AddLinPermissionIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.AddLinPermissionIDs(ids...) + return lguo +} + +// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. +func (lguo *LinGroupUpdateOne) AddLinPermission(l ...*LinPermission) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.AddLinPermissionIDs(ids...) +} + +// Mutation returns the LinGroupMutation object of the builder. +func (lguo *LinGroupUpdateOne) Mutation() *LinGroupMutation { + return lguo.mutation +} + +// ClearLinUser clears all "lin_user" edges to the LinUser entity. +func (lguo *LinGroupUpdateOne) ClearLinUser() *LinGroupUpdateOne { + lguo.mutation.ClearLinUser() + return lguo +} + +// RemoveLinUserIDs removes the "lin_user" edge to LinUser entities by IDs. +func (lguo *LinGroupUpdateOne) RemoveLinUserIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.RemoveLinUserIDs(ids...) + return lguo +} + +// RemoveLinUser removes "lin_user" edges to LinUser entities. +func (lguo *LinGroupUpdateOne) RemoveLinUser(l ...*LinUser) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.RemoveLinUserIDs(ids...) +} + +// ClearLinPermission clears all "lin_permission" edges to the LinPermission entity. +func (lguo *LinGroupUpdateOne) ClearLinPermission() *LinGroupUpdateOne { + lguo.mutation.ClearLinPermission() + return lguo +} + +// RemoveLinPermissionIDs removes the "lin_permission" edge to LinPermission entities by IDs. +func (lguo *LinGroupUpdateOne) RemoveLinPermissionIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.RemoveLinPermissionIDs(ids...) + return lguo +} + +// RemoveLinPermission removes "lin_permission" edges to LinPermission entities. +func (lguo *LinGroupUpdateOne) RemoveLinPermission(l ...*LinPermission) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.RemoveLinPermissionIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lguo *LinGroupUpdateOne) Select(field string, fields ...string) *LinGroupUpdateOne { + lguo.fields = append([]string{field}, fields...) + return lguo +} + +// Save executes the query and returns the updated LinGroup entity. +func (lguo *LinGroupUpdateOne) Save(ctx context.Context) (*LinGroup, error) { + var ( + err error + node *LinGroup + ) + if len(lguo.hooks) == 0 { + node, err = lguo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lguo.mutation = mutation + node, err = lguo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lguo.hooks) - 1; i >= 0; i-- { + if lguo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lguo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lguo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lguo *LinGroupUpdateOne) SaveX(ctx context.Context) *LinGroup { + node, err := lguo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lguo *LinGroupUpdateOne) Exec(ctx context.Context) error { + _, err := lguo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lguo *LinGroupUpdateOne) ExecX(ctx context.Context) { + if err := lguo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lguo *LinGroupUpdateOne) sqlSave(ctx context.Context) (_node *LinGroup, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + Columns: lingroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + id, ok := lguo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinGroup.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lguo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, lingroup.FieldID) + for _, f := range fields { + if !lingroup.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != lingroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lguo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lguo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldName, + }) + } + if value, ok := lguo.mutation.Info(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldInfo, + }) + } + if value, ok := lguo.mutation.Level(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if value, ok := lguo.mutation.AddedLevel(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if lguo.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.RemovedLinUserIDs(); len(nodes) > 0 && !lguo.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.LinUserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if lguo.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.RemovedLinPermissionIDs(); len(nodes) > 0 && !lguo.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.LinPermissionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LinGroup{config: lguo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lguo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{lingroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/lingrouppermission.go b/internal/data/model/lingrouppermission.go new file mode 100644 index 0000000..2bd8941 --- /dev/null +++ b/internal/data/model/lingrouppermission.go @@ -0,0 +1,109 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/lingrouppermission" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinGroupPermission is the model entity for the LinGroupPermission schema. +type LinGroupPermission struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // GroupID holds the value of the "group_id" field. + // 分组id + GroupID int `json:"group_id,omitempty"` + // PermissionID holds the value of the "permission_id" field. + // 权限id + PermissionID int `json:"permission_id,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinGroupPermission) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case lingrouppermission.FieldID, lingrouppermission.FieldGroupID, lingrouppermission.FieldPermissionID: + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type LinGroupPermission", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinGroupPermission fields. +func (lgp *LinGroupPermission) assignValues(columns []string, values []interface{}) 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 lingrouppermission.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lgp.ID = int(value.Int64) + case lingrouppermission.FieldGroupID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field group_id", values[i]) + } else if value.Valid { + lgp.GroupID = int(value.Int64) + } + case lingrouppermission.FieldPermissionID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field permission_id", values[i]) + } else if value.Valid { + lgp.PermissionID = int(value.Int64) + } + } + } + return nil +} + +// Update returns a builder for updating this LinGroupPermission. +// Note that you need to call LinGroupPermission.Unwrap() before calling this method if this LinGroupPermission +// was returned from a transaction, and the transaction was committed or rolled back. +func (lgp *LinGroupPermission) Update() *LinGroupPermissionUpdateOne { + return (&LinGroupPermissionClient{config: lgp.config}).UpdateOne(lgp) +} + +// Unwrap unwraps the LinGroupPermission 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 (lgp *LinGroupPermission) Unwrap() *LinGroupPermission { + tx, ok := lgp.config.driver.(*txDriver) + if !ok { + panic("model: LinGroupPermission is not a transactional entity") + } + lgp.config.driver = tx.drv + return lgp +} + +// String implements the fmt.Stringer. +func (lgp *LinGroupPermission) String() string { + var builder strings.Builder + builder.WriteString("LinGroupPermission(") + builder.WriteString(fmt.Sprintf("id=%v", lgp.ID)) + builder.WriteString(", group_id=") + builder.WriteString(fmt.Sprintf("%v", lgp.GroupID)) + builder.WriteString(", permission_id=") + builder.WriteString(fmt.Sprintf("%v", lgp.PermissionID)) + builder.WriteByte(')') + return builder.String() +} + +// LinGroupPermissions is a parsable slice of LinGroupPermission. +type LinGroupPermissions []*LinGroupPermission + +func (lgp LinGroupPermissions) config(cfg config) { + for _i := range lgp { + lgp[_i].config = cfg + } +} diff --git a/internal/data/model/lingrouppermission/lingrouppermission.go b/internal/data/model/lingrouppermission/lingrouppermission.go new file mode 100644 index 0000000..9257779 --- /dev/null +++ b/internal/data/model/lingrouppermission/lingrouppermission.go @@ -0,0 +1,33 @@ +// Code generated by entc, DO NOT EDIT. + +package lingrouppermission + +const ( + // Label holds the string label denoting the lingrouppermission type in the database. + Label = "lin_group_permission" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldGroupID holds the string denoting the group_id field in the database. + FieldGroupID = "group_id" + // FieldPermissionID holds the string denoting the permission_id field in the database. + FieldPermissionID = "permission_id" + // Table holds the table name of the lingrouppermission in the database. + Table = "lin_group_permission" +) + +// Columns holds all SQL columns for lingrouppermission fields. +var Columns = []string{ + FieldID, + FieldGroupID, + FieldPermissionID, +} + +// 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 +} diff --git a/internal/data/model/lingrouppermission/where.go b/internal/data/model/lingrouppermission/where.go new file mode 100644 index 0000000..9b1496a --- /dev/null +++ b/internal/data/model/lingrouppermission/where.go @@ -0,0 +1,290 @@ +// Code generated by entc, DO NOT EDIT. + +package lingrouppermission + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ. +func GroupID(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldGroupID), v)) + }) +} + +// PermissionID applies equality check predicate on the "permission_id" field. It's identical to PermissionIDEQ. +func PermissionID(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPermissionID), v)) + }) +} + +// GroupIDEQ applies the EQ predicate on the "group_id" field. +func GroupIDEQ(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldGroupID), v)) + }) +} + +// GroupIDNEQ applies the NEQ predicate on the "group_id" field. +func GroupIDNEQ(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldGroupID), v)) + }) +} + +// GroupIDIn applies the In predicate on the "group_id" field. +func GroupIDIn(vs ...int) predicate.LinGroupPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroupPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldGroupID), v...)) + }) +} + +// GroupIDNotIn applies the NotIn predicate on the "group_id" field. +func GroupIDNotIn(vs ...int) predicate.LinGroupPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroupPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldGroupID), v...)) + }) +} + +// GroupIDGT applies the GT predicate on the "group_id" field. +func GroupIDGT(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldGroupID), v)) + }) +} + +// GroupIDGTE applies the GTE predicate on the "group_id" field. +func GroupIDGTE(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldGroupID), v)) + }) +} + +// GroupIDLT applies the LT predicate on the "group_id" field. +func GroupIDLT(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldGroupID), v)) + }) +} + +// GroupIDLTE applies the LTE predicate on the "group_id" field. +func GroupIDLTE(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldGroupID), v)) + }) +} + +// PermissionIDEQ applies the EQ predicate on the "permission_id" field. +func PermissionIDEQ(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPermissionID), v)) + }) +} + +// PermissionIDNEQ applies the NEQ predicate on the "permission_id" field. +func PermissionIDNEQ(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPermissionID), v)) + }) +} + +// PermissionIDIn applies the In predicate on the "permission_id" field. +func PermissionIDIn(vs ...int) predicate.LinGroupPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroupPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPermissionID), v...)) + }) +} + +// PermissionIDNotIn applies the NotIn predicate on the "permission_id" field. +func PermissionIDNotIn(vs ...int) predicate.LinGroupPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroupPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPermissionID), v...)) + }) +} + +// PermissionIDGT applies the GT predicate on the "permission_id" field. +func PermissionIDGT(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPermissionID), v)) + }) +} + +// PermissionIDGTE applies the GTE predicate on the "permission_id" field. +func PermissionIDGTE(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPermissionID), v)) + }) +} + +// PermissionIDLT applies the LT predicate on the "permission_id" field. +func PermissionIDLT(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPermissionID), v)) + }) +} + +// PermissionIDLTE applies the LTE predicate on the "permission_id" field. +func PermissionIDLTE(v int) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPermissionID), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinGroupPermission) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinGroupPermission) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinGroupPermission) predicate.LinGroupPermission { + return predicate.LinGroupPermission(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/lingrouppermission_create.go b/internal/data/model/lingrouppermission_create.go new file mode 100644 index 0000000..25caf8f --- /dev/null +++ b/internal/data/model/lingrouppermission_create.go @@ -0,0 +1,237 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingrouppermission" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupPermissionCreate is the builder for creating a LinGroupPermission entity. +type LinGroupPermissionCreate struct { + config + mutation *LinGroupPermissionMutation + hooks []Hook +} + +// SetGroupID sets the "group_id" field. +func (lgpc *LinGroupPermissionCreate) SetGroupID(i int) *LinGroupPermissionCreate { + lgpc.mutation.SetGroupID(i) + return lgpc +} + +// SetPermissionID sets the "permission_id" field. +func (lgpc *LinGroupPermissionCreate) SetPermissionID(i int) *LinGroupPermissionCreate { + lgpc.mutation.SetPermissionID(i) + return lgpc +} + +// Mutation returns the LinGroupPermissionMutation object of the builder. +func (lgpc *LinGroupPermissionCreate) Mutation() *LinGroupPermissionMutation { + return lgpc.mutation +} + +// Save creates the LinGroupPermission in the database. +func (lgpc *LinGroupPermissionCreate) Save(ctx context.Context) (*LinGroupPermission, error) { + var ( + err error + node *LinGroupPermission + ) + if len(lgpc.hooks) == 0 { + if err = lgpc.check(); err != nil { + return nil, err + } + node, err = lgpc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lgpc.check(); err != nil { + return nil, err + } + lgpc.mutation = mutation + if node, err = lgpc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lgpc.hooks) - 1; i >= 0; i-- { + if lgpc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgpc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgpc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lgpc *LinGroupPermissionCreate) SaveX(ctx context.Context) *LinGroupPermission { + v, err := lgpc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lgpc *LinGroupPermissionCreate) Exec(ctx context.Context) error { + _, err := lgpc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgpc *LinGroupPermissionCreate) ExecX(ctx context.Context) { + if err := lgpc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lgpc *LinGroupPermissionCreate) check() error { + if _, ok := lgpc.mutation.GroupID(); !ok { + return &ValidationError{Name: "group_id", err: errors.New(`model: missing required field "group_id"`)} + } + if _, ok := lgpc.mutation.PermissionID(); !ok { + return &ValidationError{Name: "permission_id", err: errors.New(`model: missing required field "permission_id"`)} + } + return nil +} + +func (lgpc *LinGroupPermissionCreate) sqlSave(ctx context.Context) (*LinGroupPermission, error) { + _node, _spec := lgpc.createSpec() + if err := sqlgraph.CreateNode(ctx, lgpc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lgpc *LinGroupPermissionCreate) createSpec() (*LinGroupPermission, *sqlgraph.CreateSpec) { + var ( + _node = &LinGroupPermission{config: lgpc.config} + _spec = &sqlgraph.CreateSpec{ + Table: lingrouppermission.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingrouppermission.FieldID, + }, + } + ) + if value, ok := lgpc.mutation.GroupID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldGroupID, + }) + _node.GroupID = value + } + if value, ok := lgpc.mutation.PermissionID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldPermissionID, + }) + _node.PermissionID = value + } + return _node, _spec +} + +// LinGroupPermissionCreateBulk is the builder for creating many LinGroupPermission entities in bulk. +type LinGroupPermissionCreateBulk struct { + config + builders []*LinGroupPermissionCreate +} + +// Save creates the LinGroupPermission entities in the database. +func (lgpcb *LinGroupPermissionCreateBulk) Save(ctx context.Context) ([]*LinGroupPermission, error) { + specs := make([]*sqlgraph.CreateSpec, len(lgpcb.builders)) + nodes := make([]*LinGroupPermission, len(lgpcb.builders)) + mutators := make([]Mutator, len(lgpcb.builders)) + for i := range lgpcb.builders { + func(i int, root context.Context) { + builder := lgpcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lgpcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lgpcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lgpcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lgpcb *LinGroupPermissionCreateBulk) SaveX(ctx context.Context) []*LinGroupPermission { + v, err := lgpcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lgpcb *LinGroupPermissionCreateBulk) Exec(ctx context.Context) error { + _, err := lgpcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgpcb *LinGroupPermissionCreateBulk) ExecX(ctx context.Context) { + if err := lgpcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/lingrouppermission_delete.go b/internal/data/model/lingrouppermission_delete.go new file mode 100644 index 0000000..ec23705 --- /dev/null +++ b/internal/data/model/lingrouppermission_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupPermissionDelete is the builder for deleting a LinGroupPermission entity. +type LinGroupPermissionDelete struct { + config + hooks []Hook + mutation *LinGroupPermissionMutation +} + +// Where appends a list predicates to the LinGroupPermissionDelete builder. +func (lgpd *LinGroupPermissionDelete) Where(ps ...predicate.LinGroupPermission) *LinGroupPermissionDelete { + lgpd.mutation.Where(ps...) + return lgpd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lgpd *LinGroupPermissionDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lgpd.hooks) == 0 { + affected, err = lgpd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgpd.mutation = mutation + affected, err = lgpd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lgpd.hooks) - 1; i >= 0; i-- { + if lgpd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgpd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgpd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgpd *LinGroupPermissionDelete) ExecX(ctx context.Context) int { + n, err := lgpd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lgpd *LinGroupPermissionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingrouppermission.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingrouppermission.FieldID, + }, + }, + } + if ps := lgpd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lgpd.driver, _spec) +} + +// LinGroupPermissionDeleteOne is the builder for deleting a single LinGroupPermission entity. +type LinGroupPermissionDeleteOne struct { + lgpd *LinGroupPermissionDelete +} + +// Exec executes the deletion query. +func (lgpdo *LinGroupPermissionDeleteOne) Exec(ctx context.Context) error { + n, err := lgpdo.lgpd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{lingrouppermission.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgpdo *LinGroupPermissionDeleteOne) ExecX(ctx context.Context) { + lgpdo.lgpd.ExecX(ctx) +} diff --git a/internal/data/model/lingrouppermission_query.go b/internal/data/model/lingrouppermission_query.go new file mode 100644 index 0000000..abfdc86 --- /dev/null +++ b/internal/data/model/lingrouppermission_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupPermissionQuery is the builder for querying LinGroupPermission entities. +type LinGroupPermissionQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinGroupPermission + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinGroupPermissionQuery builder. +func (lgpq *LinGroupPermissionQuery) Where(ps ...predicate.LinGroupPermission) *LinGroupPermissionQuery { + lgpq.predicates = append(lgpq.predicates, ps...) + return lgpq +} + +// Limit adds a limit step to the query. +func (lgpq *LinGroupPermissionQuery) Limit(limit int) *LinGroupPermissionQuery { + lgpq.limit = &limit + return lgpq +} + +// Offset adds an offset step to the query. +func (lgpq *LinGroupPermissionQuery) Offset(offset int) *LinGroupPermissionQuery { + lgpq.offset = &offset + return lgpq +} + +// 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 (lgpq *LinGroupPermissionQuery) Unique(unique bool) *LinGroupPermissionQuery { + lgpq.unique = &unique + return lgpq +} + +// Order adds an order step to the query. +func (lgpq *LinGroupPermissionQuery) Order(o ...OrderFunc) *LinGroupPermissionQuery { + lgpq.order = append(lgpq.order, o...) + return lgpq +} + +// First returns the first LinGroupPermission entity from the query. +// Returns a *NotFoundError when no LinGroupPermission was found. +func (lgpq *LinGroupPermissionQuery) First(ctx context.Context) (*LinGroupPermission, error) { + nodes, err := lgpq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{lingrouppermission.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) FirstX(ctx context.Context) *LinGroupPermission { + node, err := lgpq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinGroupPermission ID from the query. +// Returns a *NotFoundError when no LinGroupPermission ID was found. +func (lgpq *LinGroupPermissionQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgpq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{lingrouppermission.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) FirstIDX(ctx context.Context) int { + id, err := lgpq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinGroupPermission entity from the query. +// Returns a *NotFoundError when no LinGroupPermission was found. +func (lgpq *LinGroupPermissionQuery) Last(ctx context.Context) (*LinGroupPermission, error) { + nodes, err := lgpq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{lingrouppermission.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) LastX(ctx context.Context) *LinGroupPermission { + node, err := lgpq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinGroupPermission ID from the query. +// Returns a *NotFoundError when no LinGroupPermission ID was found. +func (lgpq *LinGroupPermissionQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgpq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{lingrouppermission.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) LastIDX(ctx context.Context) int { + id, err := lgpq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinGroupPermission entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinGroupPermission entity is not found. +// Returns a *NotFoundError when no LinGroupPermission entities are found. +func (lgpq *LinGroupPermissionQuery) Only(ctx context.Context) (*LinGroupPermission, error) { + nodes, err := lgpq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{lingrouppermission.Label} + default: + return nil, &NotSingularError{lingrouppermission.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) OnlyX(ctx context.Context) *LinGroupPermission { + node, err := lgpq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinGroupPermission ID in the query. +// Returns a *NotSingularError when exactly one LinGroupPermission ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lgpq *LinGroupPermissionQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgpq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = &NotSingularError{lingrouppermission.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) OnlyIDX(ctx context.Context) int { + id, err := lgpq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinGroupPermissions. +func (lgpq *LinGroupPermissionQuery) All(ctx context.Context) ([]*LinGroupPermission, error) { + if err := lgpq.prepareQuery(ctx); err != nil { + return nil, err + } + return lgpq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) AllX(ctx context.Context) []*LinGroupPermission { + nodes, err := lgpq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinGroupPermission IDs. +func (lgpq *LinGroupPermissionQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lgpq.Select(lingrouppermission.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) IDsX(ctx context.Context) []int { + ids, err := lgpq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lgpq *LinGroupPermissionQuery) Count(ctx context.Context) (int, error) { + if err := lgpq.prepareQuery(ctx); err != nil { + return 0, err + } + return lgpq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) CountX(ctx context.Context) int { + count, err := lgpq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lgpq *LinGroupPermissionQuery) Exist(ctx context.Context) (bool, error) { + if err := lgpq.prepareQuery(ctx); err != nil { + return false, err + } + return lgpq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lgpq *LinGroupPermissionQuery) ExistX(ctx context.Context) bool { + exist, err := lgpq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinGroupPermissionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lgpq *LinGroupPermissionQuery) Clone() *LinGroupPermissionQuery { + if lgpq == nil { + return nil + } + return &LinGroupPermissionQuery{ + config: lgpq.config, + limit: lgpq.limit, + offset: lgpq.offset, + order: append([]OrderFunc{}, lgpq.order...), + predicates: append([]predicate.LinGroupPermission{}, lgpq.predicates...), + // clone intermediate query. + sql: lgpq.sql.Clone(), + path: lgpq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// GroupID int `json:"group_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinGroupPermission.Query(). +// GroupBy(lingrouppermission.FieldGroupID). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lgpq *LinGroupPermissionQuery) GroupBy(field string, fields ...string) *LinGroupPermissionGroupBy { + group := &LinGroupPermissionGroupBy{config: lgpq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lgpq.prepareQuery(ctx); err != nil { + return nil, err + } + return lgpq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// GroupID int `json:"group_id,omitempty"` +// } +// +// client.LinGroupPermission.Query(). +// Select(lingrouppermission.FieldGroupID). +// Scan(ctx, &v) +// +func (lgpq *LinGroupPermissionQuery) Select(fields ...string) *LinGroupPermissionSelect { + lgpq.fields = append(lgpq.fields, fields...) + return &LinGroupPermissionSelect{LinGroupPermissionQuery: lgpq} +} + +func (lgpq *LinGroupPermissionQuery) prepareQuery(ctx context.Context) error { + for _, f := range lgpq.fields { + if !lingrouppermission.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lgpq.path != nil { + prev, err := lgpq.path(ctx) + if err != nil { + return err + } + lgpq.sql = prev + } + return nil +} + +func (lgpq *LinGroupPermissionQuery) sqlAll(ctx context.Context) ([]*LinGroupPermission, error) { + var ( + nodes = []*LinGroupPermission{} + _spec = lgpq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinGroupPermission{config: lgpq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lgpq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (lgpq *LinGroupPermissionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lgpq.querySpec() + return sqlgraph.CountNodes(ctx, lgpq.driver, _spec) +} + +func (lgpq *LinGroupPermissionQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lgpq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lgpq *LinGroupPermissionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingrouppermission.Table, + Columns: lingrouppermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingrouppermission.FieldID, + }, + }, + From: lgpq.sql, + Unique: true, + } + if unique := lgpq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lgpq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, lingrouppermission.FieldID) + for i := range fields { + if fields[i] != lingrouppermission.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lgpq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lgpq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lgpq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lgpq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lgpq *LinGroupPermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lgpq.driver.Dialect()) + t1 := builder.Table(lingrouppermission.Table) + columns := lgpq.fields + if len(columns) == 0 { + columns = lingrouppermission.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lgpq.sql != nil { + selector = lgpq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lgpq.predicates { + p(selector) + } + for _, p := range lgpq.order { + p(selector) + } + if offset := lgpq.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 := lgpq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinGroupPermissionGroupBy is the group-by builder for LinGroupPermission entities. +type LinGroupPermissionGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lgpgb *LinGroupPermissionGroupBy) Aggregate(fns ...AggregateFunc) *LinGroupPermissionGroupBy { + lgpgb.fns = append(lgpgb.fns, fns...) + return lgpgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lgpgb *LinGroupPermissionGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lgpgb.path(ctx) + if err != nil { + return err + } + lgpgb.sql = query + return lgpgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lgpgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lgpgb.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lgpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) StringsX(ctx context.Context) []string { + v, err := lgpgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lgpgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) StringX(ctx context.Context) string { + v, err := lgpgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lgpgb.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lgpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) IntsX(ctx context.Context) []int { + v, err := lgpgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lgpgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) IntX(ctx context.Context) int { + v, err := lgpgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lgpgb.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lgpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lgpgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lgpgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) Float64X(ctx context.Context) float64 { + v, err := lgpgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lgpgb.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lgpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lgpgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lgpgb *LinGroupPermissionGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lgpgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lgpgb *LinGroupPermissionGroupBy) BoolX(ctx context.Context) bool { + v, err := lgpgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lgpgb *LinGroupPermissionGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lgpgb.fields { + if !lingrouppermission.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lgpgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lgpgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lgpgb *LinGroupPermissionGroupBy) sqlQuery() *sql.Selector { + selector := lgpgb.sql.Select() + aggregation := make([]string, 0, len(lgpgb.fns)) + for _, fn := range lgpgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lgpgb.fields)+len(lgpgb.fns)) + for _, f := range lgpgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lgpgb.fields...)...) +} + +// LinGroupPermissionSelect is the builder for selecting fields of LinGroupPermission entities. +type LinGroupPermissionSelect struct { + *LinGroupPermissionQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lgps *LinGroupPermissionSelect) Scan(ctx context.Context, v interface{}) error { + if err := lgps.prepareQuery(ctx); err != nil { + return err + } + lgps.sql = lgps.LinGroupPermissionQuery.sqlQuery(ctx) + return lgps.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) ScanX(ctx context.Context, v interface{}) { + if err := lgps.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Strings(ctx context.Context) ([]string, error) { + if len(lgps.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lgps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) StringsX(ctx context.Context) []string { + v, err := lgps.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lgps.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) StringX(ctx context.Context) string { + v, err := lgps.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Ints(ctx context.Context) ([]int, error) { + if len(lgps.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lgps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) IntsX(ctx context.Context) []int { + v, err := lgps.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lgps.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) IntX(ctx context.Context) int { + v, err := lgps.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lgps.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lgps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) Float64sX(ctx context.Context) []float64 { + v, err := lgps.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lgps.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) Float64X(ctx context.Context) float64 { + v, err := lgps.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lgps.fields) > 1 { + return nil, errors.New("model: LinGroupPermissionSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lgps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) BoolsX(ctx context.Context) []bool { + v, err := lgps.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lgps *LinGroupPermissionSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lgps.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingrouppermission.Label} + default: + err = fmt.Errorf("model: LinGroupPermissionSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lgps *LinGroupPermissionSelect) BoolX(ctx context.Context) bool { + v, err := lgps.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lgps *LinGroupPermissionSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lgps.sql.Query() + if err := lgps.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/lingrouppermission_update.go b/internal/data/model/lingrouppermission_update.go new file mode 100644 index 0000000..36cc6d5 --- /dev/null +++ b/internal/data/model/lingrouppermission_update.go @@ -0,0 +1,346 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupPermissionUpdate is the builder for updating LinGroupPermission entities. +type LinGroupPermissionUpdate struct { + config + hooks []Hook + mutation *LinGroupPermissionMutation +} + +// Where appends a list predicates to the LinGroupPermissionUpdate builder. +func (lgpu *LinGroupPermissionUpdate) Where(ps ...predicate.LinGroupPermission) *LinGroupPermissionUpdate { + lgpu.mutation.Where(ps...) + return lgpu +} + +// SetGroupID sets the "group_id" field. +func (lgpu *LinGroupPermissionUpdate) SetGroupID(i int) *LinGroupPermissionUpdate { + lgpu.mutation.ResetGroupID() + lgpu.mutation.SetGroupID(i) + return lgpu +} + +// AddGroupID adds i to the "group_id" field. +func (lgpu *LinGroupPermissionUpdate) AddGroupID(i int) *LinGroupPermissionUpdate { + lgpu.mutation.AddGroupID(i) + return lgpu +} + +// SetPermissionID sets the "permission_id" field. +func (lgpu *LinGroupPermissionUpdate) SetPermissionID(i int) *LinGroupPermissionUpdate { + lgpu.mutation.ResetPermissionID() + lgpu.mutation.SetPermissionID(i) + return lgpu +} + +// AddPermissionID adds i to the "permission_id" field. +func (lgpu *LinGroupPermissionUpdate) AddPermissionID(i int) *LinGroupPermissionUpdate { + lgpu.mutation.AddPermissionID(i) + return lgpu +} + +// Mutation returns the LinGroupPermissionMutation object of the builder. +func (lgpu *LinGroupPermissionUpdate) Mutation() *LinGroupPermissionMutation { + return lgpu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lgpu *LinGroupPermissionUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lgpu.hooks) == 0 { + affected, err = lgpu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgpu.mutation = mutation + affected, err = lgpu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lgpu.hooks) - 1; i >= 0; i-- { + if lgpu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgpu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgpu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lgpu *LinGroupPermissionUpdate) SaveX(ctx context.Context) int { + affected, err := lgpu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lgpu *LinGroupPermissionUpdate) Exec(ctx context.Context) error { + _, err := lgpu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgpu *LinGroupPermissionUpdate) ExecX(ctx context.Context) { + if err := lgpu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lgpu *LinGroupPermissionUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingrouppermission.Table, + Columns: lingrouppermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingrouppermission.FieldID, + }, + }, + } + if ps := lgpu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lgpu.mutation.GroupID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldGroupID, + }) + } + if value, ok := lgpu.mutation.AddedGroupID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldGroupID, + }) + } + if value, ok := lgpu.mutation.PermissionID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldPermissionID, + }) + } + if value, ok := lgpu.mutation.AddedPermissionID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldPermissionID, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, lgpu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{lingrouppermission.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinGroupPermissionUpdateOne is the builder for updating a single LinGroupPermission entity. +type LinGroupPermissionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinGroupPermissionMutation +} + +// SetGroupID sets the "group_id" field. +func (lgpuo *LinGroupPermissionUpdateOne) SetGroupID(i int) *LinGroupPermissionUpdateOne { + lgpuo.mutation.ResetGroupID() + lgpuo.mutation.SetGroupID(i) + return lgpuo +} + +// AddGroupID adds i to the "group_id" field. +func (lgpuo *LinGroupPermissionUpdateOne) AddGroupID(i int) *LinGroupPermissionUpdateOne { + lgpuo.mutation.AddGroupID(i) + return lgpuo +} + +// SetPermissionID sets the "permission_id" field. +func (lgpuo *LinGroupPermissionUpdateOne) SetPermissionID(i int) *LinGroupPermissionUpdateOne { + lgpuo.mutation.ResetPermissionID() + lgpuo.mutation.SetPermissionID(i) + return lgpuo +} + +// AddPermissionID adds i to the "permission_id" field. +func (lgpuo *LinGroupPermissionUpdateOne) AddPermissionID(i int) *LinGroupPermissionUpdateOne { + lgpuo.mutation.AddPermissionID(i) + return lgpuo +} + +// Mutation returns the LinGroupPermissionMutation object of the builder. +func (lgpuo *LinGroupPermissionUpdateOne) Mutation() *LinGroupPermissionMutation { + return lgpuo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lgpuo *LinGroupPermissionUpdateOne) Select(field string, fields ...string) *LinGroupPermissionUpdateOne { + lgpuo.fields = append([]string{field}, fields...) + return lgpuo +} + +// Save executes the query and returns the updated LinGroupPermission entity. +func (lgpuo *LinGroupPermissionUpdateOne) Save(ctx context.Context) (*LinGroupPermission, error) { + var ( + err error + node *LinGroupPermission + ) + if len(lgpuo.hooks) == 0 { + node, err = lgpuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgpuo.mutation = mutation + node, err = lgpuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lgpuo.hooks) - 1; i >= 0; i-- { + if lgpuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgpuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgpuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lgpuo *LinGroupPermissionUpdateOne) SaveX(ctx context.Context) *LinGroupPermission { + node, err := lgpuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lgpuo *LinGroupPermissionUpdateOne) Exec(ctx context.Context) error { + _, err := lgpuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgpuo *LinGroupPermissionUpdateOne) ExecX(ctx context.Context) { + if err := lgpuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lgpuo *LinGroupPermissionUpdateOne) sqlSave(ctx context.Context) (_node *LinGroupPermission, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingrouppermission.Table, + Columns: lingrouppermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingrouppermission.FieldID, + }, + }, + } + id, ok := lgpuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinGroupPermission.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lgpuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, lingrouppermission.FieldID) + for _, f := range fields { + if !lingrouppermission.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != lingrouppermission.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lgpuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lgpuo.mutation.GroupID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldGroupID, + }) + } + if value, ok := lgpuo.mutation.AddedGroupID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldGroupID, + }) + } + if value, ok := lgpuo.mutation.PermissionID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldPermissionID, + }) + } + if value, ok := lgpuo.mutation.AddedPermissionID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: lingrouppermission.FieldPermissionID, + }) + } + _node = &LinGroupPermission{config: lgpuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lgpuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{lingrouppermission.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linlog.go b/internal/data/model/linlog.go new file mode 100644 index 0000000..8aa0545 --- /dev/null +++ b/internal/data/model/linlog.go @@ -0,0 +1,192 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linlog" + "strings" + "time" + + "entgo.io/ent/dialect/sql" +) + +// LinLog is the model entity for the LinLog schema. +type LinLog struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` + // Message holds the value of the "message" field. + Message string `json:"message,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // Username holds the value of the "username" field. + Username string `json:"username,omitempty"` + // StatusCode holds the value of the "status_code" field. + StatusCode int `json:"status_code,omitempty"` + // Method holds the value of the "method" field. + Method string `json:"method,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // Permission holds the value of the "permission" field. + Permission string `json:"permission,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinLog) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linlog.FieldID, linlog.FieldUserID, linlog.FieldStatusCode: + values[i] = new(sql.NullInt64) + case linlog.FieldMessage, linlog.FieldUsername, linlog.FieldMethod, linlog.FieldPath, linlog.FieldPermission: + values[i] = new(sql.NullString) + case linlog.FieldCreateTime, linlog.FieldUpdateTime, linlog.FieldDeleteTime: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type LinLog", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinLog fields. +func (ll *LinLog) assignValues(columns []string, values []interface{}) 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 linlog.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ll.ID = int(value.Int64) + case linlog.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + ll.CreateTime = value.Time + } + case linlog.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + ll.UpdateTime = value.Time + } + case linlog.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + ll.DeleteTime = value.Time + } + case linlog.FieldMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message", values[i]) + } else if value.Valid { + ll.Message = value.String + } + case linlog.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + ll.UserID = int(value.Int64) + } + case linlog.FieldUsername: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value.Valid { + ll.Username = value.String + } + case linlog.FieldStatusCode: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field status_code", values[i]) + } else if value.Valid { + ll.StatusCode = int(value.Int64) + } + case linlog.FieldMethod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field method", values[i]) + } else if value.Valid { + ll.Method = value.String + } + case linlog.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + ll.Path = value.String + } + case linlog.FieldPermission: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field permission", values[i]) + } else if value.Valid { + ll.Permission = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this LinLog. +// Note that you need to call LinLog.Unwrap() before calling this method if this LinLog +// was returned from a transaction, and the transaction was committed or rolled back. +func (ll *LinLog) Update() *LinLogUpdateOne { + return (&LinLogClient{config: ll.config}).UpdateOne(ll) +} + +// Unwrap unwraps the LinLog 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 (ll *LinLog) Unwrap() *LinLog { + tx, ok := ll.config.driver.(*txDriver) + if !ok { + panic("model: LinLog is not a transactional entity") + } + ll.config.driver = tx.drv + return ll +} + +// String implements the fmt.Stringer. +func (ll *LinLog) String() string { + var builder strings.Builder + builder.WriteString("LinLog(") + builder.WriteString(fmt.Sprintf("id=%v", ll.ID)) + builder.WriteString(", create_time=") + builder.WriteString(ll.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(ll.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(ll.DeleteTime.Format(time.ANSIC)) + builder.WriteString(", message=") + builder.WriteString(ll.Message) + builder.WriteString(", user_id=") + builder.WriteString(fmt.Sprintf("%v", ll.UserID)) + builder.WriteString(", username=") + builder.WriteString(ll.Username) + builder.WriteString(", status_code=") + builder.WriteString(fmt.Sprintf("%v", ll.StatusCode)) + builder.WriteString(", method=") + builder.WriteString(ll.Method) + builder.WriteString(", path=") + builder.WriteString(ll.Path) + builder.WriteString(", permission=") + builder.WriteString(ll.Permission) + builder.WriteByte(')') + return builder.String() +} + +// LinLogs is a parsable slice of LinLog. +type LinLogs []*LinLog + +func (ll LinLogs) config(cfg config) { + for _i := range ll { + ll[_i].config = cfg + } +} diff --git a/internal/data/model/linlog/linlog.go b/internal/data/model/linlog/linlog.go new file mode 100644 index 0000000..14f4ab7 --- /dev/null +++ b/internal/data/model/linlog/linlog.go @@ -0,0 +1,72 @@ +// Code generated by entc, DO NOT EDIT. + +package linlog + +import ( + "time" +) + +const ( + // Label holds the string label denoting the linlog type in the database. + Label = "lin_log" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" + // FieldMessage holds the string denoting the message field in the database. + FieldMessage = "message" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldStatusCode holds the string denoting the status_code field in the database. + FieldStatusCode = "status_code" + // FieldMethod holds the string denoting the method field in the database. + FieldMethod = "method" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldPermission holds the string denoting the permission field in the database. + FieldPermission = "permission" + // Table holds the table name of the linlog in the database. + Table = "lin_log" +) + +// Columns holds all SQL columns for linlog fields. +var Columns = []string{ + FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldMessage, + FieldUserID, + FieldUsername, + FieldStatusCode, + FieldMethod, + FieldPath, + FieldPermission, +} + +// 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 ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // DefaultDeleteTime holds the default value on creation for the "delete_time" field. + DefaultDeleteTime func() time.Time +) diff --git a/internal/data/model/linlog/where.go b/internal/data/model/linlog/where.go new file mode 100644 index 0000000..c877f50 --- /dev/null +++ b/internal/data/model/linlog/where.go @@ -0,0 +1,1130 @@ +// Code generated by entc, DO NOT EDIT. + +package linlog + +import ( + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. +func Message(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMessage), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// StatusCode applies equality check predicate on the "status_code" field. It's identical to StatusCodeEQ. +func StatusCode(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatusCode), v)) + }) +} + +// Method applies equality check predicate on the "method" field. It's identical to MethodEQ. +func Method(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMethod), v)) + }) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// Permission applies equality check predicate on the "permission" field. It's identical to PermissionEQ. +func Permission(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPermission), v)) + }) +} + +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + +// MessageEQ applies the EQ predicate on the "message" field. +func MessageEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMessage), v)) + }) +} + +// MessageNEQ applies the NEQ predicate on the "message" field. +func MessageNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMessage), v)) + }) +} + +// MessageIn applies the In predicate on the "message" field. +func MessageIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMessage), v...)) + }) +} + +// MessageNotIn applies the NotIn predicate on the "message" field. +func MessageNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMessage), v...)) + }) +} + +// MessageGT applies the GT predicate on the "message" field. +func MessageGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMessage), v)) + }) +} + +// MessageGTE applies the GTE predicate on the "message" field. +func MessageGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMessage), v)) + }) +} + +// MessageLT applies the LT predicate on the "message" field. +func MessageLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMessage), v)) + }) +} + +// MessageLTE applies the LTE predicate on the "message" field. +func MessageLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMessage), v)) + }) +} + +// MessageContains applies the Contains predicate on the "message" field. +func MessageContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldMessage), v)) + }) +} + +// MessageHasPrefix applies the HasPrefix predicate on the "message" field. +func MessageHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldMessage), v)) + }) +} + +// MessageHasSuffix applies the HasSuffix predicate on the "message" field. +func MessageHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldMessage), v)) + }) +} + +// MessageEqualFold applies the EqualFold predicate on the "message" field. +func MessageEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldMessage), v)) + }) +} + +// MessageContainsFold applies the ContainsFold predicate on the "message" field. +func MessageContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldMessage), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUserID), v...)) + }) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUserID), v)) + }) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUserID), v)) + }) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUserID), v)) + }) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUserID), v)) + }) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUsername), v)) + }) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUsername), v...)) + }) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUsername), v...)) + }) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUsername), v)) + }) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUsername), v)) + }) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUsername), v)) + }) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUsername), v)) + }) +} + +// UsernameContains applies the Contains predicate on the "username" field. +func UsernameContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldUsername), v)) + }) +} + +// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. +func UsernameHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldUsername), v)) + }) +} + +// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. +func UsernameHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldUsername), v)) + }) +} + +// UsernameEqualFold applies the EqualFold predicate on the "username" field. +func UsernameEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldUsername), v)) + }) +} + +// UsernameContainsFold applies the ContainsFold predicate on the "username" field. +func UsernameContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldUsername), v)) + }) +} + +// StatusCodeEQ applies the EQ predicate on the "status_code" field. +func StatusCodeEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeNEQ applies the NEQ predicate on the "status_code" field. +func StatusCodeNEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeIn applies the In predicate on the "status_code" field. +func StatusCodeIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldStatusCode), v...)) + }) +} + +// StatusCodeNotIn applies the NotIn predicate on the "status_code" field. +func StatusCodeNotIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldStatusCode), v...)) + }) +} + +// StatusCodeGT applies the GT predicate on the "status_code" field. +func StatusCodeGT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeGTE applies the GTE predicate on the "status_code" field. +func StatusCodeGTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeLT applies the LT predicate on the "status_code" field. +func StatusCodeLT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeLTE applies the LTE predicate on the "status_code" field. +func StatusCodeLTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldStatusCode), v)) + }) +} + +// MethodEQ applies the EQ predicate on the "method" field. +func MethodEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMethod), v)) + }) +} + +// MethodNEQ applies the NEQ predicate on the "method" field. +func MethodNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMethod), v)) + }) +} + +// MethodIn applies the In predicate on the "method" field. +func MethodIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMethod), v...)) + }) +} + +// MethodNotIn applies the NotIn predicate on the "method" field. +func MethodNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMethod), v...)) + }) +} + +// MethodGT applies the GT predicate on the "method" field. +func MethodGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMethod), v)) + }) +} + +// MethodGTE applies the GTE predicate on the "method" field. +func MethodGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMethod), v)) + }) +} + +// MethodLT applies the LT predicate on the "method" field. +func MethodLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMethod), v)) + }) +} + +// MethodLTE applies the LTE predicate on the "method" field. +func MethodLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMethod), v)) + }) +} + +// MethodContains applies the Contains predicate on the "method" field. +func MethodContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldMethod), v)) + }) +} + +// MethodHasPrefix applies the HasPrefix predicate on the "method" field. +func MethodHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldMethod), v)) + }) +} + +// MethodHasSuffix applies the HasSuffix predicate on the "method" field. +func MethodHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldMethod), v)) + }) +} + +// MethodEqualFold applies the EqualFold predicate on the "method" field. +func MethodEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldMethod), v)) + }) +} + +// MethodContainsFold applies the ContainsFold predicate on the "method" field. +func MethodContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldMethod), v)) + }) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPath), v)) + }) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPath), v...)) + }) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPath), v...)) + }) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPath), v)) + }) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPath), v)) + }) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPath), v)) + }) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPath), v)) + }) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldPath), v)) + }) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldPath), v)) + }) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldPath), v)) + }) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldPath), v)) + }) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldPath), v)) + }) +} + +// PermissionEQ applies the EQ predicate on the "permission" field. +func PermissionEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPermission), v)) + }) +} + +// PermissionNEQ applies the NEQ predicate on the "permission" field. +func PermissionNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPermission), v)) + }) +} + +// PermissionIn applies the In predicate on the "permission" field. +func PermissionIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPermission), v...)) + }) +} + +// PermissionNotIn applies the NotIn predicate on the "permission" field. +func PermissionNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPermission), v...)) + }) +} + +// PermissionGT applies the GT predicate on the "permission" field. +func PermissionGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPermission), v)) + }) +} + +// PermissionGTE applies the GTE predicate on the "permission" field. +func PermissionGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPermission), v)) + }) +} + +// PermissionLT applies the LT predicate on the "permission" field. +func PermissionLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPermission), v)) + }) +} + +// PermissionLTE applies the LTE predicate on the "permission" field. +func PermissionLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPermission), v)) + }) +} + +// PermissionContains applies the Contains predicate on the "permission" field. +func PermissionContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldPermission), v)) + }) +} + +// PermissionHasPrefix applies the HasPrefix predicate on the "permission" field. +func PermissionHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldPermission), v)) + }) +} + +// PermissionHasSuffix applies the HasSuffix predicate on the "permission" field. +func PermissionHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldPermission), v)) + }) +} + +// PermissionEqualFold applies the EqualFold predicate on the "permission" field. +func PermissionEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldPermission), v)) + }) +} + +// PermissionContainsFold applies the ContainsFold predicate on the "permission" field. +func PermissionContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldPermission), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinLog) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinLog) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinLog) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linlog_create.go b/internal/data/model/linlog_create.go new file mode 100644 index 0000000..9b9b76d --- /dev/null +++ b/internal/data/model/linlog_create.go @@ -0,0 +1,416 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogCreate is the builder for creating a LinLog entity. +type LinLogCreate struct { + config + mutation *LinLogMutation + hooks []Hook +} + +// SetCreateTime sets the "create_time" field. +func (llc *LinLogCreate) SetCreateTime(t time.Time) *LinLogCreate { + llc.mutation.SetCreateTime(t) + return llc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (llc *LinLogCreate) SetNillableCreateTime(t *time.Time) *LinLogCreate { + if t != nil { + llc.SetCreateTime(*t) + } + return llc +} + +// SetUpdateTime sets the "update_time" field. +func (llc *LinLogCreate) SetUpdateTime(t time.Time) *LinLogCreate { + llc.mutation.SetUpdateTime(t) + return llc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (llc *LinLogCreate) SetNillableUpdateTime(t *time.Time) *LinLogCreate { + if t != nil { + llc.SetUpdateTime(*t) + } + return llc +} + +// SetDeleteTime sets the "delete_time" field. +func (llc *LinLogCreate) SetDeleteTime(t time.Time) *LinLogCreate { + llc.mutation.SetDeleteTime(t) + return llc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (llc *LinLogCreate) SetNillableDeleteTime(t *time.Time) *LinLogCreate { + if t != nil { + llc.SetDeleteTime(*t) + } + return llc +} + +// SetMessage sets the "message" field. +func (llc *LinLogCreate) SetMessage(s string) *LinLogCreate { + llc.mutation.SetMessage(s) + return llc +} + +// SetUserID sets the "user_id" field. +func (llc *LinLogCreate) SetUserID(i int) *LinLogCreate { + llc.mutation.SetUserID(i) + return llc +} + +// SetUsername sets the "username" field. +func (llc *LinLogCreate) SetUsername(s string) *LinLogCreate { + llc.mutation.SetUsername(s) + return llc +} + +// SetStatusCode sets the "status_code" field. +func (llc *LinLogCreate) SetStatusCode(i int) *LinLogCreate { + llc.mutation.SetStatusCode(i) + return llc +} + +// SetMethod sets the "method" field. +func (llc *LinLogCreate) SetMethod(s string) *LinLogCreate { + llc.mutation.SetMethod(s) + return llc +} + +// SetPath sets the "path" field. +func (llc *LinLogCreate) SetPath(s string) *LinLogCreate { + llc.mutation.SetPath(s) + return llc +} + +// SetPermission sets the "permission" field. +func (llc *LinLogCreate) SetPermission(s string) *LinLogCreate { + llc.mutation.SetPermission(s) + return llc +} + +// Mutation returns the LinLogMutation object of the builder. +func (llc *LinLogCreate) Mutation() *LinLogMutation { + return llc.mutation +} + +// Save creates the LinLog in the database. +func (llc *LinLogCreate) Save(ctx context.Context) (*LinLog, error) { + var ( + err error + node *LinLog + ) + llc.defaults() + if len(llc.hooks) == 0 { + if err = llc.check(); err != nil { + return nil, err + } + node, err = llc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = llc.check(); err != nil { + return nil, err + } + llc.mutation = mutation + if node, err = llc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(llc.hooks) - 1; i >= 0; i-- { + if llc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = llc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, llc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (llc *LinLogCreate) SaveX(ctx context.Context) *LinLog { + v, err := llc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (llc *LinLogCreate) Exec(ctx context.Context) error { + _, err := llc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (llc *LinLogCreate) ExecX(ctx context.Context) { + if err := llc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (llc *LinLogCreate) defaults() { + if _, ok := llc.mutation.CreateTime(); !ok { + v := linlog.DefaultCreateTime() + llc.mutation.SetCreateTime(v) + } + if _, ok := llc.mutation.UpdateTime(); !ok { + v := linlog.DefaultUpdateTime() + llc.mutation.SetUpdateTime(v) + } + if _, ok := llc.mutation.DeleteTime(); !ok { + v := linlog.DefaultDeleteTime() + llc.mutation.SetDeleteTime(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (llc *LinLogCreate) check() error { + if _, ok := llc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := llc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } + if _, ok := llc.mutation.DeleteTime(); !ok { + return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} + } + if _, ok := llc.mutation.Message(); !ok { + return &ValidationError{Name: "message", err: errors.New(`model: missing required field "message"`)} + } + if _, ok := llc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} + } + if _, ok := llc.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} + } + if _, ok := llc.mutation.StatusCode(); !ok { + return &ValidationError{Name: "status_code", err: errors.New(`model: missing required field "status_code"`)} + } + if _, ok := llc.mutation.Method(); !ok { + return &ValidationError{Name: "method", err: errors.New(`model: missing required field "method"`)} + } + if _, ok := llc.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`model: missing required field "path"`)} + } + if _, ok := llc.mutation.Permission(); !ok { + return &ValidationError{Name: "permission", err: errors.New(`model: missing required field "permission"`)} + } + return nil +} + +func (llc *LinLogCreate) sqlSave(ctx context.Context) (*LinLog, error) { + _node, _spec := llc.createSpec() + if err := sqlgraph.CreateNode(ctx, llc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (llc *LinLogCreate) createSpec() (*LinLog, *sqlgraph.CreateSpec) { + var ( + _node = &LinLog{config: llc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linlog.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + } + ) + if value, ok := llc.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := llc.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := llc.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldDeleteTime, + }) + _node.DeleteTime = value + } + if value, ok := llc.mutation.Message(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMessage, + }) + _node.Message = value + } + if value, ok := llc.mutation.UserID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + _node.UserID = value + } + if value, ok := llc.mutation.Username(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldUsername, + }) + _node.Username = value + } + if value, ok := llc.mutation.StatusCode(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + _node.StatusCode = value + } + if value, ok := llc.mutation.Method(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMethod, + }) + _node.Method = value + } + if value, ok := llc.mutation.Path(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPath, + }) + _node.Path = value + } + if value, ok := llc.mutation.Permission(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPermission, + }) + _node.Permission = value + } + return _node, _spec +} + +// LinLogCreateBulk is the builder for creating many LinLog entities in bulk. +type LinLogCreateBulk struct { + config + builders []*LinLogCreate +} + +// Save creates the LinLog entities in the database. +func (llcb *LinLogCreateBulk) Save(ctx context.Context) ([]*LinLog, error) { + specs := make([]*sqlgraph.CreateSpec, len(llcb.builders)) + nodes := make([]*LinLog, len(llcb.builders)) + mutators := make([]Mutator, len(llcb.builders)) + for i := range llcb.builders { + func(i int, root context.Context) { + builder := llcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, llcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, llcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, llcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (llcb *LinLogCreateBulk) SaveX(ctx context.Context) []*LinLog { + v, err := llcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (llcb *LinLogCreateBulk) Exec(ctx context.Context) error { + _, err := llcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (llcb *LinLogCreateBulk) ExecX(ctx context.Context) { + if err := llcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linlog_delete.go b/internal/data/model/linlog_delete.go new file mode 100644 index 0000000..7b370d2 --- /dev/null +++ b/internal/data/model/linlog_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogDelete is the builder for deleting a LinLog entity. +type LinLogDelete struct { + config + hooks []Hook + mutation *LinLogMutation +} + +// Where appends a list predicates to the LinLogDelete builder. +func (lld *LinLogDelete) Where(ps ...predicate.LinLog) *LinLogDelete { + lld.mutation.Where(ps...) + return lld +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lld *LinLogDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lld.hooks) == 0 { + affected, err = lld.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lld.mutation = mutation + affected, err = lld.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lld.hooks) - 1; i >= 0; i-- { + if lld.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lld.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lld.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lld *LinLogDelete) ExecX(ctx context.Context) int { + n, err := lld.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lld *LinLogDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + } + if ps := lld.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lld.driver, _spec) +} + +// LinLogDeleteOne is the builder for deleting a single LinLog entity. +type LinLogDeleteOne struct { + lld *LinLogDelete +} + +// Exec executes the deletion query. +func (lldo *LinLogDeleteOne) Exec(ctx context.Context) error { + n, err := lldo.lld.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linlog.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lldo *LinLogDeleteOne) ExecX(ctx context.Context) { + lldo.lld.ExecX(ctx) +} diff --git a/internal/data/model/linlog_query.go b/internal/data/model/linlog_query.go new file mode 100644 index 0000000..c734c14 --- /dev/null +++ b/internal/data/model/linlog_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogQuery is the builder for querying LinLog entities. +type LinLogQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinLog + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinLogQuery builder. +func (llq *LinLogQuery) Where(ps ...predicate.LinLog) *LinLogQuery { + llq.predicates = append(llq.predicates, ps...) + return llq +} + +// Limit adds a limit step to the query. +func (llq *LinLogQuery) Limit(limit int) *LinLogQuery { + llq.limit = &limit + return llq +} + +// Offset adds an offset step to the query. +func (llq *LinLogQuery) Offset(offset int) *LinLogQuery { + llq.offset = &offset + return llq +} + +// 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 (llq *LinLogQuery) Unique(unique bool) *LinLogQuery { + llq.unique = &unique + return llq +} + +// Order adds an order step to the query. +func (llq *LinLogQuery) Order(o ...OrderFunc) *LinLogQuery { + llq.order = append(llq.order, o...) + return llq +} + +// First returns the first LinLog entity from the query. +// Returns a *NotFoundError when no LinLog was found. +func (llq *LinLogQuery) First(ctx context.Context) (*LinLog, error) { + nodes, err := llq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linlog.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (llq *LinLogQuery) FirstX(ctx context.Context) *LinLog { + node, err := llq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinLog ID from the query. +// Returns a *NotFoundError when no LinLog ID was found. +func (llq *LinLogQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = llq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linlog.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (llq *LinLogQuery) FirstIDX(ctx context.Context) int { + id, err := llq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinLog entity from the query. +// Returns a *NotFoundError when no LinLog was found. +func (llq *LinLogQuery) Last(ctx context.Context) (*LinLog, error) { + nodes, err := llq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linlog.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (llq *LinLogQuery) LastX(ctx context.Context) *LinLog { + node, err := llq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinLog ID from the query. +// Returns a *NotFoundError when no LinLog ID was found. +func (llq *LinLogQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = llq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linlog.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (llq *LinLogQuery) LastIDX(ctx context.Context) int { + id, err := llq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinLog entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinLog entity is not found. +// Returns a *NotFoundError when no LinLog entities are found. +func (llq *LinLogQuery) Only(ctx context.Context) (*LinLog, error) { + nodes, err := llq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linlog.Label} + default: + return nil, &NotSingularError{linlog.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (llq *LinLogQuery) OnlyX(ctx context.Context) *LinLog { + node, err := llq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinLog ID in the query. +// Returns a *NotSingularError when exactly one LinLog ID is not found. +// Returns a *NotFoundError when no entities are found. +func (llq *LinLogQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = llq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linlog.Label} + default: + err = &NotSingularError{linlog.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (llq *LinLogQuery) OnlyIDX(ctx context.Context) int { + id, err := llq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinLogs. +func (llq *LinLogQuery) All(ctx context.Context) ([]*LinLog, error) { + if err := llq.prepareQuery(ctx); err != nil { + return nil, err + } + return llq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (llq *LinLogQuery) AllX(ctx context.Context) []*LinLog { + nodes, err := llq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinLog IDs. +func (llq *LinLogQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := llq.Select(linlog.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (llq *LinLogQuery) IDsX(ctx context.Context) []int { + ids, err := llq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (llq *LinLogQuery) Count(ctx context.Context) (int, error) { + if err := llq.prepareQuery(ctx); err != nil { + return 0, err + } + return llq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (llq *LinLogQuery) CountX(ctx context.Context) int { + count, err := llq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (llq *LinLogQuery) Exist(ctx context.Context) (bool, error) { + if err := llq.prepareQuery(ctx); err != nil { + return false, err + } + return llq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (llq *LinLogQuery) ExistX(ctx context.Context) bool { + exist, err := llq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinLogQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (llq *LinLogQuery) Clone() *LinLogQuery { + if llq == nil { + return nil + } + return &LinLogQuery{ + config: llq.config, + limit: llq.limit, + offset: llq.offset, + order: append([]OrderFunc{}, llq.order...), + predicates: append([]predicate.LinLog{}, llq.predicates...), + // clone intermediate query. + sql: llq.sql.Clone(), + path: llq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinLog.Query(). +// GroupBy(linlog.FieldCreateTime). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (llq *LinLogQuery) GroupBy(field string, fields ...string) *LinLogGroupBy { + group := &LinLogGroupBy{config: llq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := llq.prepareQuery(ctx); err != nil { + return nil, err + } + return llq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.LinLog.Query(). +// Select(linlog.FieldCreateTime). +// Scan(ctx, &v) +// +func (llq *LinLogQuery) Select(fields ...string) *LinLogSelect { + llq.fields = append(llq.fields, fields...) + return &LinLogSelect{LinLogQuery: llq} +} + +func (llq *LinLogQuery) prepareQuery(ctx context.Context) error { + for _, f := range llq.fields { + if !linlog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if llq.path != nil { + prev, err := llq.path(ctx) + if err != nil { + return err + } + llq.sql = prev + } + return nil +} + +func (llq *LinLogQuery) sqlAll(ctx context.Context) ([]*LinLog, error) { + var ( + nodes = []*LinLog{} + _spec = llq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinLog{config: llq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, llq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (llq *LinLogQuery) sqlCount(ctx context.Context) (int, error) { + _spec := llq.querySpec() + return sqlgraph.CountNodes(ctx, llq.driver, _spec) +} + +func (llq *LinLogQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := llq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (llq *LinLogQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + Columns: linlog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + From: llq.sql, + Unique: true, + } + if unique := llq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := llq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linlog.FieldID) + for i := range fields { + if fields[i] != linlog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := llq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := llq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := llq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := llq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (llq *LinLogQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(llq.driver.Dialect()) + t1 := builder.Table(linlog.Table) + columns := llq.fields + if len(columns) == 0 { + columns = linlog.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if llq.sql != nil { + selector = llq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range llq.predicates { + p(selector) + } + for _, p := range llq.order { + p(selector) + } + if offset := llq.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 := llq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinLogGroupBy is the group-by builder for LinLog entities. +type LinLogGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (llgb *LinLogGroupBy) Aggregate(fns ...AggregateFunc) *LinLogGroupBy { + llgb.fns = append(llgb.fns, fns...) + return llgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (llgb *LinLogGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := llgb.path(ctx) + if err != nil { + return err + } + llgb.sql = query + return llgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (llgb *LinLogGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := llgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (llgb *LinLogGroupBy) StringsX(ctx context.Context) []string { + v, err := llgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = llgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (llgb *LinLogGroupBy) StringX(ctx context.Context) string { + v, err := llgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (llgb *LinLogGroupBy) IntsX(ctx context.Context) []int { + v, err := llgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = llgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (llgb *LinLogGroupBy) IntX(ctx context.Context) int { + v, err := llgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (llgb *LinLogGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := llgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = llgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (llgb *LinLogGroupBy) Float64X(ctx context.Context) float64 { + v, err := llgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (llgb *LinLogGroupBy) BoolsX(ctx context.Context) []bool { + v, err := llgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = llgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (llgb *LinLogGroupBy) BoolX(ctx context.Context) bool { + v, err := llgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (llgb *LinLogGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range llgb.fields { + if !linlog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := llgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := llgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (llgb *LinLogGroupBy) sqlQuery() *sql.Selector { + selector := llgb.sql.Select() + aggregation := make([]string, 0, len(llgb.fns)) + for _, fn := range llgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(llgb.fields)+len(llgb.fns)) + for _, f := range llgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(llgb.fields...)...) +} + +// LinLogSelect is the builder for selecting fields of LinLog entities. +type LinLogSelect struct { + *LinLogQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lls *LinLogSelect) Scan(ctx context.Context, v interface{}) error { + if err := lls.prepareQuery(ctx); err != nil { + return err + } + lls.sql = lls.LinLogQuery.sqlQuery(ctx) + return lls.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lls *LinLogSelect) ScanX(ctx context.Context, v interface{}) { + if err := lls.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Strings(ctx context.Context) ([]string, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lls *LinLogSelect) StringsX(ctx context.Context) []string { + v, err := lls.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lls.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lls *LinLogSelect) StringX(ctx context.Context) string { + v, err := lls.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Ints(ctx context.Context) ([]int, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lls *LinLogSelect) IntsX(ctx context.Context) []int { + v, err := lls.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lls.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lls *LinLogSelect) IntX(ctx context.Context) int { + v, err := lls.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lls *LinLogSelect) Float64sX(ctx context.Context) []float64 { + v, err := lls.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lls.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lls *LinLogSelect) Float64X(ctx context.Context) float64 { + v, err := lls.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lls *LinLogSelect) BoolsX(ctx context.Context) []bool { + v, err := lls.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lls.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lls *LinLogSelect) BoolX(ctx context.Context) bool { + v, err := lls.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lls *LinLogSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lls.sql.Query() + if err := lls.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linlog_update.go b/internal/data/model/linlog_update.go new file mode 100644 index 0000000..7b53bc4 --- /dev/null +++ b/internal/data/model/linlog_update.go @@ -0,0 +1,563 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogUpdate is the builder for updating LinLog entities. +type LinLogUpdate struct { + config + hooks []Hook + mutation *LinLogMutation +} + +// Where appends a list predicates to the LinLogUpdate builder. +func (llu *LinLogUpdate) Where(ps ...predicate.LinLog) *LinLogUpdate { + llu.mutation.Where(ps...) + return llu +} + +// SetUpdateTime sets the "update_time" field. +func (llu *LinLogUpdate) SetUpdateTime(t time.Time) *LinLogUpdate { + llu.mutation.SetUpdateTime(t) + return llu +} + +// SetDeleteTime sets the "delete_time" field. +func (llu *LinLogUpdate) SetDeleteTime(t time.Time) *LinLogUpdate { + llu.mutation.SetDeleteTime(t) + return llu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (llu *LinLogUpdate) SetNillableDeleteTime(t *time.Time) *LinLogUpdate { + if t != nil { + llu.SetDeleteTime(*t) + } + return llu +} + +// SetMessage sets the "message" field. +func (llu *LinLogUpdate) SetMessage(s string) *LinLogUpdate { + llu.mutation.SetMessage(s) + return llu +} + +// SetUserID sets the "user_id" field. +func (llu *LinLogUpdate) SetUserID(i int) *LinLogUpdate { + llu.mutation.ResetUserID() + llu.mutation.SetUserID(i) + return llu +} + +// AddUserID adds i to the "user_id" field. +func (llu *LinLogUpdate) AddUserID(i int) *LinLogUpdate { + llu.mutation.AddUserID(i) + return llu +} + +// SetUsername sets the "username" field. +func (llu *LinLogUpdate) SetUsername(s string) *LinLogUpdate { + llu.mutation.SetUsername(s) + return llu +} + +// SetStatusCode sets the "status_code" field. +func (llu *LinLogUpdate) SetStatusCode(i int) *LinLogUpdate { + llu.mutation.ResetStatusCode() + llu.mutation.SetStatusCode(i) + return llu +} + +// AddStatusCode adds i to the "status_code" field. +func (llu *LinLogUpdate) AddStatusCode(i int) *LinLogUpdate { + llu.mutation.AddStatusCode(i) + return llu +} + +// SetMethod sets the "method" field. +func (llu *LinLogUpdate) SetMethod(s string) *LinLogUpdate { + llu.mutation.SetMethod(s) + return llu +} + +// SetPath sets the "path" field. +func (llu *LinLogUpdate) SetPath(s string) *LinLogUpdate { + llu.mutation.SetPath(s) + return llu +} + +// SetPermission sets the "permission" field. +func (llu *LinLogUpdate) SetPermission(s string) *LinLogUpdate { + llu.mutation.SetPermission(s) + return llu +} + +// Mutation returns the LinLogMutation object of the builder. +func (llu *LinLogUpdate) Mutation() *LinLogMutation { + return llu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (llu *LinLogUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + llu.defaults() + if len(llu.hooks) == 0 { + affected, err = llu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + llu.mutation = mutation + affected, err = llu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(llu.hooks) - 1; i >= 0; i-- { + if llu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = llu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, llu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (llu *LinLogUpdate) SaveX(ctx context.Context) int { + affected, err := llu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (llu *LinLogUpdate) Exec(ctx context.Context) error { + _, err := llu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (llu *LinLogUpdate) ExecX(ctx context.Context) { + if err := llu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (llu *LinLogUpdate) defaults() { + if _, ok := llu.mutation.UpdateTime(); !ok { + v := linlog.UpdateDefaultUpdateTime() + llu.mutation.SetUpdateTime(v) + } +} + +func (llu *LinLogUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + Columns: linlog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + } + if ps := llu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := llu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldUpdateTime, + }) + } + if value, ok := llu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldDeleteTime, + }) + } + if value, ok := llu.mutation.Message(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMessage, + }) + } + if value, ok := llu.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := llu.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := llu.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldUsername, + }) + } + if value, ok := llu.mutation.StatusCode(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := llu.mutation.AddedStatusCode(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := llu.mutation.Method(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMethod, + }) + } + if value, ok := llu.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPath, + }) + } + if value, ok := llu.mutation.Permission(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPermission, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, llu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linlog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinLogUpdateOne is the builder for updating a single LinLog entity. +type LinLogUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinLogMutation +} + +// SetUpdateTime sets the "update_time" field. +func (lluo *LinLogUpdateOne) SetUpdateTime(t time.Time) *LinLogUpdateOne { + lluo.mutation.SetUpdateTime(t) + return lluo +} + +// SetDeleteTime sets the "delete_time" field. +func (lluo *LinLogUpdateOne) SetDeleteTime(t time.Time) *LinLogUpdateOne { + lluo.mutation.SetDeleteTime(t) + return lluo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (lluo *LinLogUpdateOne) SetNillableDeleteTime(t *time.Time) *LinLogUpdateOne { + if t != nil { + lluo.SetDeleteTime(*t) + } + return lluo +} + +// SetMessage sets the "message" field. +func (lluo *LinLogUpdateOne) SetMessage(s string) *LinLogUpdateOne { + lluo.mutation.SetMessage(s) + return lluo +} + +// SetUserID sets the "user_id" field. +func (lluo *LinLogUpdateOne) SetUserID(i int) *LinLogUpdateOne { + lluo.mutation.ResetUserID() + lluo.mutation.SetUserID(i) + return lluo +} + +// AddUserID adds i to the "user_id" field. +func (lluo *LinLogUpdateOne) AddUserID(i int) *LinLogUpdateOne { + lluo.mutation.AddUserID(i) + return lluo +} + +// SetUsername sets the "username" field. +func (lluo *LinLogUpdateOne) SetUsername(s string) *LinLogUpdateOne { + lluo.mutation.SetUsername(s) + return lluo +} + +// SetStatusCode sets the "status_code" field. +func (lluo *LinLogUpdateOne) SetStatusCode(i int) *LinLogUpdateOne { + lluo.mutation.ResetStatusCode() + lluo.mutation.SetStatusCode(i) + return lluo +} + +// AddStatusCode adds i to the "status_code" field. +func (lluo *LinLogUpdateOne) AddStatusCode(i int) *LinLogUpdateOne { + lluo.mutation.AddStatusCode(i) + return lluo +} + +// SetMethod sets the "method" field. +func (lluo *LinLogUpdateOne) SetMethod(s string) *LinLogUpdateOne { + lluo.mutation.SetMethod(s) + return lluo +} + +// SetPath sets the "path" field. +func (lluo *LinLogUpdateOne) SetPath(s string) *LinLogUpdateOne { + lluo.mutation.SetPath(s) + return lluo +} + +// SetPermission sets the "permission" field. +func (lluo *LinLogUpdateOne) SetPermission(s string) *LinLogUpdateOne { + lluo.mutation.SetPermission(s) + return lluo +} + +// Mutation returns the LinLogMutation object of the builder. +func (lluo *LinLogUpdateOne) Mutation() *LinLogMutation { + return lluo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lluo *LinLogUpdateOne) Select(field string, fields ...string) *LinLogUpdateOne { + lluo.fields = append([]string{field}, fields...) + return lluo +} + +// Save executes the query and returns the updated LinLog entity. +func (lluo *LinLogUpdateOne) Save(ctx context.Context) (*LinLog, error) { + var ( + err error + node *LinLog + ) + lluo.defaults() + if len(lluo.hooks) == 0 { + node, err = lluo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lluo.mutation = mutation + node, err = lluo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lluo.hooks) - 1; i >= 0; i-- { + if lluo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lluo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lluo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lluo *LinLogUpdateOne) SaveX(ctx context.Context) *LinLog { + node, err := lluo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lluo *LinLogUpdateOne) Exec(ctx context.Context) error { + _, err := lluo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lluo *LinLogUpdateOne) ExecX(ctx context.Context) { + if err := lluo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (lluo *LinLogUpdateOne) defaults() { + if _, ok := lluo.mutation.UpdateTime(); !ok { + v := linlog.UpdateDefaultUpdateTime() + lluo.mutation.SetUpdateTime(v) + } +} + +func (lluo *LinLogUpdateOne) sqlSave(ctx context.Context) (_node *LinLog, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + Columns: linlog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + } + id, ok := lluo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinLog.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lluo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linlog.FieldID) + for _, f := range fields { + if !linlog.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linlog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lluo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lluo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldUpdateTime, + }) + } + if value, ok := lluo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldDeleteTime, + }) + } + if value, ok := lluo.mutation.Message(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMessage, + }) + } + if value, ok := lluo.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := lluo.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := lluo.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldUsername, + }) + } + if value, ok := lluo.mutation.StatusCode(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := lluo.mutation.AddedStatusCode(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := lluo.mutation.Method(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMethod, + }) + } + if value, ok := lluo.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPath, + }) + } + if value, ok := lluo.mutation.Permission(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPermission, + }) + } + _node = &LinLog{config: lluo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lluo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linlog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linpermission.go b/internal/data/model/linpermission.go new file mode 100644 index 0000000..f2acd85 --- /dev/null +++ b/internal/data/model/linpermission.go @@ -0,0 +1,148 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linpermission" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinPermission is the model entity for the LinPermission schema. +type LinPermission struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + // 权限名称,例如:访问首页 + Name string `json:"name,omitempty"` + // Module holds the value of the "module" field. + // 权限所属模块,例如:人员管理 + Module string `json:"module,omitempty"` + // Mount holds the value of the "mount" field. + // 0:关闭 1:开启 + Mount int8 `json:"mount,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinPermissionQuery when eager-loading is set. + Edges LinPermissionEdges `json:"edges"` +} + +// LinPermissionEdges holds the relations/edges for other nodes in the graph. +type LinPermissionEdges struct { + // LinGroup holds the value of the lin_group edge. + LinGroup []*LinGroup `json:"lin_group,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// LinGroupOrErr returns the LinGroup value or an error if the edge +// was not loaded in eager-loading. +func (e LinPermissionEdges) LinGroupOrErr() ([]*LinGroup, error) { + if e.loadedTypes[0] { + return e.LinGroup, nil + } + return nil, &NotLoadedError{edge: "lin_group"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinPermission) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linpermission.FieldID, linpermission.FieldMount: + values[i] = new(sql.NullInt64) + case linpermission.FieldName, linpermission.FieldModule: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type LinPermission", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinPermission fields. +func (lp *LinPermission) assignValues(columns []string, values []interface{}) 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 linpermission.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lp.ID = int(value.Int64) + case linpermission.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + lp.Name = value.String + } + case linpermission.FieldModule: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field module", values[i]) + } else if value.Valid { + lp.Module = value.String + } + case linpermission.FieldMount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field mount", values[i]) + } else if value.Valid { + lp.Mount = int8(value.Int64) + } + } + } + return nil +} + +// QueryLinGroup queries the "lin_group" edge of the LinPermission entity. +func (lp *LinPermission) QueryLinGroup() *LinGroupQuery { + return (&LinPermissionClient{config: lp.config}).QueryLinGroup(lp) +} + +// Update returns a builder for updating this LinPermission. +// Note that you need to call LinPermission.Unwrap() before calling this method if this LinPermission +// was returned from a transaction, and the transaction was committed or rolled back. +func (lp *LinPermission) Update() *LinPermissionUpdateOne { + return (&LinPermissionClient{config: lp.config}).UpdateOne(lp) +} + +// Unwrap unwraps the LinPermission 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 (lp *LinPermission) Unwrap() *LinPermission { + tx, ok := lp.config.driver.(*txDriver) + if !ok { + panic("model: LinPermission is not a transactional entity") + } + lp.config.driver = tx.drv + return lp +} + +// String implements the fmt.Stringer. +func (lp *LinPermission) String() string { + var builder strings.Builder + builder.WriteString("LinPermission(") + builder.WriteString(fmt.Sprintf("id=%v", lp.ID)) + builder.WriteString(", name=") + builder.WriteString(lp.Name) + builder.WriteString(", module=") + builder.WriteString(lp.Module) + builder.WriteString(", mount=") + builder.WriteString(fmt.Sprintf("%v", lp.Mount)) + builder.WriteByte(')') + return builder.String() +} + +// LinPermissions is a parsable slice of LinPermission. +type LinPermissions []*LinPermission + +func (lp LinPermissions) config(cfg config) { + for _i := range lp { + lp[_i].config = cfg + } +} diff --git a/internal/data/model/linpermission/linpermission.go b/internal/data/model/linpermission/linpermission.go new file mode 100644 index 0000000..09861cc --- /dev/null +++ b/internal/data/model/linpermission/linpermission.go @@ -0,0 +1,49 @@ +// Code generated by entc, DO NOT EDIT. + +package linpermission + +const ( + // Label holds the string label denoting the linpermission type in the database. + Label = "lin_permission" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldModule holds the string denoting the module field in the database. + FieldModule = "module" + // FieldMount holds the string denoting the mount field in the database. + FieldMount = "mount" + // EdgeLinGroup holds the string denoting the lin_group edge name in mutations. + EdgeLinGroup = "lin_group" + // Table holds the table name of the linpermission in the database. + Table = "lin_permission" + // LinGroupTable is the table that holds the lin_group relation/edge. The primary key declared below. + LinGroupTable = "lin_permission_lin_group" + // LinGroupInverseTable is the table name for the LinGroup entity. + // It exists in this package in order to avoid circular dependency with the "lingroup" package. + LinGroupInverseTable = "lin_group" +) + +// Columns holds all SQL columns for linpermission fields. +var Columns = []string{ + FieldID, + FieldName, + FieldModule, + FieldMount, +} + +var ( + // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the + // primary key for the lin_group relation (M2M). + LinGroupPrimaryKey = []string{"lin_permission_id", "lin_group_id"} +) + +// 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 +} diff --git a/internal/data/model/linpermission/where.go b/internal/data/model/linpermission/where.go new file mode 100644 index 0000000..a28e920 --- /dev/null +++ b/internal/data/model/linpermission/where.go @@ -0,0 +1,472 @@ +// Code generated by entc, DO NOT EDIT. + +package linpermission + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Module applies equality check predicate on the "module" field. It's identical to ModuleEQ. +func Module(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldModule), v)) + }) +} + +// Mount applies equality check predicate on the "mount" field. It's identical to MountEQ. +func Mount(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMount), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// ModuleEQ applies the EQ predicate on the "module" field. +func ModuleEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldModule), v)) + }) +} + +// ModuleNEQ applies the NEQ predicate on the "module" field. +func ModuleNEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldModule), v)) + }) +} + +// ModuleIn applies the In predicate on the "module" field. +func ModuleIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldModule), v...)) + }) +} + +// ModuleNotIn applies the NotIn predicate on the "module" field. +func ModuleNotIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldModule), v...)) + }) +} + +// ModuleGT applies the GT predicate on the "module" field. +func ModuleGT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldModule), v)) + }) +} + +// ModuleGTE applies the GTE predicate on the "module" field. +func ModuleGTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldModule), v)) + }) +} + +// ModuleLT applies the LT predicate on the "module" field. +func ModuleLT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldModule), v)) + }) +} + +// ModuleLTE applies the LTE predicate on the "module" field. +func ModuleLTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldModule), v)) + }) +} + +// ModuleContains applies the Contains predicate on the "module" field. +func ModuleContains(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldModule), v)) + }) +} + +// ModuleHasPrefix applies the HasPrefix predicate on the "module" field. +func ModuleHasPrefix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldModule), v)) + }) +} + +// ModuleHasSuffix applies the HasSuffix predicate on the "module" field. +func ModuleHasSuffix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldModule), v)) + }) +} + +// ModuleEqualFold applies the EqualFold predicate on the "module" field. +func ModuleEqualFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldModule), v)) + }) +} + +// ModuleContainsFold applies the ContainsFold predicate on the "module" field. +func ModuleContainsFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldModule), v)) + }) +} + +// MountEQ applies the EQ predicate on the "mount" field. +func MountEQ(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMount), v)) + }) +} + +// MountNEQ applies the NEQ predicate on the "mount" field. +func MountNEQ(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMount), v)) + }) +} + +// MountIn applies the In predicate on the "mount" field. +func MountIn(vs ...int8) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMount), v...)) + }) +} + +// MountNotIn applies the NotIn predicate on the "mount" field. +func MountNotIn(vs ...int8) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMount), v...)) + }) +} + +// MountGT applies the GT predicate on the "mount" field. +func MountGT(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMount), v)) + }) +} + +// MountGTE applies the GTE predicate on the "mount" field. +func MountGTE(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMount), v)) + }) +} + +// MountLT applies the LT predicate on the "mount" field. +func MountLT(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMount), v)) + }) +} + +// MountLTE applies the LTE predicate on the "mount" field. +func MountLTE(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMount), v)) + }) +} + +// HasLinGroup applies the HasEdge predicate on the "lin_group" edge. +func HasLinGroup() predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinGroupTable, LinGroupPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinGroupWith applies the HasEdge predicate on the "lin_group" edge with a given conditions (other predicates). +func HasLinGroupWith(preds ...predicate.LinGroup) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinGroupTable, LinGroupPrimaryKey...), + ) + 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.LinPermission) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinPermission) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinPermission) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linpermission_create.go b/internal/data/model/linpermission_create.go new file mode 100644 index 0000000..01e3d9b --- /dev/null +++ b/internal/data/model/linpermission_create.go @@ -0,0 +1,289 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionCreate is the builder for creating a LinPermission entity. +type LinPermissionCreate struct { + config + mutation *LinPermissionMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (lpc *LinPermissionCreate) SetName(s string) *LinPermissionCreate { + lpc.mutation.SetName(s) + return lpc +} + +// SetModule sets the "module" field. +func (lpc *LinPermissionCreate) SetModule(s string) *LinPermissionCreate { + lpc.mutation.SetModule(s) + return lpc +} + +// SetMount sets the "mount" field. +func (lpc *LinPermissionCreate) SetMount(i int8) *LinPermissionCreate { + lpc.mutation.SetMount(i) + return lpc +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (lpc *LinPermissionCreate) AddLinGroupIDs(ids ...int) *LinPermissionCreate { + lpc.mutation.AddLinGroupIDs(ids...) + return lpc +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (lpc *LinPermissionCreate) AddLinGroup(l ...*LinGroup) *LinPermissionCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpc.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinPermissionMutation object of the builder. +func (lpc *LinPermissionCreate) Mutation() *LinPermissionMutation { + return lpc.mutation +} + +// Save creates the LinPermission in the database. +func (lpc *LinPermissionCreate) Save(ctx context.Context) (*LinPermission, error) { + var ( + err error + node *LinPermission + ) + if len(lpc.hooks) == 0 { + if err = lpc.check(); err != nil { + return nil, err + } + node, err = lpc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lpc.check(); err != nil { + return nil, err + } + lpc.mutation = mutation + if node, err = lpc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lpc.hooks) - 1; i >= 0; i-- { + if lpc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lpc *LinPermissionCreate) SaveX(ctx context.Context) *LinPermission { + v, err := lpc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lpc *LinPermissionCreate) Exec(ctx context.Context) error { + _, err := lpc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpc *LinPermissionCreate) ExecX(ctx context.Context) { + if err := lpc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lpc *LinPermissionCreate) check() error { + if _, ok := lpc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} + } + if _, ok := lpc.mutation.Module(); !ok { + return &ValidationError{Name: "module", err: errors.New(`model: missing required field "module"`)} + } + if _, ok := lpc.mutation.Mount(); !ok { + return &ValidationError{Name: "mount", err: errors.New(`model: missing required field "mount"`)} + } + return nil +} + +func (lpc *LinPermissionCreate) sqlSave(ctx context.Context) (*LinPermission, error) { + _node, _spec := lpc.createSpec() + if err := sqlgraph.CreateNode(ctx, lpc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lpc *LinPermissionCreate) createSpec() (*LinPermission, *sqlgraph.CreateSpec) { + var ( + _node = &LinPermission{config: lpc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linpermission.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + } + ) + if value, ok := lpc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldName, + }) + _node.Name = value + } + if value, ok := lpc.mutation.Module(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldModule, + }) + _node.Module = value + } + if value, ok := lpc.mutation.Mount(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + _node.Mount = value + } + if nodes := lpc.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinPermissionCreateBulk is the builder for creating many LinPermission entities in bulk. +type LinPermissionCreateBulk struct { + config + builders []*LinPermissionCreate +} + +// Save creates the LinPermission entities in the database. +func (lpcb *LinPermissionCreateBulk) Save(ctx context.Context) ([]*LinPermission, error) { + specs := make([]*sqlgraph.CreateSpec, len(lpcb.builders)) + nodes := make([]*LinPermission, len(lpcb.builders)) + mutators := make([]Mutator, len(lpcb.builders)) + for i := range lpcb.builders { + func(i int, root context.Context) { + builder := lpcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lpcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lpcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lpcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lpcb *LinPermissionCreateBulk) SaveX(ctx context.Context) []*LinPermission { + v, err := lpcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lpcb *LinPermissionCreateBulk) Exec(ctx context.Context) error { + _, err := lpcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpcb *LinPermissionCreateBulk) ExecX(ctx context.Context) { + if err := lpcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linpermission_delete.go b/internal/data/model/linpermission_delete.go new file mode 100644 index 0000000..46660ba --- /dev/null +++ b/internal/data/model/linpermission_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionDelete is the builder for deleting a LinPermission entity. +type LinPermissionDelete struct { + config + hooks []Hook + mutation *LinPermissionMutation +} + +// Where appends a list predicates to the LinPermissionDelete builder. +func (lpd *LinPermissionDelete) Where(ps ...predicate.LinPermission) *LinPermissionDelete { + lpd.mutation.Where(ps...) + return lpd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lpd *LinPermissionDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lpd.hooks) == 0 { + affected, err = lpd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lpd.mutation = mutation + affected, err = lpd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lpd.hooks) - 1; i >= 0; i-- { + if lpd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpd *LinPermissionDelete) ExecX(ctx context.Context) int { + n, err := lpd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lpd *LinPermissionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + if ps := lpd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lpd.driver, _spec) +} + +// LinPermissionDeleteOne is the builder for deleting a single LinPermission entity. +type LinPermissionDeleteOne struct { + lpd *LinPermissionDelete +} + +// Exec executes the deletion query. +func (lpdo *LinPermissionDeleteOne) Exec(ctx context.Context) error { + n, err := lpdo.lpd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linpermission.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpdo *LinPermissionDeleteOne) ExecX(ctx context.Context) { + lpdo.lpd.ExecX(ctx) +} diff --git a/internal/data/model/linpermission_query.go b/internal/data/model/linpermission_query.go new file mode 100644 index 0000000..9ae25bc --- /dev/null +++ b/internal/data/model/linpermission_query.go @@ -0,0 +1,1068 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionQuery is the builder for querying LinPermission entities. +type LinPermissionQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinPermission + // eager-loading edges. + withLinGroup *LinGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinPermissionQuery builder. +func (lpq *LinPermissionQuery) Where(ps ...predicate.LinPermission) *LinPermissionQuery { + lpq.predicates = append(lpq.predicates, ps...) + return lpq +} + +// Limit adds a limit step to the query. +func (lpq *LinPermissionQuery) Limit(limit int) *LinPermissionQuery { + lpq.limit = &limit + return lpq +} + +// Offset adds an offset step to the query. +func (lpq *LinPermissionQuery) Offset(offset int) *LinPermissionQuery { + lpq.offset = &offset + return lpq +} + +// 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 (lpq *LinPermissionQuery) Unique(unique bool) *LinPermissionQuery { + lpq.unique = &unique + return lpq +} + +// Order adds an order step to the query. +func (lpq *LinPermissionQuery) Order(o ...OrderFunc) *LinPermissionQuery { + lpq.order = append(lpq.order, o...) + return lpq +} + +// QueryLinGroup chains the current query on the "lin_group" edge. +func (lpq *LinPermissionQuery) QueryLinGroup() *LinGroupQuery { + query := &LinGroupQuery{config: lpq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lpq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lpq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(linpermission.Table, linpermission.FieldID, selector), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, linpermission.LinGroupTable, linpermission.LinGroupPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lpq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LinPermission entity from the query. +// Returns a *NotFoundError when no LinPermission was found. +func (lpq *LinPermissionQuery) First(ctx context.Context) (*LinPermission, error) { + nodes, err := lpq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linpermission.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lpq *LinPermissionQuery) FirstX(ctx context.Context) *LinPermission { + node, err := lpq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinPermission ID from the query. +// Returns a *NotFoundError when no LinPermission ID was found. +func (lpq *LinPermissionQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lpq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linpermission.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lpq *LinPermissionQuery) FirstIDX(ctx context.Context) int { + id, err := lpq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinPermission entity from the query. +// Returns a *NotFoundError when no LinPermission was found. +func (lpq *LinPermissionQuery) Last(ctx context.Context) (*LinPermission, error) { + nodes, err := lpq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linpermission.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lpq *LinPermissionQuery) LastX(ctx context.Context) *LinPermission { + node, err := lpq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinPermission ID from the query. +// Returns a *NotFoundError when no LinPermission ID was found. +func (lpq *LinPermissionQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lpq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linpermission.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lpq *LinPermissionQuery) LastIDX(ctx context.Context) int { + id, err := lpq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinPermission entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinPermission entity is not found. +// Returns a *NotFoundError when no LinPermission entities are found. +func (lpq *LinPermissionQuery) Only(ctx context.Context) (*LinPermission, error) { + nodes, err := lpq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linpermission.Label} + default: + return nil, &NotSingularError{linpermission.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lpq *LinPermissionQuery) OnlyX(ctx context.Context) *LinPermission { + node, err := lpq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinPermission ID in the query. +// Returns a *NotSingularError when exactly one LinPermission ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lpq *LinPermissionQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lpq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = &NotSingularError{linpermission.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lpq *LinPermissionQuery) OnlyIDX(ctx context.Context) int { + id, err := lpq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinPermissions. +func (lpq *LinPermissionQuery) All(ctx context.Context) ([]*LinPermission, error) { + if err := lpq.prepareQuery(ctx); err != nil { + return nil, err + } + return lpq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lpq *LinPermissionQuery) AllX(ctx context.Context) []*LinPermission { + nodes, err := lpq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinPermission IDs. +func (lpq *LinPermissionQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lpq.Select(linpermission.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lpq *LinPermissionQuery) IDsX(ctx context.Context) []int { + ids, err := lpq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lpq *LinPermissionQuery) Count(ctx context.Context) (int, error) { + if err := lpq.prepareQuery(ctx); err != nil { + return 0, err + } + return lpq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lpq *LinPermissionQuery) CountX(ctx context.Context) int { + count, err := lpq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lpq *LinPermissionQuery) Exist(ctx context.Context) (bool, error) { + if err := lpq.prepareQuery(ctx); err != nil { + return false, err + } + return lpq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lpq *LinPermissionQuery) ExistX(ctx context.Context) bool { + exist, err := lpq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinPermissionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lpq *LinPermissionQuery) Clone() *LinPermissionQuery { + if lpq == nil { + return nil + } + return &LinPermissionQuery{ + config: lpq.config, + limit: lpq.limit, + offset: lpq.offset, + order: append([]OrderFunc{}, lpq.order...), + predicates: append([]predicate.LinPermission{}, lpq.predicates...), + withLinGroup: lpq.withLinGroup.Clone(), + // clone intermediate query. + sql: lpq.sql.Clone(), + path: lpq.path, + } +} + +// WithLinGroup tells the query-builder to eager-load the nodes that are connected to +// the "lin_group" edge. The optional arguments are used to configure the query builder of the edge. +func (lpq *LinPermissionQuery) WithLinGroup(opts ...func(*LinGroupQuery)) *LinPermissionQuery { + query := &LinGroupQuery{config: lpq.config} + for _, opt := range opts { + opt(query) + } + lpq.withLinGroup = query + return lpq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinPermission.Query(). +// GroupBy(linpermission.FieldName). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lpq *LinPermissionQuery) GroupBy(field string, fields ...string) *LinPermissionGroupBy { + group := &LinPermissionGroupBy{config: lpq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lpq.prepareQuery(ctx); err != nil { + return nil, err + } + return lpq.sqlQuery(ctx), nil + } + return group +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.LinPermission.Query(). +// Select(linpermission.FieldName). +// Scan(ctx, &v) +// +func (lpq *LinPermissionQuery) Select(fields ...string) *LinPermissionSelect { + lpq.fields = append(lpq.fields, fields...) + return &LinPermissionSelect{LinPermissionQuery: lpq} +} + +func (lpq *LinPermissionQuery) prepareQuery(ctx context.Context) error { + for _, f := range lpq.fields { + if !linpermission.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lpq.path != nil { + prev, err := lpq.path(ctx) + if err != nil { + return err + } + lpq.sql = prev + } + return nil +} + +func (lpq *LinPermissionQuery) sqlAll(ctx context.Context) ([]*LinPermission, error) { + var ( + nodes = []*LinPermission{} + _spec = lpq.querySpec() + loadedTypes = [1]bool{ + lpq.withLinGroup != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinPermission{config: lpq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lpq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := lpq.withLinGroup; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinPermission, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinGroup = []*LinGroup{} + } + var ( + edgeids []int + edges = make(map[int][]*LinPermission) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(linpermission.LinGroupPrimaryKey[0], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, lpq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_group": %w`, err) + } + query.Where(lingroup.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_group" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinGroup = append(nodes[i].Edges.LinGroup, n) + } + } + } + + return nodes, nil +} + +func (lpq *LinPermissionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lpq.querySpec() + return sqlgraph.CountNodes(ctx, lpq.driver, _spec) +} + +func (lpq *LinPermissionQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lpq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lpq *LinPermissionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + Columns: linpermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + From: lpq.sql, + Unique: true, + } + if unique := lpq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lpq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linpermission.FieldID) + for i := range fields { + if fields[i] != linpermission.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lpq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lpq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lpq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lpq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lpq *LinPermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lpq.driver.Dialect()) + t1 := builder.Table(linpermission.Table) + columns := lpq.fields + if len(columns) == 0 { + columns = linpermission.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lpq.sql != nil { + selector = lpq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lpq.predicates { + p(selector) + } + for _, p := range lpq.order { + p(selector) + } + if offset := lpq.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 := lpq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinPermissionGroupBy is the group-by builder for LinPermission entities. +type LinPermissionGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lpgb *LinPermissionGroupBy) Aggregate(fns ...AggregateFunc) *LinPermissionGroupBy { + lpgb.fns = append(lpgb.fns, fns...) + return lpgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lpgb *LinPermissionGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lpgb.path(ctx) + if err != nil { + return err + } + lpgb.sql = query + return lpgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lpgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) StringsX(ctx context.Context) []string { + v, err := lpgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lpgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) StringX(ctx context.Context) string { + v, err := lpgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) IntsX(ctx context.Context) []int { + v, err := lpgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lpgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) IntX(ctx context.Context) int { + v, err := lpgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lpgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lpgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) Float64X(ctx context.Context) float64 { + v, err := lpgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lpgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lpgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) BoolX(ctx context.Context) bool { + v, err := lpgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lpgb *LinPermissionGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lpgb.fields { + if !linpermission.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lpgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lpgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lpgb *LinPermissionGroupBy) sqlQuery() *sql.Selector { + selector := lpgb.sql.Select() + aggregation := make([]string, 0, len(lpgb.fns)) + for _, fn := range lpgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lpgb.fields)+len(lpgb.fns)) + for _, f := range lpgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lpgb.fields...)...) +} + +// LinPermissionSelect is the builder for selecting fields of LinPermission entities. +type LinPermissionSelect struct { + *LinPermissionQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lps *LinPermissionSelect) Scan(ctx context.Context, v interface{}) error { + if err := lps.prepareQuery(ctx); err != nil { + return err + } + lps.sql = lps.LinPermissionQuery.sqlQuery(ctx) + return lps.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lps *LinPermissionSelect) ScanX(ctx context.Context, v interface{}) { + if err := lps.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Strings(ctx context.Context) ([]string, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lps *LinPermissionSelect) StringsX(ctx context.Context) []string { + v, err := lps.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lps.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lps *LinPermissionSelect) StringX(ctx context.Context) string { + v, err := lps.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Ints(ctx context.Context) ([]int, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lps *LinPermissionSelect) IntsX(ctx context.Context) []int { + v, err := lps.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lps.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lps *LinPermissionSelect) IntX(ctx context.Context) int { + v, err := lps.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lps *LinPermissionSelect) Float64sX(ctx context.Context) []float64 { + v, err := lps.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lps.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lps *LinPermissionSelect) Float64X(ctx context.Context) float64 { + v, err := lps.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lps *LinPermissionSelect) BoolsX(ctx context.Context) []bool { + v, err := lps.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lps.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lps *LinPermissionSelect) BoolX(ctx context.Context) bool { + v, err := lps.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lps *LinPermissionSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lps.sql.Query() + if err := lps.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linpermission_update.go b/internal/data/model/linpermission_update.go new file mode 100644 index 0000000..cbc1e37 --- /dev/null +++ b/internal/data/model/linpermission_update.go @@ -0,0 +1,525 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionUpdate is the builder for updating LinPermission entities. +type LinPermissionUpdate struct { + config + hooks []Hook + mutation *LinPermissionMutation +} + +// Where appends a list predicates to the LinPermissionUpdate builder. +func (lpu *LinPermissionUpdate) Where(ps ...predicate.LinPermission) *LinPermissionUpdate { + lpu.mutation.Where(ps...) + return lpu +} + +// SetName sets the "name" field. +func (lpu *LinPermissionUpdate) SetName(s string) *LinPermissionUpdate { + lpu.mutation.SetName(s) + return lpu +} + +// SetModule sets the "module" field. +func (lpu *LinPermissionUpdate) SetModule(s string) *LinPermissionUpdate { + lpu.mutation.SetModule(s) + return lpu +} + +// SetMount sets the "mount" field. +func (lpu *LinPermissionUpdate) SetMount(i int8) *LinPermissionUpdate { + lpu.mutation.ResetMount() + lpu.mutation.SetMount(i) + return lpu +} + +// AddMount adds i to the "mount" field. +func (lpu *LinPermissionUpdate) AddMount(i int8) *LinPermissionUpdate { + lpu.mutation.AddMount(i) + return lpu +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (lpu *LinPermissionUpdate) AddLinGroupIDs(ids ...int) *LinPermissionUpdate { + lpu.mutation.AddLinGroupIDs(ids...) + return lpu +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (lpu *LinPermissionUpdate) AddLinGroup(l ...*LinGroup) *LinPermissionUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpu.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinPermissionMutation object of the builder. +func (lpu *LinPermissionUpdate) Mutation() *LinPermissionMutation { + return lpu.mutation +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (lpu *LinPermissionUpdate) ClearLinGroup() *LinPermissionUpdate { + lpu.mutation.ClearLinGroup() + return lpu +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (lpu *LinPermissionUpdate) RemoveLinGroupIDs(ids ...int) *LinPermissionUpdate { + lpu.mutation.RemoveLinGroupIDs(ids...) + return lpu +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (lpu *LinPermissionUpdate) RemoveLinGroup(l ...*LinGroup) *LinPermissionUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpu.RemoveLinGroupIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lpu *LinPermissionUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lpu.hooks) == 0 { + affected, err = lpu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lpu.mutation = mutation + affected, err = lpu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lpu.hooks) - 1; i >= 0; i-- { + if lpu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lpu *LinPermissionUpdate) SaveX(ctx context.Context) int { + affected, err := lpu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lpu *LinPermissionUpdate) Exec(ctx context.Context) error { + _, err := lpu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpu *LinPermissionUpdate) ExecX(ctx context.Context) { + if err := lpu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lpu *LinPermissionUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + Columns: linpermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + if ps := lpu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lpu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldName, + }) + } + if value, ok := lpu.mutation.Module(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldModule, + }) + } + if value, ok := lpu.mutation.Mount(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if value, ok := lpu.mutation.AddedMount(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if lpu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpu.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !lpu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpu.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, lpu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linpermission.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinPermissionUpdateOne is the builder for updating a single LinPermission entity. +type LinPermissionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinPermissionMutation +} + +// SetName sets the "name" field. +func (lpuo *LinPermissionUpdateOne) SetName(s string) *LinPermissionUpdateOne { + lpuo.mutation.SetName(s) + return lpuo +} + +// SetModule sets the "module" field. +func (lpuo *LinPermissionUpdateOne) SetModule(s string) *LinPermissionUpdateOne { + lpuo.mutation.SetModule(s) + return lpuo +} + +// SetMount sets the "mount" field. +func (lpuo *LinPermissionUpdateOne) SetMount(i int8) *LinPermissionUpdateOne { + lpuo.mutation.ResetMount() + lpuo.mutation.SetMount(i) + return lpuo +} + +// AddMount adds i to the "mount" field. +func (lpuo *LinPermissionUpdateOne) AddMount(i int8) *LinPermissionUpdateOne { + lpuo.mutation.AddMount(i) + return lpuo +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (lpuo *LinPermissionUpdateOne) AddLinGroupIDs(ids ...int) *LinPermissionUpdateOne { + lpuo.mutation.AddLinGroupIDs(ids...) + return lpuo +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (lpuo *LinPermissionUpdateOne) AddLinGroup(l ...*LinGroup) *LinPermissionUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpuo.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinPermissionMutation object of the builder. +func (lpuo *LinPermissionUpdateOne) Mutation() *LinPermissionMutation { + return lpuo.mutation +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (lpuo *LinPermissionUpdateOne) ClearLinGroup() *LinPermissionUpdateOne { + lpuo.mutation.ClearLinGroup() + return lpuo +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (lpuo *LinPermissionUpdateOne) RemoveLinGroupIDs(ids ...int) *LinPermissionUpdateOne { + lpuo.mutation.RemoveLinGroupIDs(ids...) + return lpuo +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (lpuo *LinPermissionUpdateOne) RemoveLinGroup(l ...*LinGroup) *LinPermissionUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpuo.RemoveLinGroupIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lpuo *LinPermissionUpdateOne) Select(field string, fields ...string) *LinPermissionUpdateOne { + lpuo.fields = append([]string{field}, fields...) + return lpuo +} + +// Save executes the query and returns the updated LinPermission entity. +func (lpuo *LinPermissionUpdateOne) Save(ctx context.Context) (*LinPermission, error) { + var ( + err error + node *LinPermission + ) + if len(lpuo.hooks) == 0 { + node, err = lpuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lpuo.mutation = mutation + node, err = lpuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lpuo.hooks) - 1; i >= 0; i-- { + if lpuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lpuo *LinPermissionUpdateOne) SaveX(ctx context.Context) *LinPermission { + node, err := lpuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lpuo *LinPermissionUpdateOne) Exec(ctx context.Context) error { + _, err := lpuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpuo *LinPermissionUpdateOne) ExecX(ctx context.Context) { + if err := lpuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lpuo *LinPermissionUpdateOne) sqlSave(ctx context.Context) (_node *LinPermission, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + Columns: linpermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + id, ok := lpuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinPermission.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lpuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linpermission.FieldID) + for _, f := range fields { + if !linpermission.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linpermission.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lpuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lpuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldName, + }) + } + if value, ok := lpuo.mutation.Module(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldModule, + }) + } + if value, ok := lpuo.mutation.Mount(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if value, ok := lpuo.mutation.AddedMount(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if lpuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpuo.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !lpuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpuo.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LinPermission{config: lpuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lpuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linpermission.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linuser.go b/internal/data/model/linuser.go new file mode 100644 index 0000000..1a587e7 --- /dev/null +++ b/internal/data/model/linuser.go @@ -0,0 +1,208 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linuser" + "strings" + "time" + + "entgo.io/ent/dialect/sql" +) + +// LinUser is the model entity for the LinUser schema. +type LinUser struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` + // Username holds the value of the "username" field. + // 用户名,唯一 + Username string `json:"username,omitempty"` + // Nickname holds the value of the "nickname" field. + // 用户昵称 + Nickname string `json:"nickname,omitempty"` + // Avatar holds the value of the "avatar" field. + // 头像url + Avatar string `json:"avatar,omitempty"` + // Email holds the value of the "email" field. + // 邮箱 + Email string `json:"email,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinUserQuery when eager-loading is set. + Edges LinUserEdges `json:"edges"` +} + +// LinUserEdges holds the relations/edges for other nodes in the graph. +type LinUserEdges struct { + // LinUserIdentiy holds the value of the lin_user_identiy edge. + LinUserIdentiy []*LinUserIdentiy `json:"lin_user_identiy,omitempty"` + // LinGroup holds the value of the lin_group edge. + LinGroup []*LinGroup `json:"lin_group,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// LinUserIdentiyOrErr returns the LinUserIdentiy value or an error if the edge +// was not loaded in eager-loading. +func (e LinUserEdges) LinUserIdentiyOrErr() ([]*LinUserIdentiy, error) { + if e.loadedTypes[0] { + return e.LinUserIdentiy, nil + } + return nil, &NotLoadedError{edge: "lin_user_identiy"} +} + +// LinGroupOrErr returns the LinGroup value or an error if the edge +// was not loaded in eager-loading. +func (e LinUserEdges) LinGroupOrErr() ([]*LinGroup, error) { + if e.loadedTypes[1] { + return e.LinGroup, nil + } + return nil, &NotLoadedError{edge: "lin_group"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinUser) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linuser.FieldID: + values[i] = new(sql.NullInt64) + case linuser.FieldUsername, linuser.FieldNickname, linuser.FieldAvatar, linuser.FieldEmail: + values[i] = new(sql.NullString) + case linuser.FieldCreateTime, linuser.FieldUpdateTime, linuser.FieldDeleteTime: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type LinUser", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinUser fields. +func (lu *LinUser) assignValues(columns []string, values []interface{}) 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 linuser.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lu.ID = int(value.Int64) + case linuser.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + lu.CreateTime = value.Time + } + case linuser.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + lu.UpdateTime = value.Time + } + case linuser.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + lu.DeleteTime = value.Time + } + case linuser.FieldUsername: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value.Valid { + lu.Username = value.String + } + case linuser.FieldNickname: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field nickname", values[i]) + } else if value.Valid { + lu.Nickname = value.String + } + case linuser.FieldAvatar: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field avatar", values[i]) + } else if value.Valid { + lu.Avatar = value.String + } + case linuser.FieldEmail: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field email", values[i]) + } else if value.Valid { + lu.Email = value.String + } + } + } + return nil +} + +// QueryLinUserIdentiy queries the "lin_user_identiy" edge of the LinUser entity. +func (lu *LinUser) QueryLinUserIdentiy() *LinUserIdentiyQuery { + return (&LinUserClient{config: lu.config}).QueryLinUserIdentiy(lu) +} + +// QueryLinGroup queries the "lin_group" edge of the LinUser entity. +func (lu *LinUser) QueryLinGroup() *LinGroupQuery { + return (&LinUserClient{config: lu.config}).QueryLinGroup(lu) +} + +// Update returns a builder for updating this LinUser. +// Note that you need to call LinUser.Unwrap() before calling this method if this LinUser +// was returned from a transaction, and the transaction was committed or rolled back. +func (lu *LinUser) Update() *LinUserUpdateOne { + return (&LinUserClient{config: lu.config}).UpdateOne(lu) +} + +// Unwrap unwraps the LinUser 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 (lu *LinUser) Unwrap() *LinUser { + tx, ok := lu.config.driver.(*txDriver) + if !ok { + panic("model: LinUser is not a transactional entity") + } + lu.config.driver = tx.drv + return lu +} + +// String implements the fmt.Stringer. +func (lu *LinUser) String() string { + var builder strings.Builder + builder.WriteString("LinUser(") + builder.WriteString(fmt.Sprintf("id=%v", lu.ID)) + builder.WriteString(", create_time=") + builder.WriteString(lu.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(lu.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(lu.DeleteTime.Format(time.ANSIC)) + builder.WriteString(", username=") + builder.WriteString(lu.Username) + builder.WriteString(", nickname=") + builder.WriteString(lu.Nickname) + builder.WriteString(", avatar=") + builder.WriteString(lu.Avatar) + builder.WriteString(", email=") + builder.WriteString(lu.Email) + builder.WriteByte(')') + return builder.String() +} + +// LinUsers is a parsable slice of LinUser. +type LinUsers []*LinUser + +func (lu LinUsers) config(cfg config) { + for _i := range lu { + lu[_i].config = cfg + } +} diff --git a/internal/data/model/linuser/linuser.go b/internal/data/model/linuser/linuser.go new file mode 100644 index 0000000..8943e07 --- /dev/null +++ b/internal/data/model/linuser/linuser.go @@ -0,0 +1,87 @@ +// Code generated by entc, DO NOT EDIT. + +package linuser + +import ( + "time" +) + +const ( + // Label holds the string label denoting the linuser type in the database. + Label = "lin_user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldNickname holds the string denoting the nickname field in the database. + FieldNickname = "nickname" + // FieldAvatar holds the string denoting the avatar field in the database. + FieldAvatar = "avatar" + // FieldEmail holds the string denoting the email field in the database. + FieldEmail = "email" + // EdgeLinUserIdentiy holds the string denoting the lin_user_identiy edge name in mutations. + EdgeLinUserIdentiy = "lin_user_identiy" + // EdgeLinGroup holds the string denoting the lin_group edge name in mutations. + EdgeLinGroup = "lin_group" + // Table holds the table name of the linuser in the database. + Table = "lin_user" + // LinUserIdentiyTable is the table that holds the lin_user_identiy relation/edge. + LinUserIdentiyTable = "lin_user_identiy" + // LinUserIdentiyInverseTable is the table name for the LinUserIdentiy entity. + // It exists in this package in order to avoid circular dependency with the "linuseridentiy" package. + LinUserIdentiyInverseTable = "lin_user_identiy" + // LinUserIdentiyColumn is the table column denoting the lin_user_identiy relation/edge. + LinUserIdentiyColumn = "lin_user_lin_user_identiy" + // LinGroupTable is the table that holds the lin_group relation/edge. The primary key declared below. + LinGroupTable = "lin_user_group" + // LinGroupInverseTable is the table name for the LinGroup entity. + // It exists in this package in order to avoid circular dependency with the "lingroup" package. + LinGroupInverseTable = "lin_group" +) + +// Columns holds all SQL columns for linuser fields. +var Columns = []string{ + FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldUsername, + FieldNickname, + FieldAvatar, + FieldEmail, +} + +var ( + // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the + // primary key for the lin_group relation (M2M). + LinGroupPrimaryKey = []string{"user_id", "group_id"} +) + +// 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 ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // DefaultDeleteTime holds the default value on creation for the "delete_time" field. + DefaultDeleteTime func() time.Time + // DefaultAvatar holds the default value on creation for the "avatar" field. + DefaultAvatar string +) diff --git a/internal/data/model/linuser/where.go b/internal/data/model/linuser/where.go new file mode 100644 index 0000000..2b13f11 --- /dev/null +++ b/internal/data/model/linuser/where.go @@ -0,0 +1,903 @@ +// Code generated by entc, DO NOT EDIT. + +package linuser + +import ( + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ. +func Nickname(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNickname), v)) + }) +} + +// Avatar applies equality check predicate on the "avatar" field. It's identical to AvatarEQ. +func Avatar(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAvatar), v)) + }) +} + +// Email applies equality check predicate on the "email" field. It's identical to EmailEQ. +func Email(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEmail), v)) + }) +} + +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUsername), v)) + }) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUsername), v...)) + }) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUsername), v...)) + }) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUsername), v)) + }) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUsername), v)) + }) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUsername), v)) + }) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUsername), v)) + }) +} + +// UsernameContains applies the Contains predicate on the "username" field. +func UsernameContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldUsername), v)) + }) +} + +// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. +func UsernameHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldUsername), v)) + }) +} + +// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. +func UsernameHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldUsername), v)) + }) +} + +// UsernameEqualFold applies the EqualFold predicate on the "username" field. +func UsernameEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldUsername), v)) + }) +} + +// UsernameContainsFold applies the ContainsFold predicate on the "username" field. +func UsernameContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldUsername), v)) + }) +} + +// NicknameEQ applies the EQ predicate on the "nickname" field. +func NicknameEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNickname), v)) + }) +} + +// NicknameNEQ applies the NEQ predicate on the "nickname" field. +func NicknameNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldNickname), v)) + }) +} + +// NicknameIn applies the In predicate on the "nickname" field. +func NicknameIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldNickname), v...)) + }) +} + +// NicknameNotIn applies the NotIn predicate on the "nickname" field. +func NicknameNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldNickname), v...)) + }) +} + +// NicknameGT applies the GT predicate on the "nickname" field. +func NicknameGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldNickname), v)) + }) +} + +// NicknameGTE applies the GTE predicate on the "nickname" field. +func NicknameGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldNickname), v)) + }) +} + +// NicknameLT applies the LT predicate on the "nickname" field. +func NicknameLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldNickname), v)) + }) +} + +// NicknameLTE applies the LTE predicate on the "nickname" field. +func NicknameLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldNickname), v)) + }) +} + +// NicknameContains applies the Contains predicate on the "nickname" field. +func NicknameContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldNickname), v)) + }) +} + +// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field. +func NicknameHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldNickname), v)) + }) +} + +// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field. +func NicknameHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldNickname), v)) + }) +} + +// NicknameEqualFold applies the EqualFold predicate on the "nickname" field. +func NicknameEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldNickname), v)) + }) +} + +// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field. +func NicknameContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldNickname), v)) + }) +} + +// AvatarEQ applies the EQ predicate on the "avatar" field. +func AvatarEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAvatar), v)) + }) +} + +// AvatarNEQ applies the NEQ predicate on the "avatar" field. +func AvatarNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAvatar), v)) + }) +} + +// AvatarIn applies the In predicate on the "avatar" field. +func AvatarIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAvatar), v...)) + }) +} + +// AvatarNotIn applies the NotIn predicate on the "avatar" field. +func AvatarNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAvatar), v...)) + }) +} + +// AvatarGT applies the GT predicate on the "avatar" field. +func AvatarGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAvatar), v)) + }) +} + +// AvatarGTE applies the GTE predicate on the "avatar" field. +func AvatarGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAvatar), v)) + }) +} + +// AvatarLT applies the LT predicate on the "avatar" field. +func AvatarLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAvatar), v)) + }) +} + +// AvatarLTE applies the LTE predicate on the "avatar" field. +func AvatarLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAvatar), v)) + }) +} + +// AvatarContains applies the Contains predicate on the "avatar" field. +func AvatarContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldAvatar), v)) + }) +} + +// AvatarHasPrefix applies the HasPrefix predicate on the "avatar" field. +func AvatarHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldAvatar), v)) + }) +} + +// AvatarHasSuffix applies the HasSuffix predicate on the "avatar" field. +func AvatarHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldAvatar), v)) + }) +} + +// AvatarEqualFold applies the EqualFold predicate on the "avatar" field. +func AvatarEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldAvatar), v)) + }) +} + +// AvatarContainsFold applies the ContainsFold predicate on the "avatar" field. +func AvatarContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldAvatar), v)) + }) +} + +// EmailEQ applies the EQ predicate on the "email" field. +func EmailEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEmail), v)) + }) +} + +// EmailNEQ applies the NEQ predicate on the "email" field. +func EmailNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldEmail), v)) + }) +} + +// EmailIn applies the In predicate on the "email" field. +func EmailIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldEmail), v...)) + }) +} + +// EmailNotIn applies the NotIn predicate on the "email" field. +func EmailNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldEmail), v...)) + }) +} + +// EmailGT applies the GT predicate on the "email" field. +func EmailGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldEmail), v)) + }) +} + +// EmailGTE applies the GTE predicate on the "email" field. +func EmailGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldEmail), v)) + }) +} + +// EmailLT applies the LT predicate on the "email" field. +func EmailLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldEmail), v)) + }) +} + +// EmailLTE applies the LTE predicate on the "email" field. +func EmailLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldEmail), v)) + }) +} + +// EmailContains applies the Contains predicate on the "email" field. +func EmailContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldEmail), v)) + }) +} + +// EmailHasPrefix applies the HasPrefix predicate on the "email" field. +func EmailHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldEmail), v)) + }) +} + +// EmailHasSuffix applies the HasSuffix predicate on the "email" field. +func EmailHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldEmail), v)) + }) +} + +// EmailEqualFold applies the EqualFold predicate on the "email" field. +func EmailEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldEmail), v)) + }) +} + +// EmailContainsFold applies the ContainsFold predicate on the "email" field. +func EmailContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldEmail), v)) + }) +} + +// HasLinUserIdentiy applies the HasEdge predicate on the "lin_user_identiy" edge. +func HasLinUserIdentiy() predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserIdentiyTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, LinUserIdentiyTable, LinUserIdentiyColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinUserIdentiyWith applies the HasEdge predicate on the "lin_user_identiy" edge with a given conditions (other predicates). +func HasLinUserIdentiyWith(preds ...predicate.LinUserIdentiy) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserIdentiyInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, LinUserIdentiyTable, LinUserIdentiyColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasLinGroup applies the HasEdge predicate on the "lin_group" edge. +func HasLinGroup() predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinGroupTable, LinGroupPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinGroupWith applies the HasEdge predicate on the "lin_group" edge with a given conditions (other predicates). +func HasLinGroupWith(preds ...predicate.LinGroup) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinGroupTable, LinGroupPrimaryKey...), + ) + 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.LinUser) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinUser) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinUser) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linuser_create.go b/internal/data/model/linuser_create.go new file mode 100644 index 0000000..60825f5 --- /dev/null +++ b/internal/data/model/linuser_create.go @@ -0,0 +1,447 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserCreate is the builder for creating a LinUser entity. +type LinUserCreate struct { + config + mutation *LinUserMutation + hooks []Hook +} + +// SetCreateTime sets the "create_time" field. +func (luc *LinUserCreate) SetCreateTime(t time.Time) *LinUserCreate { + luc.mutation.SetCreateTime(t) + return luc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableCreateTime(t *time.Time) *LinUserCreate { + if t != nil { + luc.SetCreateTime(*t) + } + return luc +} + +// SetUpdateTime sets the "update_time" field. +func (luc *LinUserCreate) SetUpdateTime(t time.Time) *LinUserCreate { + luc.mutation.SetUpdateTime(t) + return luc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableUpdateTime(t *time.Time) *LinUserCreate { + if t != nil { + luc.SetUpdateTime(*t) + } + return luc +} + +// SetDeleteTime sets the "delete_time" field. +func (luc *LinUserCreate) SetDeleteTime(t time.Time) *LinUserCreate { + luc.mutation.SetDeleteTime(t) + return luc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableDeleteTime(t *time.Time) *LinUserCreate { + if t != nil { + luc.SetDeleteTime(*t) + } + return luc +} + +// SetUsername sets the "username" field. +func (luc *LinUserCreate) SetUsername(s string) *LinUserCreate { + luc.mutation.SetUsername(s) + return luc +} + +// SetNickname sets the "nickname" field. +func (luc *LinUserCreate) SetNickname(s string) *LinUserCreate { + luc.mutation.SetNickname(s) + return luc +} + +// SetAvatar sets the "avatar" field. +func (luc *LinUserCreate) SetAvatar(s string) *LinUserCreate { + luc.mutation.SetAvatar(s) + return luc +} + +// SetNillableAvatar sets the "avatar" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableAvatar(s *string) *LinUserCreate { + if s != nil { + luc.SetAvatar(*s) + } + return luc +} + +// SetEmail sets the "email" field. +func (luc *LinUserCreate) SetEmail(s string) *LinUserCreate { + luc.mutation.SetEmail(s) + return luc +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (luc *LinUserCreate) AddLinUserIdentiyIDs(ids ...int) *LinUserCreate { + luc.mutation.AddLinUserIdentiyIDs(ids...) + return luc +} + +// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luc *LinUserCreate) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luc.AddLinUserIdentiyIDs(ids...) +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (luc *LinUserCreate) AddLinGroupIDs(ids ...int) *LinUserCreate { + luc.mutation.AddLinGroupIDs(ids...) + return luc +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (luc *LinUserCreate) AddLinGroup(l ...*LinGroup) *LinUserCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luc.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinUserMutation object of the builder. +func (luc *LinUserCreate) Mutation() *LinUserMutation { + return luc.mutation +} + +// Save creates the LinUser in the database. +func (luc *LinUserCreate) Save(ctx context.Context) (*LinUser, error) { + var ( + err error + node *LinUser + ) + luc.defaults() + if len(luc.hooks) == 0 { + if err = luc.check(); err != nil { + return nil, err + } + node, err = luc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = luc.check(); err != nil { + return nil, err + } + luc.mutation = mutation + if node, err = luc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(luc.hooks) - 1; i >= 0; i-- { + if luc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (luc *LinUserCreate) SaveX(ctx context.Context) *LinUser { + v, err := luc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (luc *LinUserCreate) Exec(ctx context.Context) error { + _, err := luc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luc *LinUserCreate) ExecX(ctx context.Context) { + if err := luc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (luc *LinUserCreate) defaults() { + if _, ok := luc.mutation.CreateTime(); !ok { + v := linuser.DefaultCreateTime() + luc.mutation.SetCreateTime(v) + } + if _, ok := luc.mutation.UpdateTime(); !ok { + v := linuser.DefaultUpdateTime() + luc.mutation.SetUpdateTime(v) + } + if _, ok := luc.mutation.DeleteTime(); !ok { + v := linuser.DefaultDeleteTime() + luc.mutation.SetDeleteTime(v) + } + if _, ok := luc.mutation.Avatar(); !ok { + v := linuser.DefaultAvatar + luc.mutation.SetAvatar(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (luc *LinUserCreate) check() error { + if _, ok := luc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := luc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } + if _, ok := luc.mutation.DeleteTime(); !ok { + return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} + } + if _, ok := luc.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} + } + if _, ok := luc.mutation.Nickname(); !ok { + return &ValidationError{Name: "nickname", err: errors.New(`model: missing required field "nickname"`)} + } + if _, ok := luc.mutation.Avatar(); !ok { + return &ValidationError{Name: "avatar", err: errors.New(`model: missing required field "avatar"`)} + } + if _, ok := luc.mutation.Email(); !ok { + return &ValidationError{Name: "email", err: errors.New(`model: missing required field "email"`)} + } + return nil +} + +func (luc *LinUserCreate) sqlSave(ctx context.Context) (*LinUser, error) { + _node, _spec := luc.createSpec() + if err := sqlgraph.CreateNode(ctx, luc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (luc *LinUserCreate) createSpec() (*LinUser, *sqlgraph.CreateSpec) { + var ( + _node = &LinUser{config: luc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linuser.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + } + ) + if value, ok := luc.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := luc.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := luc.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldDeleteTime, + }) + _node.DeleteTime = value + } + if value, ok := luc.mutation.Username(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldUsername, + }) + _node.Username = value + } + if value, ok := luc.mutation.Nickname(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldNickname, + }) + _node.Nickname = value + } + if value, ok := luc.mutation.Avatar(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldAvatar, + }) + _node.Avatar = value + } + if value, ok := luc.mutation.Email(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldEmail, + }) + _node.Email = value + } + if nodes := luc.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := luc.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinUserCreateBulk is the builder for creating many LinUser entities in bulk. +type LinUserCreateBulk struct { + config + builders []*LinUserCreate +} + +// Save creates the LinUser entities in the database. +func (lucb *LinUserCreateBulk) Save(ctx context.Context) ([]*LinUser, error) { + specs := make([]*sqlgraph.CreateSpec, len(lucb.builders)) + nodes := make([]*LinUser, len(lucb.builders)) + mutators := make([]Mutator, len(lucb.builders)) + for i := range lucb.builders { + func(i int, root context.Context) { + builder := lucb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lucb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lucb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lucb *LinUserCreateBulk) SaveX(ctx context.Context) []*LinUser { + v, err := lucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lucb *LinUserCreateBulk) Exec(ctx context.Context) error { + _, err := lucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lucb *LinUserCreateBulk) ExecX(ctx context.Context) { + if err := lucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linuser_delete.go b/internal/data/model/linuser_delete.go new file mode 100644 index 0000000..13c22cd --- /dev/null +++ b/internal/data/model/linuser_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserDelete is the builder for deleting a LinUser entity. +type LinUserDelete struct { + config + hooks []Hook + mutation *LinUserMutation +} + +// Where appends a list predicates to the LinUserDelete builder. +func (lud *LinUserDelete) Where(ps ...predicate.LinUser) *LinUserDelete { + lud.mutation.Where(ps...) + return lud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lud *LinUserDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lud.hooks) == 0 { + affected, err = lud.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lud.mutation = mutation + affected, err = lud.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lud.hooks) - 1; i >= 0; i-- { + if lud.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lud.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lud.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lud *LinUserDelete) ExecX(ctx context.Context) int { + n, err := lud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lud *LinUserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + if ps := lud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lud.driver, _spec) +} + +// LinUserDeleteOne is the builder for deleting a single LinUser entity. +type LinUserDeleteOne struct { + lud *LinUserDelete +} + +// Exec executes the deletion query. +func (ludo *LinUserDeleteOne) Exec(ctx context.Context) error { + n, err := ludo.lud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linuser.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ludo *LinUserDeleteOne) ExecX(ctx context.Context) { + ludo.lud.ExecX(ctx) +} diff --git a/internal/data/model/linuser_query.go b/internal/data/model/linuser_query.go new file mode 100644 index 0000000..fb1ddf2 --- /dev/null +++ b/internal/data/model/linuser_query.go @@ -0,0 +1,1134 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserQuery is the builder for querying LinUser entities. +type LinUserQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinUser + // eager-loading edges. + withLinUserIdentiy *LinUserIdentiyQuery + withLinGroup *LinGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinUserQuery builder. +func (luq *LinUserQuery) Where(ps ...predicate.LinUser) *LinUserQuery { + luq.predicates = append(luq.predicates, ps...) + return luq +} + +// Limit adds a limit step to the query. +func (luq *LinUserQuery) Limit(limit int) *LinUserQuery { + luq.limit = &limit + return luq +} + +// Offset adds an offset step to the query. +func (luq *LinUserQuery) Offset(offset int) *LinUserQuery { + luq.offset = &offset + return luq +} + +// 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 (luq *LinUserQuery) Unique(unique bool) *LinUserQuery { + luq.unique = &unique + return luq +} + +// Order adds an order step to the query. +func (luq *LinUserQuery) Order(o ...OrderFunc) *LinUserQuery { + luq.order = append(luq.order, o...) + return luq +} + +// QueryLinUserIdentiy chains the current query on the "lin_user_identiy" edge. +func (luq *LinUserQuery) QueryLinUserIdentiy() *LinUserIdentiyQuery { + query := &LinUserIdentiyQuery{config: luq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := luq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, selector), + sqlgraph.To(linuseridentiy.Table, linuseridentiy.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, linuser.LinUserIdentiyTable, linuser.LinUserIdentiyColumn), + ) + fromU = sqlgraph.SetNeighbors(luq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryLinGroup chains the current query on the "lin_group" edge. +func (luq *LinUserQuery) QueryLinGroup() *LinGroupQuery { + query := &LinGroupQuery{config: luq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := luq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, selector), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, linuser.LinGroupTable, linuser.LinGroupPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(luq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LinUser entity from the query. +// Returns a *NotFoundError when no LinUser was found. +func (luq *LinUserQuery) First(ctx context.Context) (*LinUser, error) { + nodes, err := luq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuser.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (luq *LinUserQuery) FirstX(ctx context.Context) *LinUser { + node, err := luq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinUser ID from the query. +// Returns a *NotFoundError when no LinUser ID was found. +func (luq *LinUserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuser.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (luq *LinUserQuery) FirstIDX(ctx context.Context) int { + id, err := luq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinUser entity from the query. +// Returns a *NotFoundError when no LinUser was found. +func (luq *LinUserQuery) Last(ctx context.Context) (*LinUser, error) { + nodes, err := luq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuser.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (luq *LinUserQuery) LastX(ctx context.Context) *LinUser { + node, err := luq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinUser ID from the query. +// Returns a *NotFoundError when no LinUser ID was found. +func (luq *LinUserQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuser.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (luq *LinUserQuery) LastIDX(ctx context.Context) int { + id, err := luq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinUser entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinUser entity is not found. +// Returns a *NotFoundError when no LinUser entities are found. +func (luq *LinUserQuery) Only(ctx context.Context) (*LinUser, error) { + nodes, err := luq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linuser.Label} + default: + return nil, &NotSingularError{linuser.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (luq *LinUserQuery) OnlyX(ctx context.Context) *LinUser { + node, err := luq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinUser ID in the query. +// Returns a *NotSingularError when exactly one LinUser ID is not found. +// Returns a *NotFoundError when no entities are found. +func (luq *LinUserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linuser.Label} + default: + err = &NotSingularError{linuser.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (luq *LinUserQuery) OnlyIDX(ctx context.Context) int { + id, err := luq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinUsers. +func (luq *LinUserQuery) All(ctx context.Context) ([]*LinUser, error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + return luq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (luq *LinUserQuery) AllX(ctx context.Context) []*LinUser { + nodes, err := luq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinUser IDs. +func (luq *LinUserQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := luq.Select(linuser.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (luq *LinUserQuery) IDsX(ctx context.Context) []int { + ids, err := luq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (luq *LinUserQuery) Count(ctx context.Context) (int, error) { + if err := luq.prepareQuery(ctx); err != nil { + return 0, err + } + return luq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (luq *LinUserQuery) CountX(ctx context.Context) int { + count, err := luq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (luq *LinUserQuery) Exist(ctx context.Context) (bool, error) { + if err := luq.prepareQuery(ctx); err != nil { + return false, err + } + return luq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (luq *LinUserQuery) ExistX(ctx context.Context) bool { + exist, err := luq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinUserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (luq *LinUserQuery) Clone() *LinUserQuery { + if luq == nil { + return nil + } + return &LinUserQuery{ + config: luq.config, + limit: luq.limit, + offset: luq.offset, + order: append([]OrderFunc{}, luq.order...), + predicates: append([]predicate.LinUser{}, luq.predicates...), + withLinUserIdentiy: luq.withLinUserIdentiy.Clone(), + withLinGroup: luq.withLinGroup.Clone(), + // clone intermediate query. + sql: luq.sql.Clone(), + path: luq.path, + } +} + +// WithLinUserIdentiy tells the query-builder to eager-load the nodes that are connected to +// the "lin_user_identiy" edge. The optional arguments are used to configure the query builder of the edge. +func (luq *LinUserQuery) WithLinUserIdentiy(opts ...func(*LinUserIdentiyQuery)) *LinUserQuery { + query := &LinUserIdentiyQuery{config: luq.config} + for _, opt := range opts { + opt(query) + } + luq.withLinUserIdentiy = query + return luq +} + +// WithLinGroup tells the query-builder to eager-load the nodes that are connected to +// the "lin_group" edge. The optional arguments are used to configure the query builder of the edge. +func (luq *LinUserQuery) WithLinGroup(opts ...func(*LinGroupQuery)) *LinUserQuery { + query := &LinGroupQuery{config: luq.config} + for _, opt := range opts { + opt(query) + } + luq.withLinGroup = query + return luq +} + +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinUser.Query(). +// GroupBy(linuser.FieldCreateTime). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (luq *LinUserQuery) GroupBy(field string, fields ...string) *LinUserGroupBy { + group := &LinUserGroupBy{config: luq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + return luq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.LinUser.Query(). +// Select(linuser.FieldCreateTime). +// Scan(ctx, &v) +// +func (luq *LinUserQuery) Select(fields ...string) *LinUserSelect { + luq.fields = append(luq.fields, fields...) + return &LinUserSelect{LinUserQuery: luq} +} + +func (luq *LinUserQuery) prepareQuery(ctx context.Context) error { + for _, f := range luq.fields { + if !linuser.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if luq.path != nil { + prev, err := luq.path(ctx) + if err != nil { + return err + } + luq.sql = prev + } + return nil +} + +func (luq *LinUserQuery) sqlAll(ctx context.Context) ([]*LinUser, error) { + var ( + nodes = []*LinUser{} + _spec = luq.querySpec() + loadedTypes = [2]bool{ + luq.withLinUserIdentiy != nil, + luq.withLinGroup != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinUser{config: luq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, luq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := luq.withLinUserIdentiy; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*LinUser) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.LinUserIdentiy = []*LinUserIdentiy{} + } + query.withFKs = true + query.Where(predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.InValues(linuser.LinUserIdentiyColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.lin_user_lin_user_identiy + if fk == nil { + return nil, fmt.Errorf(`foreign-key "lin_user_lin_user_identiy" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "lin_user_lin_user_identiy" returned %v for node %v`, *fk, n.ID) + } + node.Edges.LinUserIdentiy = append(node.Edges.LinUserIdentiy, n) + } + } + + if query := luq.withLinGroup; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinUser, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinGroup = []*LinGroup{} + } + var ( + edgeids []int + edges = make(map[int][]*LinUser) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(linuser.LinGroupPrimaryKey[1], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, luq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_group": %w`, err) + } + query.Where(lingroup.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_group" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinGroup = append(nodes[i].Edges.LinGroup, n) + } + } + } + + return nodes, nil +} + +func (luq *LinUserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := luq.querySpec() + return sqlgraph.CountNodes(ctx, luq.driver, _spec) +} + +func (luq *LinUserQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := luq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (luq *LinUserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + Columns: linuser.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + From: luq.sql, + Unique: true, + } + if unique := luq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := luq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuser.FieldID) + for i := range fields { + if fields[i] != linuser.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := luq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := luq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := luq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := luq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (luq *LinUserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(luq.driver.Dialect()) + t1 := builder.Table(linuser.Table) + columns := luq.fields + if len(columns) == 0 { + columns = linuser.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if luq.sql != nil { + selector = luq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range luq.predicates { + p(selector) + } + for _, p := range luq.order { + p(selector) + } + if offset := luq.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 := luq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinUserGroupBy is the group-by builder for LinUser entities. +type LinUserGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lugb *LinUserGroupBy) Aggregate(fns ...AggregateFunc) *LinUserGroupBy { + lugb.fns = append(lugb.fns, fns...) + return lugb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lugb *LinUserGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lugb.path(ctx) + if err != nil { + return err + } + lugb.sql = query + return lugb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lugb *LinUserGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lugb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lugb *LinUserGroupBy) StringsX(ctx context.Context) []string { + v, err := lugb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lugb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lugb *LinUserGroupBy) StringX(ctx context.Context) string { + v, err := lugb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lugb *LinUserGroupBy) IntsX(ctx context.Context) []int { + v, err := lugb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lugb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lugb *LinUserGroupBy) IntX(ctx context.Context) int { + v, err := lugb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lugb *LinUserGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lugb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lugb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lugb *LinUserGroupBy) Float64X(ctx context.Context) float64 { + v, err := lugb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lugb *LinUserGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lugb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lugb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lugb *LinUserGroupBy) BoolX(ctx context.Context) bool { + v, err := lugb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lugb *LinUserGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lugb.fields { + if !linuser.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lugb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lugb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lugb *LinUserGroupBy) sqlQuery() *sql.Selector { + selector := lugb.sql.Select() + aggregation := make([]string, 0, len(lugb.fns)) + for _, fn := range lugb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lugb.fields)+len(lugb.fns)) + for _, f := range lugb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lugb.fields...)...) +} + +// LinUserSelect is the builder for selecting fields of LinUser entities. +type LinUserSelect struct { + *LinUserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lus *LinUserSelect) Scan(ctx context.Context, v interface{}) error { + if err := lus.prepareQuery(ctx); err != nil { + return err + } + lus.sql = lus.LinUserQuery.sqlQuery(ctx) + return lus.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lus *LinUserSelect) ScanX(ctx context.Context, v interface{}) { + if err := lus.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Strings(ctx context.Context) ([]string, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lus *LinUserSelect) StringsX(ctx context.Context) []string { + v, err := lus.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lus.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lus *LinUserSelect) StringX(ctx context.Context) string { + v, err := lus.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Ints(ctx context.Context) ([]int, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lus *LinUserSelect) IntsX(ctx context.Context) []int { + v, err := lus.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lus.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lus *LinUserSelect) IntX(ctx context.Context) int { + v, err := lus.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lus *LinUserSelect) Float64sX(ctx context.Context) []float64 { + v, err := lus.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lus.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lus *LinUserSelect) Float64X(ctx context.Context) float64 { + v, err := lus.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lus *LinUserSelect) BoolsX(ctx context.Context) []bool { + v, err := lus.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lus.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lus *LinUserSelect) BoolX(ctx context.Context) bool { + v, err := lus.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lus *LinUserSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lus.sql.Query() + if err := lus.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linuser_update.go b/internal/data/model/linuser_update.go new file mode 100644 index 0000000..be3c6fb --- /dev/null +++ b/internal/data/model/linuser_update.go @@ -0,0 +1,807 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserUpdate is the builder for updating LinUser entities. +type LinUserUpdate struct { + config + hooks []Hook + mutation *LinUserMutation +} + +// Where appends a list predicates to the LinUserUpdate builder. +func (luu *LinUserUpdate) Where(ps ...predicate.LinUser) *LinUserUpdate { + luu.mutation.Where(ps...) + return luu +} + +// SetUpdateTime sets the "update_time" field. +func (luu *LinUserUpdate) SetUpdateTime(t time.Time) *LinUserUpdate { + luu.mutation.SetUpdateTime(t) + return luu +} + +// SetDeleteTime sets the "delete_time" field. +func (luu *LinUserUpdate) SetDeleteTime(t time.Time) *LinUserUpdate { + luu.mutation.SetDeleteTime(t) + return luu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luu *LinUserUpdate) SetNillableDeleteTime(t *time.Time) *LinUserUpdate { + if t != nil { + luu.SetDeleteTime(*t) + } + return luu +} + +// SetUsername sets the "username" field. +func (luu *LinUserUpdate) SetUsername(s string) *LinUserUpdate { + luu.mutation.SetUsername(s) + return luu +} + +// SetNickname sets the "nickname" field. +func (luu *LinUserUpdate) SetNickname(s string) *LinUserUpdate { + luu.mutation.SetNickname(s) + return luu +} + +// SetAvatar sets the "avatar" field. +func (luu *LinUserUpdate) SetAvatar(s string) *LinUserUpdate { + luu.mutation.SetAvatar(s) + return luu +} + +// SetNillableAvatar sets the "avatar" field if the given value is not nil. +func (luu *LinUserUpdate) SetNillableAvatar(s *string) *LinUserUpdate { + if s != nil { + luu.SetAvatar(*s) + } + return luu +} + +// SetEmail sets the "email" field. +func (luu *LinUserUpdate) SetEmail(s string) *LinUserUpdate { + luu.mutation.SetEmail(s) + return luu +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (luu *LinUserUpdate) AddLinUserIdentiyIDs(ids ...int) *LinUserUpdate { + luu.mutation.AddLinUserIdentiyIDs(ids...) + return luu +} + +// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luu *LinUserUpdate) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.AddLinUserIdentiyIDs(ids...) +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (luu *LinUserUpdate) AddLinGroupIDs(ids ...int) *LinUserUpdate { + luu.mutation.AddLinGroupIDs(ids...) + return luu +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (luu *LinUserUpdate) AddLinGroup(l ...*LinGroup) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinUserMutation object of the builder. +func (luu *LinUserUpdate) Mutation() *LinUserMutation { + return luu.mutation +} + +// ClearLinUserIdentiy clears all "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luu *LinUserUpdate) ClearLinUserIdentiy() *LinUserUpdate { + luu.mutation.ClearLinUserIdentiy() + return luu +} + +// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to LinUserIdentiy entities by IDs. +func (luu *LinUserUpdate) RemoveLinUserIdentiyIDs(ids ...int) *LinUserUpdate { + luu.mutation.RemoveLinUserIdentiyIDs(ids...) + return luu +} + +// RemoveLinUserIdentiy removes "lin_user_identiy" edges to LinUserIdentiy entities. +func (luu *LinUserUpdate) RemoveLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.RemoveLinUserIdentiyIDs(ids...) +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (luu *LinUserUpdate) ClearLinGroup() *LinUserUpdate { + luu.mutation.ClearLinGroup() + return luu +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (luu *LinUserUpdate) RemoveLinGroupIDs(ids ...int) *LinUserUpdate { + luu.mutation.RemoveLinGroupIDs(ids...) + return luu +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (luu *LinUserUpdate) RemoveLinGroup(l ...*LinGroup) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.RemoveLinGroupIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (luu *LinUserUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + luu.defaults() + if len(luu.hooks) == 0 { + affected, err = luu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luu.mutation = mutation + affected, err = luu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(luu.hooks) - 1; i >= 0; i-- { + if luu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luu *LinUserUpdate) SaveX(ctx context.Context) int { + affected, err := luu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (luu *LinUserUpdate) Exec(ctx context.Context) error { + _, err := luu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luu *LinUserUpdate) ExecX(ctx context.Context) { + if err := luu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (luu *LinUserUpdate) defaults() { + if _, ok := luu.mutation.UpdateTime(); !ok { + v := linuser.UpdateDefaultUpdateTime() + luu.mutation.SetUpdateTime(v) + } +} + +func (luu *LinUserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + Columns: linuser.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + if ps := luu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldUpdateTime, + }) + } + if value, ok := luu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldDeleteTime, + }) + } + if value, ok := luu.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldUsername, + }) + } + if value, ok := luu.mutation.Nickname(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldNickname, + }) + } + if value, ok := luu.mutation.Avatar(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldAvatar, + }) + } + if value, ok := luu.mutation.Email(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldEmail, + }) + } + if luu.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.RemovedLinUserIdentiyIDs(); len(nodes) > 0 && !luu.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if luu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !luu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, luu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuser.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinUserUpdateOne is the builder for updating a single LinUser entity. +type LinUserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinUserMutation +} + +// SetUpdateTime sets the "update_time" field. +func (luuo *LinUserUpdateOne) SetUpdateTime(t time.Time) *LinUserUpdateOne { + luuo.mutation.SetUpdateTime(t) + return luuo +} + +// SetDeleteTime sets the "delete_time" field. +func (luuo *LinUserUpdateOne) SetDeleteTime(t time.Time) *LinUserUpdateOne { + luuo.mutation.SetDeleteTime(t) + return luuo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luuo *LinUserUpdateOne) SetNillableDeleteTime(t *time.Time) *LinUserUpdateOne { + if t != nil { + luuo.SetDeleteTime(*t) + } + return luuo +} + +// SetUsername sets the "username" field. +func (luuo *LinUserUpdateOne) SetUsername(s string) *LinUserUpdateOne { + luuo.mutation.SetUsername(s) + return luuo +} + +// SetNickname sets the "nickname" field. +func (luuo *LinUserUpdateOne) SetNickname(s string) *LinUserUpdateOne { + luuo.mutation.SetNickname(s) + return luuo +} + +// SetAvatar sets the "avatar" field. +func (luuo *LinUserUpdateOne) SetAvatar(s string) *LinUserUpdateOne { + luuo.mutation.SetAvatar(s) + return luuo +} + +// SetNillableAvatar sets the "avatar" field if the given value is not nil. +func (luuo *LinUserUpdateOne) SetNillableAvatar(s *string) *LinUserUpdateOne { + if s != nil { + luuo.SetAvatar(*s) + } + return luuo +} + +// SetEmail sets the "email" field. +func (luuo *LinUserUpdateOne) SetEmail(s string) *LinUserUpdateOne { + luuo.mutation.SetEmail(s) + return luuo +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (luuo *LinUserUpdateOne) AddLinUserIdentiyIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.AddLinUserIdentiyIDs(ids...) + return luuo +} + +// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luuo *LinUserUpdateOne) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.AddLinUserIdentiyIDs(ids...) +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (luuo *LinUserUpdateOne) AddLinGroupIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.AddLinGroupIDs(ids...) + return luuo +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (luuo *LinUserUpdateOne) AddLinGroup(l ...*LinGroup) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinUserMutation object of the builder. +func (luuo *LinUserUpdateOne) Mutation() *LinUserMutation { + return luuo.mutation +} + +// ClearLinUserIdentiy clears all "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luuo *LinUserUpdateOne) ClearLinUserIdentiy() *LinUserUpdateOne { + luuo.mutation.ClearLinUserIdentiy() + return luuo +} + +// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to LinUserIdentiy entities by IDs. +func (luuo *LinUserUpdateOne) RemoveLinUserIdentiyIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.RemoveLinUserIdentiyIDs(ids...) + return luuo +} + +// RemoveLinUserIdentiy removes "lin_user_identiy" edges to LinUserIdentiy entities. +func (luuo *LinUserUpdateOne) RemoveLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.RemoveLinUserIdentiyIDs(ids...) +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (luuo *LinUserUpdateOne) ClearLinGroup() *LinUserUpdateOne { + luuo.mutation.ClearLinGroup() + return luuo +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (luuo *LinUserUpdateOne) RemoveLinGroupIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.RemoveLinGroupIDs(ids...) + return luuo +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (luuo *LinUserUpdateOne) RemoveLinGroup(l ...*LinGroup) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.RemoveLinGroupIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (luuo *LinUserUpdateOne) Select(field string, fields ...string) *LinUserUpdateOne { + luuo.fields = append([]string{field}, fields...) + return luuo +} + +// Save executes the query and returns the updated LinUser entity. +func (luuo *LinUserUpdateOne) Save(ctx context.Context) (*LinUser, error) { + var ( + err error + node *LinUser + ) + luuo.defaults() + if len(luuo.hooks) == 0 { + node, err = luuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luuo.mutation = mutation + node, err = luuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(luuo.hooks) - 1; i >= 0; i-- { + if luuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luuo *LinUserUpdateOne) SaveX(ctx context.Context) *LinUser { + node, err := luuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (luuo *LinUserUpdateOne) Exec(ctx context.Context) error { + _, err := luuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luuo *LinUserUpdateOne) ExecX(ctx context.Context) { + if err := luuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (luuo *LinUserUpdateOne) defaults() { + if _, ok := luuo.mutation.UpdateTime(); !ok { + v := linuser.UpdateDefaultUpdateTime() + luuo.mutation.SetUpdateTime(v) + } +} + +func (luuo *LinUserUpdateOne) sqlSave(ctx context.Context) (_node *LinUser, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + Columns: linuser.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + id, ok := luuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinUser.ID for update")} + } + _spec.Node.ID.Value = id + if fields := luuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuser.FieldID) + for _, f := range fields { + if !linuser.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linuser.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := luuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luuo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldUpdateTime, + }) + } + if value, ok := luuo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldDeleteTime, + }) + } + if value, ok := luuo.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldUsername, + }) + } + if value, ok := luuo.mutation.Nickname(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldNickname, + }) + } + if value, ok := luuo.mutation.Avatar(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldAvatar, + }) + } + if value, ok := luuo.mutation.Email(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldEmail, + }) + } + if luuo.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.RemovedLinUserIdentiyIDs(); len(nodes) > 0 && !luuo.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if luuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !luuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LinUser{config: luuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, luuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuser.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linuseridentiy.go b/internal/data/model/linuseridentiy.go new file mode 100644 index 0000000..5834615 --- /dev/null +++ b/internal/data/model/linuseridentiy.go @@ -0,0 +1,140 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinUserIdentiy is the model entity for the LinUserIdentiy schema. +type LinUserIdentiy struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + // 用户id + UserID int `json:"user_id,omitempty"` + // IdentityType holds the value of the "identity_type" field. + IdentityType string `json:"identity_type,omitempty"` + // Identifier holds the value of the "identifier" field. + Identifier string `json:"identifier,omitempty"` + // Credential holds the value of the "credential" field. + Credential string `json:"credential,omitempty"` + lin_user_lin_user_identiy *int +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinUserIdentiy) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linuseridentiy.FieldID, linuseridentiy.FieldUserID: + values[i] = new(sql.NullInt64) + case linuseridentiy.FieldIdentityType, linuseridentiy.FieldIdentifier, linuseridentiy.FieldCredential: + values[i] = new(sql.NullString) + case linuseridentiy.ForeignKeys[0]: // lin_user_lin_user_identiy + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type LinUserIdentiy", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinUserIdentiy fields. +func (lui *LinUserIdentiy) assignValues(columns []string, values []interface{}) 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 linuseridentiy.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lui.ID = int(value.Int64) + case linuseridentiy.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + lui.UserID = int(value.Int64) + } + case linuseridentiy.FieldIdentityType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field identity_type", values[i]) + } else if value.Valid { + lui.IdentityType = value.String + } + case linuseridentiy.FieldIdentifier: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field identifier", values[i]) + } else if value.Valid { + lui.Identifier = value.String + } + case linuseridentiy.FieldCredential: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field credential", values[i]) + } else if value.Valid { + lui.Credential = value.String + } + case linuseridentiy.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field lin_user_lin_user_identiy", value) + } else if value.Valid { + lui.lin_user_lin_user_identiy = new(int) + *lui.lin_user_lin_user_identiy = int(value.Int64) + } + } + } + return nil +} + +// Update returns a builder for updating this LinUserIdentiy. +// Note that you need to call LinUserIdentiy.Unwrap() before calling this method if this LinUserIdentiy +// was returned from a transaction, and the transaction was committed or rolled back. +func (lui *LinUserIdentiy) Update() *LinUserIdentiyUpdateOne { + return (&LinUserIdentiyClient{config: lui.config}).UpdateOne(lui) +} + +// Unwrap unwraps the LinUserIdentiy 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 (lui *LinUserIdentiy) Unwrap() *LinUserIdentiy { + tx, ok := lui.config.driver.(*txDriver) + if !ok { + panic("model: LinUserIdentiy is not a transactional entity") + } + lui.config.driver = tx.drv + return lui +} + +// String implements the fmt.Stringer. +func (lui *LinUserIdentiy) String() string { + var builder strings.Builder + builder.WriteString("LinUserIdentiy(") + builder.WriteString(fmt.Sprintf("id=%v", lui.ID)) + builder.WriteString(", user_id=") + builder.WriteString(fmt.Sprintf("%v", lui.UserID)) + builder.WriteString(", identity_type=") + builder.WriteString(lui.IdentityType) + builder.WriteString(", identifier=") + builder.WriteString(lui.Identifier) + builder.WriteString(", credential=") + builder.WriteString(lui.Credential) + builder.WriteByte(')') + return builder.String() +} + +// LinUserIdentiys is a parsable slice of LinUserIdentiy. +type LinUserIdentiys []*LinUserIdentiy + +func (lui LinUserIdentiys) config(cfg config) { + for _i := range lui { + lui[_i].config = cfg + } +} diff --git a/internal/data/model/linuseridentiy/linuseridentiy.go b/internal/data/model/linuseridentiy/linuseridentiy.go new file mode 100644 index 0000000..7339818 --- /dev/null +++ b/internal/data/model/linuseridentiy/linuseridentiy.go @@ -0,0 +1,50 @@ +// Code generated by entc, DO NOT EDIT. + +package linuseridentiy + +const ( + // Label holds the string label denoting the linuseridentiy type in the database. + Label = "lin_user_identiy" + // 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" + // FieldIdentityType holds the string denoting the identity_type field in the database. + FieldIdentityType = "identity_type" + // FieldIdentifier holds the string denoting the identifier field in the database. + FieldIdentifier = "identifier" + // FieldCredential holds the string denoting the credential field in the database. + FieldCredential = "credential" + // Table holds the table name of the linuseridentiy in the database. + Table = "lin_user_identiy" +) + +// Columns holds all SQL columns for linuseridentiy fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldIdentityType, + FieldIdentifier, + FieldCredential, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "lin_user_identiy" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "lin_user_lin_user_identiy", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} diff --git a/internal/data/model/linuseridentiy/where.go b/internal/data/model/linuseridentiy/where.go new file mode 100644 index 0000000..69704f1 --- /dev/null +++ b/internal/data/model/linuseridentiy/where.go @@ -0,0 +1,561 @@ +// Code generated by entc, DO NOT EDIT. + +package linuseridentiy + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// IdentityType applies equality check predicate on the "identity_type" field. It's identical to IdentityTypeEQ. +func IdentityType(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentityType), v)) + }) +} + +// Identifier applies equality check predicate on the "identifier" field. It's identical to IdentifierEQ. +func Identifier(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentifier), v)) + }) +} + +// Credential applies equality check predicate on the "credential" field. It's identical to CredentialEQ. +func Credential(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCredential), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUserID), v...)) + }) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUserID), v)) + }) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUserID), v)) + }) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUserID), v)) + }) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUserID), v)) + }) +} + +// IdentityTypeEQ applies the EQ predicate on the "identity_type" field. +func IdentityTypeEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeNEQ applies the NEQ predicate on the "identity_type" field. +func IdentityTypeNEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeIn applies the In predicate on the "identity_type" field. +func IdentityTypeIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldIdentityType), v...)) + }) +} + +// IdentityTypeNotIn applies the NotIn predicate on the "identity_type" field. +func IdentityTypeNotIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldIdentityType), v...)) + }) +} + +// IdentityTypeGT applies the GT predicate on the "identity_type" field. +func IdentityTypeGT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeGTE applies the GTE predicate on the "identity_type" field. +func IdentityTypeGTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeLT applies the LT predicate on the "identity_type" field. +func IdentityTypeLT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeLTE applies the LTE predicate on the "identity_type" field. +func IdentityTypeLTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeContains applies the Contains predicate on the "identity_type" field. +func IdentityTypeContains(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeHasPrefix applies the HasPrefix predicate on the "identity_type" field. +func IdentityTypeHasPrefix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeHasSuffix applies the HasSuffix predicate on the "identity_type" field. +func IdentityTypeHasSuffix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeEqualFold applies the EqualFold predicate on the "identity_type" field. +func IdentityTypeEqualFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeContainsFold applies the ContainsFold predicate on the "identity_type" field. +func IdentityTypeContainsFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldIdentityType), v)) + }) +} + +// IdentifierEQ applies the EQ predicate on the "identifier" field. +func IdentifierEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierNEQ applies the NEQ predicate on the "identifier" field. +func IdentifierNEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierIn applies the In predicate on the "identifier" field. +func IdentifierIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldIdentifier), v...)) + }) +} + +// IdentifierNotIn applies the NotIn predicate on the "identifier" field. +func IdentifierNotIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldIdentifier), v...)) + }) +} + +// IdentifierGT applies the GT predicate on the "identifier" field. +func IdentifierGT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierGTE applies the GTE predicate on the "identifier" field. +func IdentifierGTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierLT applies the LT predicate on the "identifier" field. +func IdentifierLT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierLTE applies the LTE predicate on the "identifier" field. +func IdentifierLTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierContains applies the Contains predicate on the "identifier" field. +func IdentifierContains(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierHasPrefix applies the HasPrefix predicate on the "identifier" field. +func IdentifierHasPrefix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierHasSuffix applies the HasSuffix predicate on the "identifier" field. +func IdentifierHasSuffix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierEqualFold applies the EqualFold predicate on the "identifier" field. +func IdentifierEqualFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierContainsFold applies the ContainsFold predicate on the "identifier" field. +func IdentifierContainsFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldIdentifier), v)) + }) +} + +// CredentialEQ applies the EQ predicate on the "credential" field. +func CredentialEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCredential), v)) + }) +} + +// CredentialNEQ applies the NEQ predicate on the "credential" field. +func CredentialNEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCredential), v)) + }) +} + +// CredentialIn applies the In predicate on the "credential" field. +func CredentialIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCredential), v...)) + }) +} + +// CredentialNotIn applies the NotIn predicate on the "credential" field. +func CredentialNotIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCredential), v...)) + }) +} + +// CredentialGT applies the GT predicate on the "credential" field. +func CredentialGT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCredential), v)) + }) +} + +// CredentialGTE applies the GTE predicate on the "credential" field. +func CredentialGTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCredential), v)) + }) +} + +// CredentialLT applies the LT predicate on the "credential" field. +func CredentialLT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCredential), v)) + }) +} + +// CredentialLTE applies the LTE predicate on the "credential" field. +func CredentialLTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCredential), v)) + }) +} + +// CredentialContains applies the Contains predicate on the "credential" field. +func CredentialContains(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldCredential), v)) + }) +} + +// CredentialHasPrefix applies the HasPrefix predicate on the "credential" field. +func CredentialHasPrefix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldCredential), v)) + }) +} + +// CredentialHasSuffix applies the HasSuffix predicate on the "credential" field. +func CredentialHasSuffix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldCredential), v)) + }) +} + +// CredentialEqualFold applies the EqualFold predicate on the "credential" field. +func CredentialEqualFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldCredential), v)) + }) +} + +// CredentialContainsFold applies the ContainsFold predicate on the "credential" field. +func CredentialContainsFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldCredential), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinUserIdentiy) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinUserIdentiy) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinUserIdentiy) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linuseridentiy_create.go b/internal/data/model/linuseridentiy_create.go new file mode 100644 index 0000000..5c5c685 --- /dev/null +++ b/internal/data/model/linuseridentiy_create.go @@ -0,0 +1,271 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyCreate is the builder for creating a LinUserIdentiy entity. +type LinUserIdentiyCreate struct { + config + mutation *LinUserIdentiyMutation + hooks []Hook +} + +// SetUserID sets the "user_id" field. +func (luic *LinUserIdentiyCreate) SetUserID(i int) *LinUserIdentiyCreate { + luic.mutation.SetUserID(i) + return luic +} + +// SetIdentityType sets the "identity_type" field. +func (luic *LinUserIdentiyCreate) SetIdentityType(s string) *LinUserIdentiyCreate { + luic.mutation.SetIdentityType(s) + return luic +} + +// SetIdentifier sets the "identifier" field. +func (luic *LinUserIdentiyCreate) SetIdentifier(s string) *LinUserIdentiyCreate { + luic.mutation.SetIdentifier(s) + return luic +} + +// SetCredential sets the "credential" field. +func (luic *LinUserIdentiyCreate) SetCredential(s string) *LinUserIdentiyCreate { + luic.mutation.SetCredential(s) + return luic +} + +// Mutation returns the LinUserIdentiyMutation object of the builder. +func (luic *LinUserIdentiyCreate) Mutation() *LinUserIdentiyMutation { + return luic.mutation +} + +// Save creates the LinUserIdentiy in the database. +func (luic *LinUserIdentiyCreate) Save(ctx context.Context) (*LinUserIdentiy, error) { + var ( + err error + node *LinUserIdentiy + ) + if len(luic.hooks) == 0 { + if err = luic.check(); err != nil { + return nil, err + } + node, err = luic.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = luic.check(); err != nil { + return nil, err + } + luic.mutation = mutation + if node, err = luic.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(luic.hooks) - 1; i >= 0; i-- { + if luic.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luic.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luic.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (luic *LinUserIdentiyCreate) SaveX(ctx context.Context) *LinUserIdentiy { + v, err := luic.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (luic *LinUserIdentiyCreate) Exec(ctx context.Context) error { + _, err := luic.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luic *LinUserIdentiyCreate) ExecX(ctx context.Context) { + if err := luic.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (luic *LinUserIdentiyCreate) check() error { + if _, ok := luic.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} + } + if _, ok := luic.mutation.IdentityType(); !ok { + return &ValidationError{Name: "identity_type", err: errors.New(`model: missing required field "identity_type"`)} + } + if _, ok := luic.mutation.Identifier(); !ok { + return &ValidationError{Name: "identifier", err: errors.New(`model: missing required field "identifier"`)} + } + if _, ok := luic.mutation.Credential(); !ok { + return &ValidationError{Name: "credential", err: errors.New(`model: missing required field "credential"`)} + } + return nil +} + +func (luic *LinUserIdentiyCreate) sqlSave(ctx context.Context) (*LinUserIdentiy, error) { + _node, _spec := luic.createSpec() + if err := sqlgraph.CreateNode(ctx, luic.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (luic *LinUserIdentiyCreate) createSpec() (*LinUserIdentiy, *sqlgraph.CreateSpec) { + var ( + _node = &LinUserIdentiy{config: luic.config} + _spec = &sqlgraph.CreateSpec{ + Table: linuseridentiy.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + } + ) + if value, ok := luic.mutation.UserID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + _node.UserID = value + } + if value, ok := luic.mutation.IdentityType(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentityType, + }) + _node.IdentityType = value + } + if value, ok := luic.mutation.Identifier(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentifier, + }) + _node.Identifier = value + } + if value, ok := luic.mutation.Credential(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldCredential, + }) + _node.Credential = value + } + return _node, _spec +} + +// LinUserIdentiyCreateBulk is the builder for creating many LinUserIdentiy entities in bulk. +type LinUserIdentiyCreateBulk struct { + config + builders []*LinUserIdentiyCreate +} + +// Save creates the LinUserIdentiy entities in the database. +func (luicb *LinUserIdentiyCreateBulk) Save(ctx context.Context) ([]*LinUserIdentiy, error) { + specs := make([]*sqlgraph.CreateSpec, len(luicb.builders)) + nodes := make([]*LinUserIdentiy, len(luicb.builders)) + mutators := make([]Mutator, len(luicb.builders)) + for i := range luicb.builders { + func(i int, root context.Context) { + builder := luicb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, luicb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, luicb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, luicb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (luicb *LinUserIdentiyCreateBulk) SaveX(ctx context.Context) []*LinUserIdentiy { + v, err := luicb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (luicb *LinUserIdentiyCreateBulk) Exec(ctx context.Context) error { + _, err := luicb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luicb *LinUserIdentiyCreateBulk) ExecX(ctx context.Context) { + if err := luicb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linuseridentiy_delete.go b/internal/data/model/linuseridentiy_delete.go new file mode 100644 index 0000000..74d2ac9 --- /dev/null +++ b/internal/data/model/linuseridentiy_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyDelete is the builder for deleting a LinUserIdentiy entity. +type LinUserIdentiyDelete struct { + config + hooks []Hook + mutation *LinUserIdentiyMutation +} + +// Where appends a list predicates to the LinUserIdentiyDelete builder. +func (luid *LinUserIdentiyDelete) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyDelete { + luid.mutation.Where(ps...) + return luid +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (luid *LinUserIdentiyDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(luid.hooks) == 0 { + affected, err = luid.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luid.mutation = mutation + affected, err = luid.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(luid.hooks) - 1; i >= 0; i-- { + if luid.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luid.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luid.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luid *LinUserIdentiyDelete) ExecX(ctx context.Context) int { + n, err := luid.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (luid *LinUserIdentiyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + if ps := luid.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, luid.driver, _spec) +} + +// LinUserIdentiyDeleteOne is the builder for deleting a single LinUserIdentiy entity. +type LinUserIdentiyDeleteOne struct { + luid *LinUserIdentiyDelete +} + +// Exec executes the deletion query. +func (luido *LinUserIdentiyDeleteOne) Exec(ctx context.Context) error { + n, err := luido.luid.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linuseridentiy.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (luido *LinUserIdentiyDeleteOne) ExecX(ctx context.Context) { + luido.luid.ExecX(ctx) +} diff --git a/internal/data/model/linuseridentiy_query.go b/internal/data/model/linuseridentiy_query.go new file mode 100644 index 0000000..2a91964 --- /dev/null +++ b/internal/data/model/linuseridentiy_query.go @@ -0,0 +1,965 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyQuery is the builder for querying LinUserIdentiy entities. +type LinUserIdentiyQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinUserIdentiy + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinUserIdentiyQuery builder. +func (luiq *LinUserIdentiyQuery) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyQuery { + luiq.predicates = append(luiq.predicates, ps...) + return luiq +} + +// Limit adds a limit step to the query. +func (luiq *LinUserIdentiyQuery) Limit(limit int) *LinUserIdentiyQuery { + luiq.limit = &limit + return luiq +} + +// Offset adds an offset step to the query. +func (luiq *LinUserIdentiyQuery) Offset(offset int) *LinUserIdentiyQuery { + luiq.offset = &offset + return luiq +} + +// 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 (luiq *LinUserIdentiyQuery) Unique(unique bool) *LinUserIdentiyQuery { + luiq.unique = &unique + return luiq +} + +// Order adds an order step to the query. +func (luiq *LinUserIdentiyQuery) Order(o ...OrderFunc) *LinUserIdentiyQuery { + luiq.order = append(luiq.order, o...) + return luiq +} + +// First returns the first LinUserIdentiy entity from the query. +// Returns a *NotFoundError when no LinUserIdentiy was found. +func (luiq *LinUserIdentiyQuery) First(ctx context.Context) (*LinUserIdentiy, error) { + nodes, err := luiq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuseridentiy.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) FirstX(ctx context.Context) *LinUserIdentiy { + node, err := luiq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinUserIdentiy ID from the query. +// Returns a *NotFoundError when no LinUserIdentiy ID was found. +func (luiq *LinUserIdentiyQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luiq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuseridentiy.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) FirstIDX(ctx context.Context) int { + id, err := luiq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinUserIdentiy entity from the query. +// Returns a *NotFoundError when no LinUserIdentiy was found. +func (luiq *LinUserIdentiyQuery) Last(ctx context.Context) (*LinUserIdentiy, error) { + nodes, err := luiq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuseridentiy.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) LastX(ctx context.Context) *LinUserIdentiy { + node, err := luiq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinUserIdentiy ID from the query. +// Returns a *NotFoundError when no LinUserIdentiy ID was found. +func (luiq *LinUserIdentiyQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luiq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuseridentiy.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) LastIDX(ctx context.Context) int { + id, err := luiq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinUserIdentiy entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinUserIdentiy entity is not found. +// Returns a *NotFoundError when no LinUserIdentiy entities are found. +func (luiq *LinUserIdentiyQuery) Only(ctx context.Context) (*LinUserIdentiy, error) { + nodes, err := luiq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linuseridentiy.Label} + default: + return nil, &NotSingularError{linuseridentiy.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) OnlyX(ctx context.Context) *LinUserIdentiy { + node, err := luiq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinUserIdentiy ID in the query. +// Returns a *NotSingularError when exactly one LinUserIdentiy ID is not found. +// Returns a *NotFoundError when no entities are found. +func (luiq *LinUserIdentiyQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luiq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = &NotSingularError{linuseridentiy.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) OnlyIDX(ctx context.Context) int { + id, err := luiq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinUserIdentiys. +func (luiq *LinUserIdentiyQuery) All(ctx context.Context) ([]*LinUserIdentiy, error) { + if err := luiq.prepareQuery(ctx); err != nil { + return nil, err + } + return luiq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) AllX(ctx context.Context) []*LinUserIdentiy { + nodes, err := luiq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinUserIdentiy IDs. +func (luiq *LinUserIdentiyQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := luiq.Select(linuseridentiy.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) IDsX(ctx context.Context) []int { + ids, err := luiq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (luiq *LinUserIdentiyQuery) Count(ctx context.Context) (int, error) { + if err := luiq.prepareQuery(ctx); err != nil { + return 0, err + } + return luiq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) CountX(ctx context.Context) int { + count, err := luiq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (luiq *LinUserIdentiyQuery) Exist(ctx context.Context) (bool, error) { + if err := luiq.prepareQuery(ctx); err != nil { + return false, err + } + return luiq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) ExistX(ctx context.Context) bool { + exist, err := luiq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinUserIdentiyQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (luiq *LinUserIdentiyQuery) Clone() *LinUserIdentiyQuery { + if luiq == nil { + return nil + } + return &LinUserIdentiyQuery{ + config: luiq.config, + limit: luiq.limit, + offset: luiq.offset, + order: append([]OrderFunc{}, luiq.order...), + predicates: append([]predicate.LinUserIdentiy{}, luiq.predicates...), + // clone intermediate query. + sql: luiq.sql.Clone(), + path: luiq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// UserID int `json:"user_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinUserIdentiy.Query(). +// GroupBy(linuseridentiy.FieldUserID). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (luiq *LinUserIdentiyQuery) GroupBy(field string, fields ...string) *LinUserIdentiyGroupBy { + group := &LinUserIdentiyGroupBy{config: luiq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := luiq.prepareQuery(ctx); err != nil { + return nil, err + } + return luiq.sqlQuery(ctx), nil + } + return group +} + +// 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 int `json:"user_id,omitempty"` +// } +// +// client.LinUserIdentiy.Query(). +// Select(linuseridentiy.FieldUserID). +// Scan(ctx, &v) +// +func (luiq *LinUserIdentiyQuery) Select(fields ...string) *LinUserIdentiySelect { + luiq.fields = append(luiq.fields, fields...) + return &LinUserIdentiySelect{LinUserIdentiyQuery: luiq} +} + +func (luiq *LinUserIdentiyQuery) prepareQuery(ctx context.Context) error { + for _, f := range luiq.fields { + if !linuseridentiy.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if luiq.path != nil { + prev, err := luiq.path(ctx) + if err != nil { + return err + } + luiq.sql = prev + } + return nil +} + +func (luiq *LinUserIdentiyQuery) sqlAll(ctx context.Context) ([]*LinUserIdentiy, error) { + var ( + nodes = []*LinUserIdentiy{} + withFKs = luiq.withFKs + _spec = luiq.querySpec() + ) + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinUserIdentiy{config: luiq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, luiq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (luiq *LinUserIdentiyQuery) sqlCount(ctx context.Context) (int, error) { + _spec := luiq.querySpec() + return sqlgraph.CountNodes(ctx, luiq.driver, _spec) +} + +func (luiq *LinUserIdentiyQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := luiq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (luiq *LinUserIdentiyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + Columns: linuseridentiy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + From: luiq.sql, + Unique: true, + } + if unique := luiq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := luiq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.FieldID) + for i := range fields { + if fields[i] != linuseridentiy.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := luiq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := luiq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := luiq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := luiq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (luiq *LinUserIdentiyQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(luiq.driver.Dialect()) + t1 := builder.Table(linuseridentiy.Table) + columns := luiq.fields + if len(columns) == 0 { + columns = linuseridentiy.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if luiq.sql != nil { + selector = luiq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range luiq.predicates { + p(selector) + } + for _, p := range luiq.order { + p(selector) + } + if offset := luiq.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 := luiq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinUserIdentiyGroupBy is the group-by builder for LinUserIdentiy entities. +type LinUserIdentiyGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (luigb *LinUserIdentiyGroupBy) Aggregate(fns ...AggregateFunc) *LinUserIdentiyGroupBy { + luigb.fns = append(luigb.fns, fns...) + return luigb +} + +// Scan applies the group-by query and scans the result into the given value. +func (luigb *LinUserIdentiyGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := luigb.path(ctx) + if err != nil { + return err + } + luigb.sql = query + return luigb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := luigb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) StringsX(ctx context.Context) []string { + v, err := luigb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = luigb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) StringX(ctx context.Context) string { + v, err := luigb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) IntsX(ctx context.Context) []int { + v, err := luigb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = luigb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) IntX(ctx context.Context) int { + v, err := luigb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := luigb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = luigb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) Float64X(ctx context.Context) float64 { + v, err := luigb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) BoolsX(ctx context.Context) []bool { + v, err := luigb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = luigb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) BoolX(ctx context.Context) bool { + v, err := luigb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (luigb *LinUserIdentiyGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range luigb.fields { + if !linuseridentiy.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := luigb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := luigb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (luigb *LinUserIdentiyGroupBy) sqlQuery() *sql.Selector { + selector := luigb.sql.Select() + aggregation := make([]string, 0, len(luigb.fns)) + for _, fn := range luigb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(luigb.fields)+len(luigb.fns)) + for _, f := range luigb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(luigb.fields...)...) +} + +// LinUserIdentiySelect is the builder for selecting fields of LinUserIdentiy entities. +type LinUserIdentiySelect struct { + *LinUserIdentiyQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (luis *LinUserIdentiySelect) Scan(ctx context.Context, v interface{}) error { + if err := luis.prepareQuery(ctx); err != nil { + return err + } + luis.sql = luis.LinUserIdentiyQuery.sqlQuery(ctx) + return luis.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (luis *LinUserIdentiySelect) ScanX(ctx context.Context, v interface{}) { + if err := luis.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Strings(ctx context.Context) ([]string, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (luis *LinUserIdentiySelect) StringsX(ctx context.Context) []string { + v, err := luis.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = luis.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (luis *LinUserIdentiySelect) StringX(ctx context.Context) string { + v, err := luis.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Ints(ctx context.Context) ([]int, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (luis *LinUserIdentiySelect) IntsX(ctx context.Context) []int { + v, err := luis.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = luis.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (luis *LinUserIdentiySelect) IntX(ctx context.Context) int { + v, err := luis.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Float64s(ctx context.Context) ([]float64, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (luis *LinUserIdentiySelect) Float64sX(ctx context.Context) []float64 { + v, err := luis.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = luis.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (luis *LinUserIdentiySelect) Float64X(ctx context.Context) float64 { + v, err := luis.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Bools(ctx context.Context) ([]bool, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (luis *LinUserIdentiySelect) BoolsX(ctx context.Context) []bool { + v, err := luis.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = luis.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (luis *LinUserIdentiySelect) BoolX(ctx context.Context) bool { + v, err := luis.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (luis *LinUserIdentiySelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := luis.sql.Query() + if err := luis.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linuseridentiy_update.go b/internal/data/model/linuseridentiy_update.go new file mode 100644 index 0000000..d11f59b --- /dev/null +++ b/internal/data/model/linuseridentiy_update.go @@ -0,0 +1,370 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyUpdate is the builder for updating LinUserIdentiy entities. +type LinUserIdentiyUpdate struct { + config + hooks []Hook + mutation *LinUserIdentiyMutation +} + +// Where appends a list predicates to the LinUserIdentiyUpdate builder. +func (luiu *LinUserIdentiyUpdate) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyUpdate { + luiu.mutation.Where(ps...) + return luiu +} + +// SetUserID sets the "user_id" field. +func (luiu *LinUserIdentiyUpdate) SetUserID(i int) *LinUserIdentiyUpdate { + luiu.mutation.ResetUserID() + luiu.mutation.SetUserID(i) + return luiu +} + +// AddUserID adds i to the "user_id" field. +func (luiu *LinUserIdentiyUpdate) AddUserID(i int) *LinUserIdentiyUpdate { + luiu.mutation.AddUserID(i) + return luiu +} + +// SetIdentityType sets the "identity_type" field. +func (luiu *LinUserIdentiyUpdate) SetIdentityType(s string) *LinUserIdentiyUpdate { + luiu.mutation.SetIdentityType(s) + return luiu +} + +// SetIdentifier sets the "identifier" field. +func (luiu *LinUserIdentiyUpdate) SetIdentifier(s string) *LinUserIdentiyUpdate { + luiu.mutation.SetIdentifier(s) + return luiu +} + +// SetCredential sets the "credential" field. +func (luiu *LinUserIdentiyUpdate) SetCredential(s string) *LinUserIdentiyUpdate { + luiu.mutation.SetCredential(s) + return luiu +} + +// Mutation returns the LinUserIdentiyMutation object of the builder. +func (luiu *LinUserIdentiyUpdate) Mutation() *LinUserIdentiyMutation { + return luiu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (luiu *LinUserIdentiyUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(luiu.hooks) == 0 { + affected, err = luiu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luiu.mutation = mutation + affected, err = luiu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(luiu.hooks) - 1; i >= 0; i-- { + if luiu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luiu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luiu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luiu *LinUserIdentiyUpdate) SaveX(ctx context.Context) int { + affected, err := luiu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (luiu *LinUserIdentiyUpdate) Exec(ctx context.Context) error { + _, err := luiu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luiu *LinUserIdentiyUpdate) ExecX(ctx context.Context) { + if err := luiu.Exec(ctx); err != nil { + panic(err) + } +} + +func (luiu *LinUserIdentiyUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + Columns: linuseridentiy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + if ps := luiu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luiu.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiu.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiu.mutation.IdentityType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentityType, + }) + } + if value, ok := luiu.mutation.Identifier(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentifier, + }) + } + if value, ok := luiu.mutation.Credential(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldCredential, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, luiu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuseridentiy.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinUserIdentiyUpdateOne is the builder for updating a single LinUserIdentiy entity. +type LinUserIdentiyUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinUserIdentiyMutation +} + +// SetUserID sets the "user_id" field. +func (luiuo *LinUserIdentiyUpdateOne) SetUserID(i int) *LinUserIdentiyUpdateOne { + luiuo.mutation.ResetUserID() + luiuo.mutation.SetUserID(i) + return luiuo +} + +// AddUserID adds i to the "user_id" field. +func (luiuo *LinUserIdentiyUpdateOne) AddUserID(i int) *LinUserIdentiyUpdateOne { + luiuo.mutation.AddUserID(i) + return luiuo +} + +// SetIdentityType sets the "identity_type" field. +func (luiuo *LinUserIdentiyUpdateOne) SetIdentityType(s string) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetIdentityType(s) + return luiuo +} + +// SetIdentifier sets the "identifier" field. +func (luiuo *LinUserIdentiyUpdateOne) SetIdentifier(s string) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetIdentifier(s) + return luiuo +} + +// SetCredential sets the "credential" field. +func (luiuo *LinUserIdentiyUpdateOne) SetCredential(s string) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetCredential(s) + return luiuo +} + +// Mutation returns the LinUserIdentiyMutation object of the builder. +func (luiuo *LinUserIdentiyUpdateOne) Mutation() *LinUserIdentiyMutation { + return luiuo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (luiuo *LinUserIdentiyUpdateOne) Select(field string, fields ...string) *LinUserIdentiyUpdateOne { + luiuo.fields = append([]string{field}, fields...) + return luiuo +} + +// Save executes the query and returns the updated LinUserIdentiy entity. +func (luiuo *LinUserIdentiyUpdateOne) Save(ctx context.Context) (*LinUserIdentiy, error) { + var ( + err error + node *LinUserIdentiy + ) + if len(luiuo.hooks) == 0 { + node, err = luiuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luiuo.mutation = mutation + node, err = luiuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(luiuo.hooks) - 1; i >= 0; i-- { + if luiuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luiuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luiuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luiuo *LinUserIdentiyUpdateOne) SaveX(ctx context.Context) *LinUserIdentiy { + node, err := luiuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (luiuo *LinUserIdentiyUpdateOne) Exec(ctx context.Context) error { + _, err := luiuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luiuo *LinUserIdentiyUpdateOne) ExecX(ctx context.Context) { + if err := luiuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (luiuo *LinUserIdentiyUpdateOne) sqlSave(ctx context.Context) (_node *LinUserIdentiy, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + Columns: linuseridentiy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + id, ok := luiuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinUserIdentiy.ID for update")} + } + _spec.Node.ID.Value = id + if fields := luiuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.FieldID) + for _, f := range fields { + if !linuseridentiy.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linuseridentiy.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := luiuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luiuo.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiuo.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiuo.mutation.IdentityType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentityType, + }) + } + if value, ok := luiuo.mutation.Identifier(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentifier, + }) + } + if value, ok := luiuo.mutation.Credential(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldCredential, + }) + } + _node = &LinUserIdentiy{config: luiuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, luiuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuseridentiy.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/migrate/migrate.go b/internal/data/model/migrate/migrate.go new file mode 100644 index 0000000..e4a9a22 --- /dev/null +++ b/internal/data/model/migrate/migrate.go @@ -0,0 +1,72 @@ +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithFixture sets the foreign-key renaming option to the migration when upgrading + // ent from v0.1.0 (issue-#285). Defaults to false. + WithFixture = schema.WithFixture + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver + universalID bool +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +// +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + drv := &schema.WriteDriver{ + Writer: w, + Driver: s.drv, + } + migrate, err := schema.NewMigrate(drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} diff --git a/internal/data/model/migrate/schema.go b/internal/data/model/migrate/schema.go new file mode 100644 index 0000000..210788f --- /dev/null +++ b/internal/data/model/migrate/schema.go @@ -0,0 +1,235 @@ +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // BookColumns holds the columns for the "book" table. + BookColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "title", Type: field.TypeString}, + {Name: "author", Type: field.TypeString}, + {Name: "summary", Type: field.TypeString}, + {Name: "image", Type: field.TypeString}, + } + // BookTable holds the schema information for the "book" table. + BookTable = &schema.Table{ + Name: "book", + Columns: BookColumns, + PrimaryKey: []*schema.Column{BookColumns[0]}, + } + // LinFileColumns holds the columns for the "lin_file" table. + LinFileColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "path", Type: field.TypeString}, + {Name: "type", Type: field.TypeInt8}, + {Name: "name", Type: field.TypeString}, + {Name: "extension", Type: field.TypeString}, + {Name: "size", Type: field.TypeInt}, + {Name: "md5", Type: field.TypeString, Unique: true}, + } + // LinFileTable holds the schema information for the "lin_file" table. + LinFileTable = &schema.Table{ + Name: "lin_file", + Columns: LinFileColumns, + PrimaryKey: []*schema.Column{LinFileColumns[0]}, + } + // LinGroupColumns holds the columns for the "lin_group" table. + LinGroupColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Unique: true}, + {Name: "info", Type: field.TypeString}, + {Name: "level", Type: field.TypeInt8}, + } + // LinGroupTable holds the schema information for the "lin_group" table. + LinGroupTable = &schema.Table{ + Name: "lin_group", + Columns: LinGroupColumns, + PrimaryKey: []*schema.Column{LinGroupColumns[0]}, + } + // LinGroupPermissionColumns holds the columns for the "lin_group_permission" table. + LinGroupPermissionColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "group_id", Type: field.TypeInt, Unique: true}, + {Name: "permission_id", Type: field.TypeInt}, + } + // LinGroupPermissionTable holds the schema information for the "lin_group_permission" table. + LinGroupPermissionTable = &schema.Table{ + Name: "lin_group_permission", + Columns: LinGroupPermissionColumns, + PrimaryKey: []*schema.Column{LinGroupPermissionColumns[0]}, + } + // LinLogColumns holds the columns for the "lin_log" table. + LinLogColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime}, + {Name: "message", Type: field.TypeString}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "username", Type: field.TypeString}, + {Name: "status_code", Type: field.TypeInt}, + {Name: "method", Type: field.TypeString}, + {Name: "path", Type: field.TypeString}, + {Name: "permission", Type: field.TypeString}, + } + // LinLogTable holds the schema information for the "lin_log" table. + LinLogTable = &schema.Table{ + Name: "lin_log", + Columns: LinLogColumns, + PrimaryKey: []*schema.Column{LinLogColumns[0]}, + } + // LinPermissionColumns holds the columns for the "lin_permission" table. + LinPermissionColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "module", Type: field.TypeString}, + {Name: "mount", Type: field.TypeInt8}, + } + // LinPermissionTable holds the schema information for the "lin_permission" table. + LinPermissionTable = &schema.Table{ + Name: "lin_permission", + Columns: LinPermissionColumns, + PrimaryKey: []*schema.Column{LinPermissionColumns[0]}, + } + // LinUserColumns holds the columns for the "lin_user" table. + LinUserColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime}, + {Name: "username", Type: field.TypeString, Unique: true}, + {Name: "nickname", Type: field.TypeString}, + {Name: "avatar", Type: field.TypeString, Default: ""}, + {Name: "email", Type: field.TypeString, Unique: true}, + } + // LinUserTable holds the schema information for the "lin_user" table. + LinUserTable = &schema.Table{ + Name: "lin_user", + Columns: LinUserColumns, + PrimaryKey: []*schema.Column{LinUserColumns[0]}, + } + // LinUserIdentiyColumns holds the columns for the "lin_user_identiy" table. + LinUserIdentiyColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "identity_type", Type: field.TypeString}, + {Name: "identifier", Type: field.TypeString}, + {Name: "credential", Type: field.TypeString}, + {Name: "lin_user_lin_user_identiy", Type: field.TypeInt, Nullable: true}, + } + // LinUserIdentiyTable holds the schema information for the "lin_user_identiy" table. + LinUserIdentiyTable = &schema.Table{ + Name: "lin_user_identiy", + Columns: LinUserIdentiyColumns, + PrimaryKey: []*schema.Column{LinUserIdentiyColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_user_identiy_lin_user_lin_user_identiy", + Columns: []*schema.Column{LinUserIdentiyColumns[5]}, + RefColumns: []*schema.Column{LinUserColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // LinUserGroupColumns holds the columns for the "lin_user_group" table. + LinUserGroupColumns = []*schema.Column{ + {Name: "user_id", Type: field.TypeInt}, + {Name: "group_id", Type: field.TypeInt}, + } + // LinUserGroupTable holds the schema information for the "lin_user_group" table. + LinUserGroupTable = &schema.Table{ + Name: "lin_user_group", + Columns: LinUserGroupColumns, + PrimaryKey: []*schema.Column{LinUserGroupColumns[0], LinUserGroupColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_user_group_user_id", + Columns: []*schema.Column{LinUserGroupColumns[0]}, + RefColumns: []*schema.Column{LinGroupColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "lin_user_group_group_id", + Columns: []*schema.Column{LinUserGroupColumns[1]}, + RefColumns: []*schema.Column{LinUserColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // LinPermissionLinGroupColumns holds the columns for the "lin_permission_lin_group" table. + LinPermissionLinGroupColumns = []*schema.Column{ + {Name: "lin_permission_id", Type: field.TypeInt}, + {Name: "lin_group_id", Type: field.TypeInt}, + } + // LinPermissionLinGroupTable holds the schema information for the "lin_permission_lin_group" table. + LinPermissionLinGroupTable = &schema.Table{ + Name: "lin_permission_lin_group", + Columns: LinPermissionLinGroupColumns, + PrimaryKey: []*schema.Column{LinPermissionLinGroupColumns[0], LinPermissionLinGroupColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_permission_lin_group_lin_permission_id", + Columns: []*schema.Column{LinPermissionLinGroupColumns[0]}, + RefColumns: []*schema.Column{LinPermissionColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "lin_permission_lin_group_lin_group_id", + Columns: []*schema.Column{LinPermissionLinGroupColumns[1]}, + RefColumns: []*schema.Column{LinGroupColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + BookTable, + LinFileTable, + LinGroupTable, + LinGroupPermissionTable, + LinLogTable, + LinPermissionTable, + LinUserTable, + LinUserIdentiyTable, + LinUserGroupTable, + LinPermissionLinGroupTable, + } +) + +func init() { + BookTable.Annotation = &entsql.Annotation{ + Table: "book", + } + LinFileTable.Annotation = &entsql.Annotation{ + Table: "lin_file", + } + LinGroupTable.Annotation = &entsql.Annotation{ + Table: "lin_group", + } + LinGroupPermissionTable.Annotation = &entsql.Annotation{ + Table: "lin_group_permission", + } + LinLogTable.Annotation = &entsql.Annotation{ + Table: "lin_log", + } + LinPermissionTable.Annotation = &entsql.Annotation{ + Table: "lin_permission", + } + LinUserTable.Annotation = &entsql.Annotation{ + Table: "lin_user", + } + LinUserIdentiyTable.ForeignKeys[0].RefTable = LinUserTable + LinUserIdentiyTable.Annotation = &entsql.Annotation{ + Table: "lin_user_identiy", + } + LinUserGroupTable.ForeignKeys[0].RefTable = LinGroupTable + LinUserGroupTable.ForeignKeys[1].RefTable = LinUserTable + LinPermissionLinGroupTable.ForeignKeys[0].RefTable = LinPermissionTable + LinPermissionLinGroupTable.ForeignKeys[1].RefTable = LinGroupTable +} diff --git a/internal/data/model/mutation.go b/internal/data/model/mutation.go new file mode 100644 index 0000000..0d37c80 --- /dev/null +++ b/internal/data/model/mutation.go @@ -0,0 +1,4810 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "sync" + "time" + + "entgo.io/ent" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeBook = "Book" + TypeLinFile = "LinFile" + TypeLinGroup = "LinGroup" + TypeLinGroupPermission = "LinGroupPermission" + TypeLinLog = "LinLog" + TypeLinPermission = "LinPermission" + TypeLinUser = "LinUser" + TypeLinUserIdentiy = "LinUserIdentiy" +) + +// BookMutation represents an operation that mutates the Book nodes in the graph. +type BookMutation struct { + config + op Op + typ string + id *int + title *string + author *string + summary *string + image *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Book, error) + predicates []predicate.Book +} + +var _ ent.Mutation = (*BookMutation)(nil) + +// bookOption allows management of the mutation configuration using functional options. +type bookOption func(*BookMutation) + +// newBookMutation creates new mutation for the Book entity. +func newBookMutation(c config, op Op, opts ...bookOption) *BookMutation { + m := &BookMutation{ + config: c, + op: op, + typ: TypeBook, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBookID sets the ID field of the mutation. +func withBookID(id int) bookOption { + return func(m *BookMutation) { + var ( + err error + once sync.Once + value *Book + ) + m.oldValue = func(ctx context.Context) (*Book, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Book.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBook sets the old Book of the mutation. +func withBook(node *Book) bookOption { + return func(m *BookMutation) { + m.oldValue = func(context.Context) (*Book, 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 BookMutation) 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 BookMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *BookMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetTitle sets the "title" field. +func (m *BookMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *BookMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Book entity. +// If the Book 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 *BookMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *BookMutation) ResetTitle() { + m.title = nil +} + +// SetAuthor sets the "author" field. +func (m *BookMutation) SetAuthor(s string) { + m.author = &s +} + +// Author returns the value of the "author" field in the mutation. +func (m *BookMutation) Author() (r string, exists bool) { + v := m.author + if v == nil { + return + } + return *v, true +} + +// OldAuthor returns the old "author" field's value of the Book entity. +// If the Book 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 *BookMutation) OldAuthor(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldAuthor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldAuthor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthor: %w", err) + } + return oldValue.Author, nil +} + +// ResetAuthor resets all changes to the "author" field. +func (m *BookMutation) ResetAuthor() { + m.author = nil +} + +// SetSummary sets the "summary" field. +func (m *BookMutation) SetSummary(s string) { + m.summary = &s +} + +// Summary returns the value of the "summary" field in the mutation. +func (m *BookMutation) Summary() (r string, exists bool) { + v := m.summary + if v == nil { + return + } + return *v, true +} + +// OldSummary returns the old "summary" field's value of the Book entity. +// If the Book 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 *BookMutation) OldSummary(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldSummary is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldSummary requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSummary: %w", err) + } + return oldValue.Summary, nil +} + +// ResetSummary resets all changes to the "summary" field. +func (m *BookMutation) ResetSummary() { + m.summary = nil +} + +// SetImage sets the "image" field. +func (m *BookMutation) SetImage(s string) { + m.image = &s +} + +// Image returns the value of the "image" field in the mutation. +func (m *BookMutation) Image() (r string, exists bool) { + v := m.image + if v == nil { + return + } + return *v, true +} + +// OldImage returns the old "image" field's value of the Book entity. +// If the Book 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 *BookMutation) OldImage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldImage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldImage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImage: %w", err) + } + return oldValue.Image, nil +} + +// ResetImage resets all changes to the "image" field. +func (m *BookMutation) ResetImage() { + m.image = nil +} + +// Where appends a list predicates to the BookMutation builder. +func (m *BookMutation) Where(ps ...predicate.Book) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *BookMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Book). +func (m *BookMutation) 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 *BookMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.title != nil { + fields = append(fields, book.FieldTitle) + } + if m.author != nil { + fields = append(fields, book.FieldAuthor) + } + if m.summary != nil { + fields = append(fields, book.FieldSummary) + } + if m.image != nil { + fields = append(fields, book.FieldImage) + } + 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 *BookMutation) Field(name string) (ent.Value, bool) { + switch name { + case book.FieldTitle: + return m.Title() + case book.FieldAuthor: + return m.Author() + case book.FieldSummary: + return m.Summary() + case book.FieldImage: + return m.Image() + } + 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 *BookMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case book.FieldTitle: + return m.OldTitle(ctx) + case book.FieldAuthor: + return m.OldAuthor(ctx) + case book.FieldSummary: + return m.OldSummary(ctx) + case book.FieldImage: + return m.OldImage(ctx) + } + return nil, fmt.Errorf("unknown Book 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 *BookMutation) SetField(name string, value ent.Value) error { + switch name { + case book.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case book.FieldAuthor: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthor(v) + return nil + case book.FieldSummary: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSummary(v) + return nil + case book.FieldImage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImage(v) + return nil + } + return fmt.Errorf("unknown Book field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BookMutation) 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 *BookMutation) 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 *BookMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Book numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BookMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BookMutation) 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 *BookMutation) ClearField(name string) error { + return fmt.Errorf("unknown Book 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 *BookMutation) ResetField(name string) error { + switch name { + case book.FieldTitle: + m.ResetTitle() + return nil + case book.FieldAuthor: + m.ResetAuthor() + return nil + case book.FieldSummary: + m.ResetSummary() + return nil + case book.FieldImage: + m.ResetImage() + return nil + } + return fmt.Errorf("unknown Book field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BookMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BookMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BookMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BookMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BookMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BookMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *BookMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Book 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 *BookMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Book edge %s", name) +} + +// LinFileMutation represents an operation that mutates the LinFile nodes in the graph. +type LinFileMutation struct { + config + op Op + typ string + id *int + _path *string + _type *int8 + add_type *int8 + name *string + extension *string + size *int + addsize *int + md5 *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinFile, error) + predicates []predicate.LinFile +} + +var _ ent.Mutation = (*LinFileMutation)(nil) + +// linfileOption allows management of the mutation configuration using functional options. +type linfileOption func(*LinFileMutation) + +// newLinFileMutation creates new mutation for the LinFile entity. +func newLinFileMutation(c config, op Op, opts ...linfileOption) *LinFileMutation { + m := &LinFileMutation{ + config: c, + op: op, + typ: TypeLinFile, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinFileID sets the ID field of the mutation. +func withLinFileID(id int) linfileOption { + return func(m *LinFileMutation) { + var ( + err error + once sync.Once + value *LinFile + ) + m.oldValue = func(ctx context.Context) (*LinFile, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinFile.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinFile sets the old LinFile of the mutation. +func withLinFile(node *LinFile) linfileOption { + return func(m *LinFileMutation) { + m.oldValue = func(context.Context) (*LinFile, 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 LinFileMutation) 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 LinFileMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinFileMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetPath sets the "path" field. +func (m *LinFileMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *LinFileMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *LinFileMutation) ResetPath() { + m._path = nil +} + +// SetType sets the "type" field. +func (m *LinFileMutation) SetType(i int8) { + m._type = &i + m.add_type = nil +} + +// GetType returns the value of the "type" field in the mutation. +func (m *LinFileMutation) GetType() (r int8, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldType(ctx context.Context) (v int8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// AddType adds i to the "type" field. +func (m *LinFileMutation) AddType(i int8) { + if m.add_type != nil { + *m.add_type += i + } else { + m.add_type = &i + } +} + +// AddedType returns the value that was added to the "type" field in this mutation. +func (m *LinFileMutation) AddedType() (r int8, exists bool) { + v := m.add_type + if v == nil { + return + } + return *v, true +} + +// ResetType resets all changes to the "type" field. +func (m *LinFileMutation) ResetType() { + m._type = nil + m.add_type = nil +} + +// SetName sets the "name" field. +func (m *LinFileMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *LinFileMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *LinFileMutation) ResetName() { + m.name = nil +} + +// SetExtension sets the "extension" field. +func (m *LinFileMutation) SetExtension(s string) { + m.extension = &s +} + +// Extension returns the value of the "extension" field in the mutation. +func (m *LinFileMutation) Extension() (r string, exists bool) { + v := m.extension + if v == nil { + return + } + return *v, true +} + +// OldExtension returns the old "extension" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldExtension(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldExtension is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldExtension requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExtension: %w", err) + } + return oldValue.Extension, nil +} + +// ResetExtension resets all changes to the "extension" field. +func (m *LinFileMutation) ResetExtension() { + m.extension = nil +} + +// SetSize sets the "size" field. +func (m *LinFileMutation) SetSize(i int) { + m.size = &i + m.addsize = nil +} + +// Size returns the value of the "size" field in the mutation. +func (m *LinFileMutation) Size() (r int, exists bool) { + v := m.size + if v == nil { + return + } + return *v, true +} + +// OldSize returns the old "size" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldSize(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldSize is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldSize requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSize: %w", err) + } + return oldValue.Size, nil +} + +// AddSize adds i to the "size" field. +func (m *LinFileMutation) AddSize(i int) { + if m.addsize != nil { + *m.addsize += i + } else { + m.addsize = &i + } +} + +// AddedSize returns the value that was added to the "size" field in this mutation. +func (m *LinFileMutation) AddedSize() (r int, exists bool) { + v := m.addsize + if v == nil { + return + } + return *v, true +} + +// ResetSize resets all changes to the "size" field. +func (m *LinFileMutation) ResetSize() { + m.size = nil + m.addsize = nil +} + +// SetMd5 sets the "md5" field. +func (m *LinFileMutation) SetMd5(s string) { + m.md5 = &s +} + +// Md5 returns the value of the "md5" field in the mutation. +func (m *LinFileMutation) Md5() (r string, exists bool) { + v := m.md5 + if v == nil { + return + } + return *v, true +} + +// OldMd5 returns the old "md5" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldMd5(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMd5 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMd5 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMd5: %w", err) + } + return oldValue.Md5, nil +} + +// ResetMd5 resets all changes to the "md5" field. +func (m *LinFileMutation) ResetMd5() { + m.md5 = nil +} + +// Where appends a list predicates to the LinFileMutation builder. +func (m *LinFileMutation) Where(ps ...predicate.LinFile) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinFileMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinFile). +func (m *LinFileMutation) 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 *LinFileMutation) Fields() []string { + fields := make([]string, 0, 6) + if m._path != nil { + fields = append(fields, linfile.FieldPath) + } + if m._type != nil { + fields = append(fields, linfile.FieldType) + } + if m.name != nil { + fields = append(fields, linfile.FieldName) + } + if m.extension != nil { + fields = append(fields, linfile.FieldExtension) + } + if m.size != nil { + fields = append(fields, linfile.FieldSize) + } + if m.md5 != nil { + fields = append(fields, linfile.FieldMd5) + } + 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 *LinFileMutation) Field(name string) (ent.Value, bool) { + switch name { + case linfile.FieldPath: + return m.Path() + case linfile.FieldType: + return m.GetType() + case linfile.FieldName: + return m.Name() + case linfile.FieldExtension: + return m.Extension() + case linfile.FieldSize: + return m.Size() + case linfile.FieldMd5: + return m.Md5() + } + 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 *LinFileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linfile.FieldPath: + return m.OldPath(ctx) + case linfile.FieldType: + return m.OldType(ctx) + case linfile.FieldName: + return m.OldName(ctx) + case linfile.FieldExtension: + return m.OldExtension(ctx) + case linfile.FieldSize: + return m.OldSize(ctx) + case linfile.FieldMd5: + return m.OldMd5(ctx) + } + return nil, fmt.Errorf("unknown LinFile 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 *LinFileMutation) SetField(name string, value ent.Value) error { + switch name { + case linfile.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case linfile.FieldType: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case linfile.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case linfile.FieldExtension: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExtension(v) + return nil + case linfile.FieldSize: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSize(v) + return nil + case linfile.FieldMd5: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMd5(v) + return nil + } + return fmt.Errorf("unknown LinFile field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinFileMutation) AddedFields() []string { + var fields []string + if m.add_type != nil { + fields = append(fields, linfile.FieldType) + } + if m.addsize != nil { + fields = append(fields, linfile.FieldSize) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinFileMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linfile.FieldType: + return m.AddedType() + case linfile.FieldSize: + return m.AddedSize() + } + 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 *LinFileMutation) AddField(name string, value ent.Value) error { + switch name { + case linfile.FieldType: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddType(v) + return nil + case linfile.FieldSize: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSize(v) + return nil + } + return fmt.Errorf("unknown LinFile numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinFileMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinFileMutation) 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 *LinFileMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinFile 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 *LinFileMutation) ResetField(name string) error { + switch name { + case linfile.FieldPath: + m.ResetPath() + return nil + case linfile.FieldType: + m.ResetType() + return nil + case linfile.FieldName: + m.ResetName() + return nil + case linfile.FieldExtension: + m.ResetExtension() + return nil + case linfile.FieldSize: + m.ResetSize() + return nil + case linfile.FieldMd5: + m.ResetMd5() + return nil + } + return fmt.Errorf("unknown LinFile field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinFileMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinFileMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinFileMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinFileMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinFileMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinFileMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinFileMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinFile 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 *LinFileMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinFile edge %s", name) +} + +// LinGroupMutation represents an operation that mutates the LinGroup nodes in the graph. +type LinGroupMutation struct { + config + op Op + typ string + id *int + name *string + info *string + level *int8 + addlevel *int8 + clearedFields map[string]struct{} + lin_user map[int]struct{} + removedlin_user map[int]struct{} + clearedlin_user bool + lin_permission map[int]struct{} + removedlin_permission map[int]struct{} + clearedlin_permission bool + done bool + oldValue func(context.Context) (*LinGroup, error) + predicates []predicate.LinGroup +} + +var _ ent.Mutation = (*LinGroupMutation)(nil) + +// lingroupOption allows management of the mutation configuration using functional options. +type lingroupOption func(*LinGroupMutation) + +// newLinGroupMutation creates new mutation for the LinGroup entity. +func newLinGroupMutation(c config, op Op, opts ...lingroupOption) *LinGroupMutation { + m := &LinGroupMutation{ + config: c, + op: op, + typ: TypeLinGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinGroupID sets the ID field of the mutation. +func withLinGroupID(id int) lingroupOption { + return func(m *LinGroupMutation) { + var ( + err error + once sync.Once + value *LinGroup + ) + m.oldValue = func(ctx context.Context) (*LinGroup, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinGroup sets the old LinGroup of the mutation. +func withLinGroup(node *LinGroup) lingroupOption { + return func(m *LinGroupMutation) { + m.oldValue = func(context.Context) (*LinGroup, 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 LinGroupMutation) 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 LinGroupMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinGroupMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetName sets the "name" field. +func (m *LinGroupMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *LinGroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *LinGroupMutation) ResetName() { + m.name = nil +} + +// SetInfo sets the "info" field. +func (m *LinGroupMutation) SetInfo(s string) { + m.info = &s +} + +// Info returns the value of the "info" field in the mutation. +func (m *LinGroupMutation) Info() (r string, exists bool) { + v := m.info + if v == nil { + return + } + return *v, true +} + +// OldInfo returns the old "info" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldInfo(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldInfo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldInfo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInfo: %w", err) + } + return oldValue.Info, nil +} + +// ResetInfo resets all changes to the "info" field. +func (m *LinGroupMutation) ResetInfo() { + m.info = nil +} + +// SetLevel sets the "level" field. +func (m *LinGroupMutation) SetLevel(i int8) { + m.level = &i + m.addlevel = nil +} + +// Level returns the value of the "level" field in the mutation. +func (m *LinGroupMutation) Level() (r int8, exists bool) { + v := m.level + if v == nil { + return + } + return *v, true +} + +// OldLevel returns the old "level" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldLevel(ctx context.Context) (v int8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldLevel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldLevel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLevel: %w", err) + } + return oldValue.Level, nil +} + +// AddLevel adds i to the "level" field. +func (m *LinGroupMutation) AddLevel(i int8) { + if m.addlevel != nil { + *m.addlevel += i + } else { + m.addlevel = &i + } +} + +// AddedLevel returns the value that was added to the "level" field in this mutation. +func (m *LinGroupMutation) AddedLevel() (r int8, exists bool) { + v := m.addlevel + if v == nil { + return + } + return *v, true +} + +// ResetLevel resets all changes to the "level" field. +func (m *LinGroupMutation) ResetLevel() { + m.level = nil + m.addlevel = nil +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by ids. +func (m *LinGroupMutation) AddLinUserIDs(ids ...int) { + if m.lin_user == nil { + m.lin_user = make(map[int]struct{}) + } + for i := range ids { + m.lin_user[ids[i]] = struct{}{} + } +} + +// ClearLinUser clears the "lin_user" edge to the LinUser entity. +func (m *LinGroupMutation) ClearLinUser() { + m.clearedlin_user = true +} + +// LinUserCleared reports if the "lin_user" edge to the LinUser entity was cleared. +func (m *LinGroupMutation) LinUserCleared() bool { + return m.clearedlin_user +} + +// RemoveLinUserIDs removes the "lin_user" edge to the LinUser entity by IDs. +func (m *LinGroupMutation) RemoveLinUserIDs(ids ...int) { + if m.removedlin_user == nil { + m.removedlin_user = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_user, ids[i]) + m.removedlin_user[ids[i]] = struct{}{} + } +} + +// RemovedLinUser returns the removed IDs of the "lin_user" edge to the LinUser entity. +func (m *LinGroupMutation) RemovedLinUserIDs() (ids []int) { + for id := range m.removedlin_user { + ids = append(ids, id) + } + return +} + +// LinUserIDs returns the "lin_user" edge IDs in the mutation. +func (m *LinGroupMutation) LinUserIDs() (ids []int) { + for id := range m.lin_user { + ids = append(ids, id) + } + return +} + +// ResetLinUser resets all changes to the "lin_user" edge. +func (m *LinGroupMutation) ResetLinUser() { + m.lin_user = nil + m.clearedlin_user = false + m.removedlin_user = nil +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by ids. +func (m *LinGroupMutation) AddLinPermissionIDs(ids ...int) { + if m.lin_permission == nil { + m.lin_permission = make(map[int]struct{}) + } + for i := range ids { + m.lin_permission[ids[i]] = struct{}{} + } +} + +// ClearLinPermission clears the "lin_permission" edge to the LinPermission entity. +func (m *LinGroupMutation) ClearLinPermission() { + m.clearedlin_permission = true +} + +// LinPermissionCleared reports if the "lin_permission" edge to the LinPermission entity was cleared. +func (m *LinGroupMutation) LinPermissionCleared() bool { + return m.clearedlin_permission +} + +// RemoveLinPermissionIDs removes the "lin_permission" edge to the LinPermission entity by IDs. +func (m *LinGroupMutation) RemoveLinPermissionIDs(ids ...int) { + if m.removedlin_permission == nil { + m.removedlin_permission = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_permission, ids[i]) + m.removedlin_permission[ids[i]] = struct{}{} + } +} + +// RemovedLinPermission returns the removed IDs of the "lin_permission" edge to the LinPermission entity. +func (m *LinGroupMutation) RemovedLinPermissionIDs() (ids []int) { + for id := range m.removedlin_permission { + ids = append(ids, id) + } + return +} + +// LinPermissionIDs returns the "lin_permission" edge IDs in the mutation. +func (m *LinGroupMutation) LinPermissionIDs() (ids []int) { + for id := range m.lin_permission { + ids = append(ids, id) + } + return +} + +// ResetLinPermission resets all changes to the "lin_permission" edge. +func (m *LinGroupMutation) ResetLinPermission() { + m.lin_permission = nil + m.clearedlin_permission = false + m.removedlin_permission = nil +} + +// Where appends a list predicates to the LinGroupMutation builder. +func (m *LinGroupMutation) Where(ps ...predicate.LinGroup) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinGroupMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinGroup). +func (m *LinGroupMutation) 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 *LinGroupMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, lingroup.FieldName) + } + if m.info != nil { + fields = append(fields, lingroup.FieldInfo) + } + if m.level != nil { + fields = append(fields, lingroup.FieldLevel) + } + 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 *LinGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case lingroup.FieldName: + return m.Name() + case lingroup.FieldInfo: + return m.Info() + case lingroup.FieldLevel: + return m.Level() + } + 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 *LinGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case lingroup.FieldName: + return m.OldName(ctx) + case lingroup.FieldInfo: + return m.OldInfo(ctx) + case lingroup.FieldLevel: + return m.OldLevel(ctx) + } + return nil, fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case lingroup.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case lingroup.FieldInfo: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInfo(v) + return nil + case lingroup.FieldLevel: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLevel(v) + return nil + } + return fmt.Errorf("unknown LinGroup field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinGroupMutation) AddedFields() []string { + var fields []string + if m.addlevel != nil { + fields = append(fields, lingroup.FieldLevel) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinGroupMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case lingroup.FieldLevel: + return m.AddedLevel() + } + 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 *LinGroupMutation) AddField(name string, value ent.Value) error { + switch name { + case lingroup.FieldLevel: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddLevel(v) + return nil + } + return fmt.Errorf("unknown LinGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinGroupMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinGroupMutation) 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 *LinGroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) ResetField(name string) error { + switch name { + case lingroup.FieldName: + m.ResetName() + return nil + case lingroup.FieldInfo: + m.ResetInfo() + return nil + case lingroup.FieldLevel: + m.ResetLevel() + return nil + } + return fmt.Errorf("unknown LinGroup field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.lin_user != nil { + edges = append(edges, lingroup.EdgeLinUser) + } + if m.lin_permission != nil { + edges = append(edges, lingroup.EdgeLinPermission) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case lingroup.EdgeLinUser: + ids := make([]ent.Value, 0, len(m.lin_user)) + for id := range m.lin_user { + ids = append(ids, id) + } + return ids + case lingroup.EdgeLinPermission: + ids := make([]ent.Value, 0, len(m.lin_permission)) + for id := range m.lin_permission { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedlin_user != nil { + edges = append(edges, lingroup.EdgeLinUser) + } + if m.removedlin_permission != nil { + edges = append(edges, lingroup.EdgeLinPermission) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case lingroup.EdgeLinUser: + ids := make([]ent.Value, 0, len(m.removedlin_user)) + for id := range m.removedlin_user { + ids = append(ids, id) + } + return ids + case lingroup.EdgeLinPermission: + ids := make([]ent.Value, 0, len(m.removedlin_permission)) + for id := range m.removedlin_permission { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedlin_user { + edges = append(edges, lingroup.EdgeLinUser) + } + if m.clearedlin_permission { + edges = append(edges, lingroup.EdgeLinPermission) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinGroupMutation) EdgeCleared(name string) bool { + switch name { + case lingroup.EdgeLinUser: + return m.clearedlin_user + case lingroup.EdgeLinPermission: + return m.clearedlin_permission + } + 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 *LinGroupMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) ResetEdge(name string) error { + switch name { + case lingroup.EdgeLinUser: + m.ResetLinUser() + return nil + case lingroup.EdgeLinPermission: + m.ResetLinPermission() + return nil + } + return fmt.Errorf("unknown LinGroup edge %s", name) +} + +// LinGroupPermissionMutation represents an operation that mutates the LinGroupPermission nodes in the graph. +type LinGroupPermissionMutation struct { + config + op Op + typ string + id *int + group_id *int + addgroup_id *int + permission_id *int + addpermission_id *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinGroupPermission, error) + predicates []predicate.LinGroupPermission +} + +var _ ent.Mutation = (*LinGroupPermissionMutation)(nil) + +// lingrouppermissionOption allows management of the mutation configuration using functional options. +type lingrouppermissionOption func(*LinGroupPermissionMutation) + +// newLinGroupPermissionMutation creates new mutation for the LinGroupPermission entity. +func newLinGroupPermissionMutation(c config, op Op, opts ...lingrouppermissionOption) *LinGroupPermissionMutation { + m := &LinGroupPermissionMutation{ + config: c, + op: op, + typ: TypeLinGroupPermission, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinGroupPermissionID sets the ID field of the mutation. +func withLinGroupPermissionID(id int) lingrouppermissionOption { + return func(m *LinGroupPermissionMutation) { + var ( + err error + once sync.Once + value *LinGroupPermission + ) + m.oldValue = func(ctx context.Context) (*LinGroupPermission, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinGroupPermission.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinGroupPermission sets the old LinGroupPermission of the mutation. +func withLinGroupPermission(node *LinGroupPermission) lingrouppermissionOption { + return func(m *LinGroupPermissionMutation) { + m.oldValue = func(context.Context) (*LinGroupPermission, 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 LinGroupPermissionMutation) 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 LinGroupPermissionMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinGroupPermissionMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetGroupID sets the "group_id" field. +func (m *LinGroupPermissionMutation) SetGroupID(i int) { + m.group_id = &i + m.addgroup_id = nil +} + +// GroupID returns the value of the "group_id" field in the mutation. +func (m *LinGroupPermissionMutation) GroupID() (r int, exists bool) { + v := m.group_id + if v == nil { + return + } + return *v, true +} + +// OldGroupID returns the old "group_id" field's value of the LinGroupPermission entity. +// If the LinGroupPermission 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 *LinGroupPermissionMutation) OldGroupID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) + } + return oldValue.GroupID, nil +} + +// AddGroupID adds i to the "group_id" field. +func (m *LinGroupPermissionMutation) AddGroupID(i int) { + if m.addgroup_id != nil { + *m.addgroup_id += i + } else { + m.addgroup_id = &i + } +} + +// AddedGroupID returns the value that was added to the "group_id" field in this mutation. +func (m *LinGroupPermissionMutation) AddedGroupID() (r int, exists bool) { + v := m.addgroup_id + if v == nil { + return + } + return *v, true +} + +// ResetGroupID resets all changes to the "group_id" field. +func (m *LinGroupPermissionMutation) ResetGroupID() { + m.group_id = nil + m.addgroup_id = nil +} + +// SetPermissionID sets the "permission_id" field. +func (m *LinGroupPermissionMutation) SetPermissionID(i int) { + m.permission_id = &i + m.addpermission_id = nil +} + +// PermissionID returns the value of the "permission_id" field in the mutation. +func (m *LinGroupPermissionMutation) PermissionID() (r int, exists bool) { + v := m.permission_id + if v == nil { + return + } + return *v, true +} + +// OldPermissionID returns the old "permission_id" field's value of the LinGroupPermission entity. +// If the LinGroupPermission 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 *LinGroupPermissionMutation) OldPermissionID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPermissionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPermissionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPermissionID: %w", err) + } + return oldValue.PermissionID, nil +} + +// AddPermissionID adds i to the "permission_id" field. +func (m *LinGroupPermissionMutation) AddPermissionID(i int) { + if m.addpermission_id != nil { + *m.addpermission_id += i + } else { + m.addpermission_id = &i + } +} + +// AddedPermissionID returns the value that was added to the "permission_id" field in this mutation. +func (m *LinGroupPermissionMutation) AddedPermissionID() (r int, exists bool) { + v := m.addpermission_id + if v == nil { + return + } + return *v, true +} + +// ResetPermissionID resets all changes to the "permission_id" field. +func (m *LinGroupPermissionMutation) ResetPermissionID() { + m.permission_id = nil + m.addpermission_id = nil +} + +// Where appends a list predicates to the LinGroupPermissionMutation builder. +func (m *LinGroupPermissionMutation) Where(ps ...predicate.LinGroupPermission) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinGroupPermissionMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinGroupPermission). +func (m *LinGroupPermissionMutation) 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 *LinGroupPermissionMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.group_id != nil { + fields = append(fields, lingrouppermission.FieldGroupID) + } + if m.permission_id != nil { + fields = append(fields, lingrouppermission.FieldPermissionID) + } + 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 *LinGroupPermissionMutation) Field(name string) (ent.Value, bool) { + switch name { + case lingrouppermission.FieldGroupID: + return m.GroupID() + case lingrouppermission.FieldPermissionID: + return m.PermissionID() + } + 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 *LinGroupPermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case lingrouppermission.FieldGroupID: + return m.OldGroupID(ctx) + case lingrouppermission.FieldPermissionID: + return m.OldPermissionID(ctx) + } + return nil, fmt.Errorf("unknown LinGroupPermission 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 *LinGroupPermissionMutation) SetField(name string, value ent.Value) error { + switch name { + case lingrouppermission.FieldGroupID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGroupID(v) + return nil + case lingrouppermission.FieldPermissionID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPermissionID(v) + return nil + } + return fmt.Errorf("unknown LinGroupPermission field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinGroupPermissionMutation) AddedFields() []string { + var fields []string + if m.addgroup_id != nil { + fields = append(fields, lingrouppermission.FieldGroupID) + } + if m.addpermission_id != nil { + fields = append(fields, lingrouppermission.FieldPermissionID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinGroupPermissionMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case lingrouppermission.FieldGroupID: + return m.AddedGroupID() + case lingrouppermission.FieldPermissionID: + return m.AddedPermissionID() + } + 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 *LinGroupPermissionMutation) AddField(name string, value ent.Value) error { + switch name { + case lingrouppermission.FieldGroupID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddGroupID(v) + return nil + case lingrouppermission.FieldPermissionID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPermissionID(v) + return nil + } + return fmt.Errorf("unknown LinGroupPermission numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinGroupPermissionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinGroupPermissionMutation) 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 *LinGroupPermissionMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinGroupPermission 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 *LinGroupPermissionMutation) ResetField(name string) error { + switch name { + case lingrouppermission.FieldGroupID: + m.ResetGroupID() + return nil + case lingrouppermission.FieldPermissionID: + m.ResetPermissionID() + return nil + } + return fmt.Errorf("unknown LinGroupPermission field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinGroupPermissionMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinGroupPermissionMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinGroupPermissionMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinGroupPermissionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinGroupPermissionMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinGroupPermissionMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinGroupPermissionMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinGroupPermission 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 *LinGroupPermissionMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinGroupPermission edge %s", name) +} + +// LinLogMutation represents an operation that mutates the LinLog nodes in the graph. +type LinLogMutation struct { + config + op Op + typ string + id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time + message *string + user_id *int + adduser_id *int + username *string + status_code *int + addstatus_code *int + method *string + _path *string + permission *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinLog, error) + predicates []predicate.LinLog +} + +var _ ent.Mutation = (*LinLogMutation)(nil) + +// linlogOption allows management of the mutation configuration using functional options. +type linlogOption func(*LinLogMutation) + +// newLinLogMutation creates new mutation for the LinLog entity. +func newLinLogMutation(c config, op Op, opts ...linlogOption) *LinLogMutation { + m := &LinLogMutation{ + config: c, + op: op, + typ: TypeLinLog, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinLogID sets the ID field of the mutation. +func withLinLogID(id int) linlogOption { + return func(m *LinLogMutation) { + var ( + err error + once sync.Once + value *LinLog + ) + m.oldValue = func(ctx context.Context) (*LinLog, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinLog.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinLog sets the old LinLog of the mutation. +func withLinLog(node *LinLog) linlogOption { + return func(m *LinLogMutation) { + m.oldValue = func(context.Context) (*LinLog, 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 LinLogMutation) 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 LinLogMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinLogMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetCreateTime sets the "create_time" field. +func (m *LinLogMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *LinLogMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *LinLogMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *LinLogMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *LinLogMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *LinLogMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *LinLogMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *LinLogMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *LinLogMutation) ResetDeleteTime() { + m.delete_time = nil +} + +// SetMessage sets the "message" field. +func (m *LinLogMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *LinLogMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return + } + return *v, true +} + +// OldMessage returns the old "message" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil +} + +// ResetMessage resets all changes to the "message" field. +func (m *LinLogMutation) ResetMessage() { + m.message = nil +} + +// SetUserID sets the "user_id" field. +func (m *LinLogMutation) SetUserID(i int) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *LinLogMutation) UserID() (r int, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// AddUserID adds i to the "user_id" field. +func (m *LinLogMutation) AddUserID(i int) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *LinLogMutation) AddedUserID() (r int, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *LinLogMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetUsername sets the "username" field. +func (m *LinLogMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *LinLogMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *LinLogMutation) ResetUsername() { + m.username = nil +} + +// SetStatusCode sets the "status_code" field. +func (m *LinLogMutation) SetStatusCode(i int) { + m.status_code = &i + m.addstatus_code = nil +} + +// StatusCode returns the value of the "status_code" field in the mutation. +func (m *LinLogMutation) StatusCode() (r int, exists bool) { + v := m.status_code + if v == nil { + return + } + return *v, true +} + +// OldStatusCode returns the old "status_code" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldStatusCode(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldStatusCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldStatusCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatusCode: %w", err) + } + return oldValue.StatusCode, nil +} + +// AddStatusCode adds i to the "status_code" field. +func (m *LinLogMutation) AddStatusCode(i int) { + if m.addstatus_code != nil { + *m.addstatus_code += i + } else { + m.addstatus_code = &i + } +} + +// AddedStatusCode returns the value that was added to the "status_code" field in this mutation. +func (m *LinLogMutation) AddedStatusCode() (r int, exists bool) { + v := m.addstatus_code + if v == nil { + return + } + return *v, true +} + +// ResetStatusCode resets all changes to the "status_code" field. +func (m *LinLogMutation) ResetStatusCode() { + m.status_code = nil + m.addstatus_code = nil +} + +// SetMethod sets the "method" field. +func (m *LinLogMutation) SetMethod(s string) { + m.method = &s +} + +// Method returns the value of the "method" field in the mutation. +func (m *LinLogMutation) Method() (r string, exists bool) { + v := m.method + if v == nil { + return + } + return *v, true +} + +// OldMethod returns the old "method" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldMethod(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMethod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMethod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMethod: %w", err) + } + return oldValue.Method, nil +} + +// ResetMethod resets all changes to the "method" field. +func (m *LinLogMutation) ResetMethod() { + m.method = nil +} + +// SetPath sets the "path" field. +func (m *LinLogMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *LinLogMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *LinLogMutation) ResetPath() { + m._path = nil +} + +// SetPermission sets the "permission" field. +func (m *LinLogMutation) SetPermission(s string) { + m.permission = &s +} + +// Permission returns the value of the "permission" field in the mutation. +func (m *LinLogMutation) Permission() (r string, exists bool) { + v := m.permission + if v == nil { + return + } + return *v, true +} + +// OldPermission returns the old "permission" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldPermission(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPermission is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPermission requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPermission: %w", err) + } + return oldValue.Permission, nil +} + +// ResetPermission resets all changes to the "permission" field. +func (m *LinLogMutation) ResetPermission() { + m.permission = nil +} + +// Where appends a list predicates to the LinLogMutation builder. +func (m *LinLogMutation) Where(ps ...predicate.LinLog) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinLogMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinLog). +func (m *LinLogMutation) 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 *LinLogMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.create_time != nil { + fields = append(fields, linlog.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, linlog.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, linlog.FieldDeleteTime) + } + if m.message != nil { + fields = append(fields, linlog.FieldMessage) + } + if m.user_id != nil { + fields = append(fields, linlog.FieldUserID) + } + if m.username != nil { + fields = append(fields, linlog.FieldUsername) + } + if m.status_code != nil { + fields = append(fields, linlog.FieldStatusCode) + } + if m.method != nil { + fields = append(fields, linlog.FieldMethod) + } + if m._path != nil { + fields = append(fields, linlog.FieldPath) + } + if m.permission != nil { + fields = append(fields, linlog.FieldPermission) + } + 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 *LinLogMutation) Field(name string) (ent.Value, bool) { + switch name { + case linlog.FieldCreateTime: + return m.CreateTime() + case linlog.FieldUpdateTime: + return m.UpdateTime() + case linlog.FieldDeleteTime: + return m.DeleteTime() + case linlog.FieldMessage: + return m.Message() + case linlog.FieldUserID: + return m.UserID() + case linlog.FieldUsername: + return m.Username() + case linlog.FieldStatusCode: + return m.StatusCode() + case linlog.FieldMethod: + return m.Method() + case linlog.FieldPath: + return m.Path() + case linlog.FieldPermission: + return m.Permission() + } + 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 *LinLogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linlog.FieldCreateTime: + return m.OldCreateTime(ctx) + case linlog.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case linlog.FieldDeleteTime: + return m.OldDeleteTime(ctx) + case linlog.FieldMessage: + return m.OldMessage(ctx) + case linlog.FieldUserID: + return m.OldUserID(ctx) + case linlog.FieldUsername: + return m.OldUsername(ctx) + case linlog.FieldStatusCode: + return m.OldStatusCode(ctx) + case linlog.FieldMethod: + return m.OldMethod(ctx) + case linlog.FieldPath: + return m.OldPath(ctx) + case linlog.FieldPermission: + return m.OldPermission(ctx) + } + return nil, fmt.Errorf("unknown LinLog 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 *LinLogMutation) SetField(name string, value ent.Value) error { + switch name { + case linlog.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case linlog.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case linlog.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil + case linlog.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case linlog.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case linlog.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case linlog.FieldStatusCode: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatusCode(v) + return nil + case linlog.FieldMethod: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMethod(v) + return nil + case linlog.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case linlog.FieldPermission: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPermission(v) + return nil + } + return fmt.Errorf("unknown LinLog field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinLogMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, linlog.FieldUserID) + } + if m.addstatus_code != nil { + fields = append(fields, linlog.FieldStatusCode) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinLogMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linlog.FieldUserID: + return m.AddedUserID() + case linlog.FieldStatusCode: + return m.AddedStatusCode() + } + 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 *LinLogMutation) AddField(name string, value ent.Value) error { + switch name { + case linlog.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + case linlog.FieldStatusCode: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStatusCode(v) + return nil + } + return fmt.Errorf("unknown LinLog numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinLogMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinLogMutation) 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 *LinLogMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinLog 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 *LinLogMutation) ResetField(name string) error { + switch name { + case linlog.FieldCreateTime: + m.ResetCreateTime() + return nil + case linlog.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case linlog.FieldDeleteTime: + m.ResetDeleteTime() + return nil + case linlog.FieldMessage: + m.ResetMessage() + return nil + case linlog.FieldUserID: + m.ResetUserID() + return nil + case linlog.FieldUsername: + m.ResetUsername() + return nil + case linlog.FieldStatusCode: + m.ResetStatusCode() + return nil + case linlog.FieldMethod: + m.ResetMethod() + return nil + case linlog.FieldPath: + m.ResetPath() + return nil + case linlog.FieldPermission: + m.ResetPermission() + return nil + } + return fmt.Errorf("unknown LinLog field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinLogMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinLogMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinLogMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinLogMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinLogMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinLogMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinLogMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinLog 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 *LinLogMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinLog edge %s", name) +} + +// LinPermissionMutation represents an operation that mutates the LinPermission nodes in the graph. +type LinPermissionMutation struct { + config + op Op + typ string + id *int + name *string + module *string + mount *int8 + addmount *int8 + clearedFields map[string]struct{} + lin_group map[int]struct{} + removedlin_group map[int]struct{} + clearedlin_group bool + done bool + oldValue func(context.Context) (*LinPermission, error) + predicates []predicate.LinPermission +} + +var _ ent.Mutation = (*LinPermissionMutation)(nil) + +// linpermissionOption allows management of the mutation configuration using functional options. +type linpermissionOption func(*LinPermissionMutation) + +// newLinPermissionMutation creates new mutation for the LinPermission entity. +func newLinPermissionMutation(c config, op Op, opts ...linpermissionOption) *LinPermissionMutation { + m := &LinPermissionMutation{ + config: c, + op: op, + typ: TypeLinPermission, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinPermissionID sets the ID field of the mutation. +func withLinPermissionID(id int) linpermissionOption { + return func(m *LinPermissionMutation) { + var ( + err error + once sync.Once + value *LinPermission + ) + m.oldValue = func(ctx context.Context) (*LinPermission, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinPermission.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinPermission sets the old LinPermission of the mutation. +func withLinPermission(node *LinPermission) linpermissionOption { + return func(m *LinPermissionMutation) { + m.oldValue = func(context.Context) (*LinPermission, 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 LinPermissionMutation) 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 LinPermissionMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinPermissionMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetName sets the "name" field. +func (m *LinPermissionMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *LinPermissionMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the LinPermission entity. +// If the LinPermission 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 *LinPermissionMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *LinPermissionMutation) ResetName() { + m.name = nil +} + +// SetModule sets the "module" field. +func (m *LinPermissionMutation) SetModule(s string) { + m.module = &s +} + +// Module returns the value of the "module" field in the mutation. +func (m *LinPermissionMutation) Module() (r string, exists bool) { + v := m.module + if v == nil { + return + } + return *v, true +} + +// OldModule returns the old "module" field's value of the LinPermission entity. +// If the LinPermission 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 *LinPermissionMutation) OldModule(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldModule is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldModule requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModule: %w", err) + } + return oldValue.Module, nil +} + +// ResetModule resets all changes to the "module" field. +func (m *LinPermissionMutation) ResetModule() { + m.module = nil +} + +// SetMount sets the "mount" field. +func (m *LinPermissionMutation) SetMount(i int8) { + m.mount = &i + m.addmount = nil +} + +// Mount returns the value of the "mount" field in the mutation. +func (m *LinPermissionMutation) Mount() (r int8, exists bool) { + v := m.mount + if v == nil { + return + } + return *v, true +} + +// OldMount returns the old "mount" field's value of the LinPermission entity. +// If the LinPermission 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 *LinPermissionMutation) OldMount(ctx context.Context) (v int8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMount: %w", err) + } + return oldValue.Mount, nil +} + +// AddMount adds i to the "mount" field. +func (m *LinPermissionMutation) AddMount(i int8) { + if m.addmount != nil { + *m.addmount += i + } else { + m.addmount = &i + } +} + +// AddedMount returns the value that was added to the "mount" field in this mutation. +func (m *LinPermissionMutation) AddedMount() (r int8, exists bool) { + v := m.addmount + if v == nil { + return + } + return *v, true +} + +// ResetMount resets all changes to the "mount" field. +func (m *LinPermissionMutation) ResetMount() { + m.mount = nil + m.addmount = nil +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by ids. +func (m *LinPermissionMutation) AddLinGroupIDs(ids ...int) { + if m.lin_group == nil { + m.lin_group = make(map[int]struct{}) + } + for i := range ids { + m.lin_group[ids[i]] = struct{}{} + } +} + +// ClearLinGroup clears the "lin_group" edge to the LinGroup entity. +func (m *LinPermissionMutation) ClearLinGroup() { + m.clearedlin_group = true +} + +// LinGroupCleared reports if the "lin_group" edge to the LinGroup entity was cleared. +func (m *LinPermissionMutation) LinGroupCleared() bool { + return m.clearedlin_group +} + +// RemoveLinGroupIDs removes the "lin_group" edge to the LinGroup entity by IDs. +func (m *LinPermissionMutation) RemoveLinGroupIDs(ids ...int) { + if m.removedlin_group == nil { + m.removedlin_group = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_group, ids[i]) + m.removedlin_group[ids[i]] = struct{}{} + } +} + +// RemovedLinGroup returns the removed IDs of the "lin_group" edge to the LinGroup entity. +func (m *LinPermissionMutation) RemovedLinGroupIDs() (ids []int) { + for id := range m.removedlin_group { + ids = append(ids, id) + } + return +} + +// LinGroupIDs returns the "lin_group" edge IDs in the mutation. +func (m *LinPermissionMutation) LinGroupIDs() (ids []int) { + for id := range m.lin_group { + ids = append(ids, id) + } + return +} + +// ResetLinGroup resets all changes to the "lin_group" edge. +func (m *LinPermissionMutation) ResetLinGroup() { + m.lin_group = nil + m.clearedlin_group = false + m.removedlin_group = nil +} + +// Where appends a list predicates to the LinPermissionMutation builder. +func (m *LinPermissionMutation) Where(ps ...predicate.LinPermission) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinPermissionMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinPermission). +func (m *LinPermissionMutation) 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 *LinPermissionMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, linpermission.FieldName) + } + if m.module != nil { + fields = append(fields, linpermission.FieldModule) + } + if m.mount != nil { + fields = append(fields, linpermission.FieldMount) + } + 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 *LinPermissionMutation) Field(name string) (ent.Value, bool) { + switch name { + case linpermission.FieldName: + return m.Name() + case linpermission.FieldModule: + return m.Module() + case linpermission.FieldMount: + return m.Mount() + } + 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 *LinPermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linpermission.FieldName: + return m.OldName(ctx) + case linpermission.FieldModule: + return m.OldModule(ctx) + case linpermission.FieldMount: + return m.OldMount(ctx) + } + return nil, fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) SetField(name string, value ent.Value) error { + switch name { + case linpermission.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case linpermission.FieldModule: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModule(v) + return nil + case linpermission.FieldMount: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMount(v) + return nil + } + return fmt.Errorf("unknown LinPermission field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinPermissionMutation) AddedFields() []string { + var fields []string + if m.addmount != nil { + fields = append(fields, linpermission.FieldMount) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinPermissionMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linpermission.FieldMount: + return m.AddedMount() + } + 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 *LinPermissionMutation) AddField(name string, value ent.Value) error { + switch name { + case linpermission.FieldMount: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMount(v) + return nil + } + return fmt.Errorf("unknown LinPermission numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinPermissionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinPermissionMutation) 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 *LinPermissionMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) ResetField(name string) error { + switch name { + case linpermission.FieldName: + m.ResetName() + return nil + case linpermission.FieldModule: + m.ResetModule() + return nil + case linpermission.FieldMount: + m.ResetMount() + return nil + } + return fmt.Errorf("unknown LinPermission field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinPermissionMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.lin_group != nil { + edges = append(edges, linpermission.EdgeLinGroup) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinPermissionMutation) AddedIDs(name string) []ent.Value { + switch name { + case linpermission.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.lin_group)) + for id := range m.lin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinPermissionMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedlin_group != nil { + edges = append(edges, linpermission.EdgeLinGroup) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinPermissionMutation) RemovedIDs(name string) []ent.Value { + switch name { + case linpermission.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.removedlin_group)) + for id := range m.removedlin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinPermissionMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedlin_group { + edges = append(edges, linpermission.EdgeLinGroup) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinPermissionMutation) EdgeCleared(name string) bool { + switch name { + case linpermission.EdgeLinGroup: + return m.clearedlin_group + } + 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 *LinPermissionMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) ResetEdge(name string) error { + switch name { + case linpermission.EdgeLinGroup: + m.ResetLinGroup() + return nil + } + return fmt.Errorf("unknown LinPermission edge %s", name) +} + +// LinUserMutation represents an operation that mutates the LinUser nodes in the graph. +type LinUserMutation struct { + config + op Op + typ string + id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time + username *string + nickname *string + avatar *string + email *string + clearedFields map[string]struct{} + lin_user_identiy map[int]struct{} + removedlin_user_identiy map[int]struct{} + clearedlin_user_identiy bool + lin_group map[int]struct{} + removedlin_group map[int]struct{} + clearedlin_group bool + done bool + oldValue func(context.Context) (*LinUser, error) + predicates []predicate.LinUser +} + +var _ ent.Mutation = (*LinUserMutation)(nil) + +// linuserOption allows management of the mutation configuration using functional options. +type linuserOption func(*LinUserMutation) + +// newLinUserMutation creates new mutation for the LinUser entity. +func newLinUserMutation(c config, op Op, opts ...linuserOption) *LinUserMutation { + m := &LinUserMutation{ + config: c, + op: op, + typ: TypeLinUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinUserID sets the ID field of the mutation. +func withLinUserID(id int) linuserOption { + return func(m *LinUserMutation) { + var ( + err error + once sync.Once + value *LinUser + ) + m.oldValue = func(ctx context.Context) (*LinUser, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinUser.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinUser sets the old LinUser of the mutation. +func withLinUser(node *LinUser) linuserOption { + return func(m *LinUserMutation) { + m.oldValue = func(context.Context) (*LinUser, 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 LinUserMutation) 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 LinUserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinUserMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetCreateTime sets the "create_time" field. +func (m *LinUserMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *LinUserMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *LinUserMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *LinUserMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *LinUserMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *LinUserMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *LinUserMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *LinUserMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *LinUserMutation) ResetDeleteTime() { + m.delete_time = nil +} + +// SetUsername sets the "username" field. +func (m *LinUserMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *LinUserMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *LinUserMutation) ResetUsername() { + m.username = nil +} + +// SetNickname sets the "nickname" field. +func (m *LinUserMutation) SetNickname(s string) { + m.nickname = &s +} + +// Nickname returns the value of the "nickname" field in the mutation. +func (m *LinUserMutation) 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 LinUser entity. +// If the LinUser 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 *LinUserMutation) OldNickname(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldNickname is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// ResetNickname resets all changes to the "nickname" field. +func (m *LinUserMutation) ResetNickname() { + m.nickname = nil +} + +// SetAvatar sets the "avatar" field. +func (m *LinUserMutation) SetAvatar(s string) { + m.avatar = &s +} + +// Avatar returns the value of the "avatar" field in the mutation. +func (m *LinUserMutation) Avatar() (r string, exists bool) { + v := m.avatar + if v == nil { + return + } + return *v, true +} + +// OldAvatar returns the old "avatar" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldAvatar(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldAvatar is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldAvatar requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAvatar: %w", err) + } + return oldValue.Avatar, nil +} + +// ResetAvatar resets all changes to the "avatar" field. +func (m *LinUserMutation) ResetAvatar() { + m.avatar = nil +} + +// SetEmail sets the "email" field. +func (m *LinUserMutation) SetEmail(s string) { + m.email = &s +} + +// Email returns the value of the "email" field in the mutation. +func (m *LinUserMutation) 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 LinUser entity. +// If the LinUser 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 *LinUserMutation) OldEmail(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldEmail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// ResetEmail resets all changes to the "email" field. +func (m *LinUserMutation) ResetEmail() { + m.email = nil +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by ids. +func (m *LinUserMutation) AddLinUserIdentiyIDs(ids ...int) { + if m.lin_user_identiy == nil { + m.lin_user_identiy = make(map[int]struct{}) + } + for i := range ids { + m.lin_user_identiy[ids[i]] = struct{}{} + } +} + +// ClearLinUserIdentiy clears the "lin_user_identiy" edge to the LinUserIdentiy entity. +func (m *LinUserMutation) ClearLinUserIdentiy() { + m.clearedlin_user_identiy = true +} + +// LinUserIdentiyCleared reports if the "lin_user_identiy" edge to the LinUserIdentiy entity was cleared. +func (m *LinUserMutation) LinUserIdentiyCleared() bool { + return m.clearedlin_user_identiy +} + +// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (m *LinUserMutation) RemoveLinUserIdentiyIDs(ids ...int) { + if m.removedlin_user_identiy == nil { + m.removedlin_user_identiy = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_user_identiy, ids[i]) + m.removedlin_user_identiy[ids[i]] = struct{}{} + } +} + +// RemovedLinUserIdentiy returns the removed IDs of the "lin_user_identiy" edge to the LinUserIdentiy entity. +func (m *LinUserMutation) RemovedLinUserIdentiyIDs() (ids []int) { + for id := range m.removedlin_user_identiy { + ids = append(ids, id) + } + return +} + +// LinUserIdentiyIDs returns the "lin_user_identiy" edge IDs in the mutation. +func (m *LinUserMutation) LinUserIdentiyIDs() (ids []int) { + for id := range m.lin_user_identiy { + ids = append(ids, id) + } + return +} + +// ResetLinUserIdentiy resets all changes to the "lin_user_identiy" edge. +func (m *LinUserMutation) ResetLinUserIdentiy() { + m.lin_user_identiy = nil + m.clearedlin_user_identiy = false + m.removedlin_user_identiy = nil +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by ids. +func (m *LinUserMutation) AddLinGroupIDs(ids ...int) { + if m.lin_group == nil { + m.lin_group = make(map[int]struct{}) + } + for i := range ids { + m.lin_group[ids[i]] = struct{}{} + } +} + +// ClearLinGroup clears the "lin_group" edge to the LinGroup entity. +func (m *LinUserMutation) ClearLinGroup() { + m.clearedlin_group = true +} + +// LinGroupCleared reports if the "lin_group" edge to the LinGroup entity was cleared. +func (m *LinUserMutation) LinGroupCleared() bool { + return m.clearedlin_group +} + +// RemoveLinGroupIDs removes the "lin_group" edge to the LinGroup entity by IDs. +func (m *LinUserMutation) RemoveLinGroupIDs(ids ...int) { + if m.removedlin_group == nil { + m.removedlin_group = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_group, ids[i]) + m.removedlin_group[ids[i]] = struct{}{} + } +} + +// RemovedLinGroup returns the removed IDs of the "lin_group" edge to the LinGroup entity. +func (m *LinUserMutation) RemovedLinGroupIDs() (ids []int) { + for id := range m.removedlin_group { + ids = append(ids, id) + } + return +} + +// LinGroupIDs returns the "lin_group" edge IDs in the mutation. +func (m *LinUserMutation) LinGroupIDs() (ids []int) { + for id := range m.lin_group { + ids = append(ids, id) + } + return +} + +// ResetLinGroup resets all changes to the "lin_group" edge. +func (m *LinUserMutation) ResetLinGroup() { + m.lin_group = nil + m.clearedlin_group = false + m.removedlin_group = nil +} + +// Where appends a list predicates to the LinUserMutation builder. +func (m *LinUserMutation) Where(ps ...predicate.LinUser) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinUserMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinUser). +func (m *LinUserMutation) 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 *LinUserMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.create_time != nil { + fields = append(fields, linuser.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, linuser.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, linuser.FieldDeleteTime) + } + if m.username != nil { + fields = append(fields, linuser.FieldUsername) + } + if m.nickname != nil { + fields = append(fields, linuser.FieldNickname) + } + if m.avatar != nil { + fields = append(fields, linuser.FieldAvatar) + } + if m.email != nil { + fields = append(fields, linuser.FieldEmail) + } + 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 *LinUserMutation) Field(name string) (ent.Value, bool) { + switch name { + case linuser.FieldCreateTime: + return m.CreateTime() + case linuser.FieldUpdateTime: + return m.UpdateTime() + case linuser.FieldDeleteTime: + return m.DeleteTime() + case linuser.FieldUsername: + return m.Username() + case linuser.FieldNickname: + return m.Nickname() + case linuser.FieldAvatar: + return m.Avatar() + case linuser.FieldEmail: + return m.Email() + } + 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 *LinUserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linuser.FieldCreateTime: + return m.OldCreateTime(ctx) + case linuser.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case linuser.FieldDeleteTime: + return m.OldDeleteTime(ctx) + case linuser.FieldUsername: + return m.OldUsername(ctx) + case linuser.FieldNickname: + return m.OldNickname(ctx) + case linuser.FieldAvatar: + return m.OldAvatar(ctx) + case linuser.FieldEmail: + return m.OldEmail(ctx) + } + return nil, fmt.Errorf("unknown LinUser 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 *LinUserMutation) SetField(name string, value ent.Value) error { + switch name { + case linuser.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case linuser.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case linuser.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil + case linuser.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case linuser.FieldNickname: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNickname(v) + return nil + case linuser.FieldAvatar: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatar(v) + return nil + case linuser.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + } + return fmt.Errorf("unknown LinUser field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinUserMutation) 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 *LinUserMutation) 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 *LinUserMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LinUser numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinUserMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinUserMutation) 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 *LinUserMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinUser 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 *LinUserMutation) ResetField(name string) error { + switch name { + case linuser.FieldCreateTime: + m.ResetCreateTime() + return nil + case linuser.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case linuser.FieldDeleteTime: + m.ResetDeleteTime() + return nil + case linuser.FieldUsername: + m.ResetUsername() + return nil + case linuser.FieldNickname: + m.ResetNickname() + return nil + case linuser.FieldAvatar: + m.ResetAvatar() + return nil + case linuser.FieldEmail: + m.ResetEmail() + return nil + } + return fmt.Errorf("unknown LinUser field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinUserMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.lin_user_identiy != nil { + edges = append(edges, linuser.EdgeLinUserIdentiy) + } + if m.lin_group != nil { + edges = append(edges, linuser.EdgeLinGroup) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinUserMutation) AddedIDs(name string) []ent.Value { + switch name { + case linuser.EdgeLinUserIdentiy: + ids := make([]ent.Value, 0, len(m.lin_user_identiy)) + for id := range m.lin_user_identiy { + ids = append(ids, id) + } + return ids + case linuser.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.lin_group)) + for id := range m.lin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinUserMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedlin_user_identiy != nil { + edges = append(edges, linuser.EdgeLinUserIdentiy) + } + if m.removedlin_group != nil { + edges = append(edges, linuser.EdgeLinGroup) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinUserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case linuser.EdgeLinUserIdentiy: + ids := make([]ent.Value, 0, len(m.removedlin_user_identiy)) + for id := range m.removedlin_user_identiy { + ids = append(ids, id) + } + return ids + case linuser.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.removedlin_group)) + for id := range m.removedlin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinUserMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedlin_user_identiy { + edges = append(edges, linuser.EdgeLinUserIdentiy) + } + if m.clearedlin_group { + edges = append(edges, linuser.EdgeLinGroup) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinUserMutation) EdgeCleared(name string) bool { + switch name { + case linuser.EdgeLinUserIdentiy: + return m.clearedlin_user_identiy + case linuser.EdgeLinGroup: + return m.clearedlin_group + } + 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 *LinUserMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LinUser 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 *LinUserMutation) ResetEdge(name string) error { + switch name { + case linuser.EdgeLinUserIdentiy: + m.ResetLinUserIdentiy() + return nil + case linuser.EdgeLinGroup: + m.ResetLinGroup() + return nil + } + return fmt.Errorf("unknown LinUser edge %s", name) +} + +// LinUserIdentiyMutation represents an operation that mutates the LinUserIdentiy nodes in the graph. +type LinUserIdentiyMutation struct { + config + op Op + typ string + id *int + user_id *int + adduser_id *int + identity_type *string + identifier *string + credential *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinUserIdentiy, error) + predicates []predicate.LinUserIdentiy +} + +var _ ent.Mutation = (*LinUserIdentiyMutation)(nil) + +// linuseridentiyOption allows management of the mutation configuration using functional options. +type linuseridentiyOption func(*LinUserIdentiyMutation) + +// newLinUserIdentiyMutation creates new mutation for the LinUserIdentiy entity. +func newLinUserIdentiyMutation(c config, op Op, opts ...linuseridentiyOption) *LinUserIdentiyMutation { + m := &LinUserIdentiyMutation{ + config: c, + op: op, + typ: TypeLinUserIdentiy, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinUserIdentiyID sets the ID field of the mutation. +func withLinUserIdentiyID(id int) linuseridentiyOption { + return func(m *LinUserIdentiyMutation) { + var ( + err error + once sync.Once + value *LinUserIdentiy + ) + m.oldValue = func(ctx context.Context) (*LinUserIdentiy, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinUserIdentiy.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinUserIdentiy sets the old LinUserIdentiy of the mutation. +func withLinUserIdentiy(node *LinUserIdentiy) linuseridentiyOption { + return func(m *LinUserIdentiyMutation) { + m.oldValue = func(context.Context) (*LinUserIdentiy, 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 LinUserIdentiyMutation) 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 LinUserIdentiyMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinUserIdentiyMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetUserID sets the "user_id" field. +func (m *LinUserIdentiyMutation) SetUserID(i int) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *LinUserIdentiyMutation) UserID() (r int, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// AddUserID adds i to the "user_id" field. +func (m *LinUserIdentiyMutation) AddUserID(i int) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *LinUserIdentiyMutation) AddedUserID() (r int, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *LinUserIdentiyMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetIdentityType sets the "identity_type" field. +func (m *LinUserIdentiyMutation) SetIdentityType(s string) { + m.identity_type = &s +} + +// IdentityType returns the value of the "identity_type" field in the mutation. +func (m *LinUserIdentiyMutation) IdentityType() (r string, exists bool) { + v := m.identity_type + if v == nil { + return + } + return *v, true +} + +// OldIdentityType returns the old "identity_type" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldIdentityType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldIdentityType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldIdentityType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIdentityType: %w", err) + } + return oldValue.IdentityType, nil +} + +// ResetIdentityType resets all changes to the "identity_type" field. +func (m *LinUserIdentiyMutation) ResetIdentityType() { + m.identity_type = nil +} + +// SetIdentifier sets the "identifier" field. +func (m *LinUserIdentiyMutation) SetIdentifier(s string) { + m.identifier = &s +} + +// Identifier returns the value of the "identifier" field in the mutation. +func (m *LinUserIdentiyMutation) Identifier() (r string, exists bool) { + v := m.identifier + if v == nil { + return + } + return *v, true +} + +// OldIdentifier returns the old "identifier" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldIdentifier(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldIdentifier is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldIdentifier requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIdentifier: %w", err) + } + return oldValue.Identifier, nil +} + +// ResetIdentifier resets all changes to the "identifier" field. +func (m *LinUserIdentiyMutation) ResetIdentifier() { + m.identifier = nil +} + +// SetCredential sets the "credential" field. +func (m *LinUserIdentiyMutation) SetCredential(s string) { + m.credential = &s +} + +// Credential returns the value of the "credential" field in the mutation. +func (m *LinUserIdentiyMutation) Credential() (r string, exists bool) { + v := m.credential + if v == nil { + return + } + return *v, true +} + +// OldCredential returns the old "credential" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldCredential(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCredential is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCredential requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCredential: %w", err) + } + return oldValue.Credential, nil +} + +// ResetCredential resets all changes to the "credential" field. +func (m *LinUserIdentiyMutation) ResetCredential() { + m.credential = nil +} + +// Where appends a list predicates to the LinUserIdentiyMutation builder. +func (m *LinUserIdentiyMutation) Where(ps ...predicate.LinUserIdentiy) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinUserIdentiyMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinUserIdentiy). +func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.user_id != nil { + fields = append(fields, linuseridentiy.FieldUserID) + } + if m.identity_type != nil { + fields = append(fields, linuseridentiy.FieldIdentityType) + } + if m.identifier != nil { + fields = append(fields, linuseridentiy.FieldIdentifier) + } + if m.credential != nil { + fields = append(fields, linuseridentiy.FieldCredential) + } + 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 *LinUserIdentiyMutation) Field(name string) (ent.Value, bool) { + switch name { + case linuseridentiy.FieldUserID: + return m.UserID() + case linuseridentiy.FieldIdentityType: + return m.IdentityType() + case linuseridentiy.FieldIdentifier: + return m.Identifier() + case linuseridentiy.FieldCredential: + return m.Credential() + } + 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 *LinUserIdentiyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linuseridentiy.FieldUserID: + return m.OldUserID(ctx) + case linuseridentiy.FieldIdentityType: + return m.OldIdentityType(ctx) + case linuseridentiy.FieldIdentifier: + return m.OldIdentifier(ctx) + case linuseridentiy.FieldCredential: + return m.OldCredential(ctx) + } + return nil, fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) SetField(name string, value ent.Value) error { + switch name { + case linuseridentiy.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case linuseridentiy.FieldIdentityType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentityType(v) + return nil + case linuseridentiy.FieldIdentifier: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentifier(v) + return nil + case linuseridentiy.FieldCredential: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCredential(v) + return nil + } + return fmt.Errorf("unknown LinUserIdentiy field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinUserIdentiyMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, linuseridentiy.FieldUserID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinUserIdentiyMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linuseridentiy.FieldUserID: + return m.AddedUserID() + } + 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 *LinUserIdentiyMutation) AddField(name string, value ent.Value) error { + switch name { + case linuseridentiy.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + } + return fmt.Errorf("unknown LinUserIdentiy numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinUserIdentiyMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) ResetField(name string) error { + switch name { + case linuseridentiy.FieldUserID: + m.ResetUserID() + return nil + case linuseridentiy.FieldIdentityType: + m.ResetIdentityType() + return nil + case linuseridentiy.FieldIdentifier: + m.ResetIdentifier() + return nil + case linuseridentiy.FieldCredential: + m.ResetCredential() + return nil + } + return fmt.Errorf("unknown LinUserIdentiy field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinUserIdentiyMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinUserIdentiyMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinUserIdentiyMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinUserIdentiyMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinUserIdentiyMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinUserIdentiyMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinUserIdentiyMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinUserIdentiy edge %s", name) +} diff --git a/internal/data/model/predicate/predicate.go b/internal/data/model/predicate/predicate.go new file mode 100644 index 0000000..4d1fa5e --- /dev/null +++ b/internal/data/model/predicate/predicate.go @@ -0,0 +1,31 @@ +// Code generated by entc, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Book is the predicate function for book builders. +type Book func(*sql.Selector) + +// LinFile is the predicate function for linfile builders. +type LinFile func(*sql.Selector) + +// LinGroup is the predicate function for lingroup builders. +type LinGroup func(*sql.Selector) + +// LinGroupPermission is the predicate function for lingrouppermission builders. +type LinGroupPermission func(*sql.Selector) + +// LinLog is the predicate function for linlog builders. +type LinLog func(*sql.Selector) + +// LinPermission is the predicate function for linpermission builders. +type LinPermission func(*sql.Selector) + +// LinUser is the predicate function for linuser builders. +type LinUser func(*sql.Selector) + +// LinUserIdentiy is the predicate function for linuseridentiy builders. +type LinUserIdentiy func(*sql.Selector) diff --git a/internal/data/model/runtime.go b/internal/data/model/runtime.go new file mode 100644 index 0000000..345205e --- /dev/null +++ b/internal/data/model/runtime.go @@ -0,0 +1,58 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "lin-cms-go/internal/data/ent/schema" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linuser" + "time" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + linlogMixin := schema.LinLog{}.Mixin() + linlogMixinFields0 := linlogMixin[0].Fields() + _ = linlogMixinFields0 + linlogFields := schema.LinLog{}.Fields() + _ = linlogFields + // linlogDescCreateTime is the schema descriptor for create_time field. + linlogDescCreateTime := linlogMixinFields0[0].Descriptor() + // linlog.DefaultCreateTime holds the default value on creation for the create_time field. + linlog.DefaultCreateTime = linlogDescCreateTime.Default.(func() time.Time) + // linlogDescUpdateTime is the schema descriptor for update_time field. + linlogDescUpdateTime := linlogMixinFields0[1].Descriptor() + // linlog.DefaultUpdateTime holds the default value on creation for the update_time field. + linlog.DefaultUpdateTime = linlogDescUpdateTime.Default.(func() time.Time) + // linlog.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + linlog.UpdateDefaultUpdateTime = linlogDescUpdateTime.UpdateDefault.(func() time.Time) + // linlogDescDeleteTime is the schema descriptor for delete_time field. + linlogDescDeleteTime := linlogMixinFields0[2].Descriptor() + // linlog.DefaultDeleteTime holds the default value on creation for the delete_time field. + linlog.DefaultDeleteTime = linlogDescDeleteTime.Default.(func() time.Time) + linuserMixin := schema.LinUser{}.Mixin() + linuserMixinFields0 := linuserMixin[0].Fields() + _ = linuserMixinFields0 + linuserFields := schema.LinUser{}.Fields() + _ = linuserFields + // linuserDescCreateTime is the schema descriptor for create_time field. + linuserDescCreateTime := linuserMixinFields0[0].Descriptor() + // linuser.DefaultCreateTime holds the default value on creation for the create_time field. + linuser.DefaultCreateTime = linuserDescCreateTime.Default.(func() time.Time) + // linuserDescUpdateTime is the schema descriptor for update_time field. + linuserDescUpdateTime := linuserMixinFields0[1].Descriptor() + // linuser.DefaultUpdateTime holds the default value on creation for the update_time field. + linuser.DefaultUpdateTime = linuserDescUpdateTime.Default.(func() time.Time) + // linuser.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + linuser.UpdateDefaultUpdateTime = linuserDescUpdateTime.UpdateDefault.(func() time.Time) + // linuserDescDeleteTime is the schema descriptor for delete_time field. + linuserDescDeleteTime := linuserMixinFields0[2].Descriptor() + // linuser.DefaultDeleteTime holds the default value on creation for the delete_time field. + linuser.DefaultDeleteTime = linuserDescDeleteTime.Default.(func() time.Time) + // linuserDescAvatar is the schema descriptor for avatar field. + linuserDescAvatar := linuserFields[2].Descriptor() + // linuser.DefaultAvatar holds the default value on creation for the avatar field. + linuser.DefaultAvatar = linuserDescAvatar.Default.(string) +} diff --git a/internal/data/model/runtime/runtime.go b/internal/data/model/runtime/runtime.go new file mode 100644 index 0000000..73d2fd8 --- /dev/null +++ b/internal/data/model/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by entc, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in lin-cms-go/internal/data/model/runtime.go + +const ( + Version = "v0.9.1" // Version of ent codegen. + Sum = "h1:IG8andyeD79GG24U8Q+1Y45hQXj6gY5evSBcva5gtBk=" // Sum of ent codegen. +) diff --git a/internal/data/model/tx.go b/internal/data/model/tx.go new file mode 100644 index 0000000..c77a3a0 --- /dev/null +++ b/internal/data/model/tx.go @@ -0,0 +1,231 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Book is the client for interacting with the Book builders. + Book *BookClient + // LinFile is the client for interacting with the LinFile builders. + LinFile *LinFileClient + // LinGroup is the client for interacting with the LinGroup builders. + LinGroup *LinGroupClient + // LinGroupPermission is the client for interacting with the LinGroupPermission builders. + LinGroupPermission *LinGroupPermissionClient + // LinLog is the client for interacting with the LinLog builders. + LinLog *LinLogClient + // LinPermission is the client for interacting with the LinPermission builders. + LinPermission *LinPermissionClient + // LinUser is the client for interacting with the LinUser builders. + LinUser *LinUserClient + // LinUserIdentiy is the client for interacting with the LinUserIdentiy builders. + LinUserIdentiy *LinUserIdentiyClient + + // lazily loaded. + client *Client + clientOnce sync.Once + + // completion callbacks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook + + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Committer method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + tx.mu.Lock() + hooks := append([]CommitHook(nil), tx.onCommit...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onCommit = append(tx.onCommit, f) +} + +type ( + // Rollbacker is the interface that wraps the Rollbacker method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + tx.mu.Lock() + hooks := append([]RollbackHook(nil), tx.onRollback...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onRollback = append(tx.onRollback, f) +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Book = NewBookClient(tx.config) + tx.LinFile = NewLinFileClient(tx.config) + tx.LinGroup = NewLinGroupClient(tx.config) + tx.LinGroupPermission = NewLinGroupPermissionClient(tx.config) + tx.LinLog = NewLinLogClient(tx.config) + tx.LinPermission = NewLinPermissionClient(tx.config) + tx.LinUser = NewLinUserClient(tx.config) + tx.LinUserIdentiy = NewLinUserIdentiyClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Book.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/test/log_test.go b/test/log_test.go new file mode 100644 index 0000000..fb6ebdf --- /dev/null +++ b/test/log_test.go @@ -0,0 +1,27 @@ +package test + +import ( + "testing" + + +) + +func TestGetLogUsers(t *testing.T) { + // type args struct { + // c *fiber.Ctx + // } + // tests := []struct { + // name string + // args args + // wantErr bool + // }{ + // // TODO: Add test cases. + // } + // for _, tt := range tests { + // t.Run(tt.name, func(t *testing.T) { + // if err := api.GetLogUsers(tt.args.c); (err != nil) != tt.wantErr { + // t.Errorf("GetLogUsers() error = %v, wantErr %v", err, tt.wantErr) + // } + // }) + // } +} From 36774b71e4dea53585f5afdea7a7e092eaeaa935 Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Mon, 1 Nov 2021 10:21:27 +0800 Subject: [PATCH 25/44] feat:group --- internal/data/group.go | 36 ++++++++++++++++++++++++++++++++ internal/data/groupPermission.go | 15 +++++++++++++ internal/data/permission.go | 12 +++++++++++ internal/request/admin.go | 8 +++---- pkg/enum/grouplevel.go | 5 +++++ 5 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 internal/data/group.go create mode 100644 internal/data/groupPermission.go create mode 100644 internal/data/permission.go create mode 100644 pkg/enum/grouplevel.go diff --git a/internal/data/group.go b/internal/data/group.go new file mode 100644 index 0000000..79eb96c --- /dev/null +++ b/internal/data/group.go @@ -0,0 +1,36 @@ +package data + +import ( + "context" + "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/pkg/enum" +) + +func GetAllGroup(ctx context.Context) (groups []*model.LinGroup, err error) { + groups, err = GetDB().LinGroup.Query().All(ctx) + return +} + +func GetLinGroupById(ctx context.Context, groupId int) (group *model.LinGroup, err error) { + group, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).Where(lingroup.And(lingroup.LevelGT(enum.ROOT))).First(ctx) + return +} + +func GetLinGroupByName(ctx context.Context, name string) (group *model.LinGroup, err error) { + group, _ = GetDB().LinGroup.Query().Where(lingroup.Name(name)).First(ctx) + return +} + +func CreateGroup(ctx context.Context, name string, info string) (res *model.LinGroup, err error) { + res, err = GetDB().LinGroup.Create().SetName(name).SetInfo(info).SetLevel(3).Save(ctx) + if err != nil { + return + } + return +} + +func UpdateGroup(ctx context.Context, id int, name string, info string) (err error) { + _, err = GetDB().LinGroup.UpdateOneID(id).SetName(name).SetInfo(info).Save(ctx) + return +} diff --git a/internal/data/groupPermission.go b/internal/data/groupPermission.go new file mode 100644 index 0000000..c76bee7 --- /dev/null +++ b/internal/data/groupPermission.go @@ -0,0 +1,15 @@ +package data + +import ( + "context" + "lin-cms-go/internal/data/model" +) + +func BatchCreateGroupPermission(ctx context.Context, groupId int, permissionId []int) (err error) { + bulk := make([]*model.LinGroupPermissionCreate, len(permissionId)) + for i, pid := range permissionId { + bulk[i] = GetDB().LinGroupPermission.Create().SetGroupID(groupId).SetPermissionID(pid) + } + _, err = GetDB().LinGroupPermission.CreateBulk(bulk...).Save(ctx) + return +} diff --git a/internal/data/permission.go b/internal/data/permission.go new file mode 100644 index 0000000..2565c91 --- /dev/null +++ b/internal/data/permission.go @@ -0,0 +1,12 @@ +package data + +import ( + "context" + "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/linpermission" +) + +func GetLinPermissionById(ctx context.Context, id int) (permission *model.LinPermission, err error) { + permission, err = GetDB().LinPermission.Query().Where(linpermission.ID(id)).First(ctx) + return +} diff --git a/internal/request/admin.go b/internal/request/admin.go index 042ddf5..155b06c 100644 --- a/internal/request/admin.go +++ b/internal/request/admin.go @@ -18,11 +18,11 @@ type UpdateUser struct { GroupIds []int `json:"group_ids" validate:"required"` } type CreateGroup struct { - Name string `json:"name"` - Info string `json:"info"` + Name string `json:"name" validate:"required" comment:"分组名称"` + Info string `json:"info" validate:"required" comment:"分组信息"` PermissionIds []int `json:"permission_ids"` } type UpdateGroup struct { - Name string `json:"name"` - Info string `json:"info"` + Name string `json:"name" validate:"required" comment:"分组名称" ` + Info string `json:"info" validate:"required" comment:"分组信息" ` } diff --git a/pkg/enum/grouplevel.go b/pkg/enum/grouplevel.go new file mode 100644 index 0000000..a8c3a57 --- /dev/null +++ b/pkg/enum/grouplevel.go @@ -0,0 +1,5 @@ +package enum + +const ROOT int8 = 1 +const GUEST int8 = 2 +const USER int8 = 3 From fb5a2ae357588b4c1a8d5e5e3feb5751d16f8b4f Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Wed, 3 Nov 2021 15:23:08 +0800 Subject: [PATCH 26/44] perf:CreateGroup --- internal/data/group.go | 6 ++++++ internal/data/groupPermission.go | 25 ++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/internal/data/group.go b/internal/data/group.go index 79eb96c..d885df1 100644 --- a/internal/data/group.go +++ b/internal/data/group.go @@ -34,3 +34,9 @@ func UpdateGroup(ctx context.Context, id int, name string, info string) (err err _, err = GetDB().LinGroup.UpdateOneID(id).SetName(name).SetInfo(info).Save(ctx) return } + +func DeleteGroup(ctx context.Context, id int) (err error) { + + return nil + +} diff --git a/internal/data/groupPermission.go b/internal/data/groupPermission.go index c76bee7..7e3ffc6 100644 --- a/internal/data/groupPermission.go +++ b/internal/data/groupPermission.go @@ -3,13 +3,32 @@ package data import ( "context" "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/lingrouppermission" ) func BatchCreateGroupPermission(ctx context.Context, groupId int, permissionId []int) (err error) { - bulk := make([]*model.LinGroupPermissionCreate, len(permissionId)) - for i, pid := range permissionId { - bulk[i] = GetDB().LinGroupPermission.Create().SetGroupID(groupId).SetPermissionID(pid) + bulk := make([]*model.LinGroupPermissionCreate, 0) + for _, pid := range permissionId { + bulk = append(bulk, GetDB().LinGroupPermission.Create().SetGroupID(groupId).SetPermissionID(pid)) } _, err = GetDB().LinGroupPermission.CreateBulk(bulk...).Save(ctx) return } + +func GetGroupPermissionByGroupId(ctx context.Context, groupId int) (groupPermission []*model.LinGroupPermission, err error) { + groupPermission, err = GetDB().LinGroupPermission.Query().Where(lingrouppermission.GroupID(groupId)).All(ctx) + return +} + +func DeleteGroupPermission(ctx context.Context, groupId int) (err error) { + groupPermission, err := GetGroupPermissionByGroupId(ctx, groupId) + if err != nil { + return err + } + if len(groupPermission) == 0 { + return nil + } + + _, err = GetDB().LinGroupPermission.Delete().Where(lingrouppermission.GroupIDEQ(groupId)).Exec(ctx) + return +} From 5716be4125e602f47a1a428aff0f22f2ca8eea38 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 4 Nov 2021 11:34:08 +0800 Subject: [PATCH 27/44] refactor:error handle --- api/user.go | 1 + internal/biz/user.go | 9 +++++--- main.go | 9 ++++---- pkg/core/response.go | 43 ++++++++++++++++++++----------------- test/user_test.go | 51 ++++++++++++++++++++++---------------------- 5 files changed, 62 insertions(+), 51 deletions(-) diff --git a/api/user.go b/api/user.go index 766e212..cc9b85b 100644 --- a/api/user.go +++ b/api/user.go @@ -8,6 +8,7 @@ import ( "github.com/gofiber/fiber/v2" ) + func Hello(ctx *fiber.Ctx) error { return ctx.JSON("Hello") } diff --git a/internal/biz/user.go b/internal/biz/user.go index 7fccc6b..9313b1c 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -22,7 +22,7 @@ func Login(ctx context.Context, username, password string) (res map[string]inter // 正确密码验证 userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, username) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } if err != nil { @@ -125,12 +125,15 @@ func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, //data["permissions"] = permissions return } -func GetMyInfomation(ctx context.Context, uid int) (res interface{}, err error) { +type LinUser struct { + model.LinUser +} +func GetMyInfomation(ctx context.Context, uid int) (res LinUser, err error) { usermodel, err := data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { err = core.NewErrorCode(errcode.UserNotFound) return } - res = usermodel + res = LinUser{*usermodel} return } diff --git a/main.go b/main.go index 3dfef2c..9830151 100644 --- a/main.go +++ b/main.go @@ -17,14 +17,14 @@ import ( func errorHandler(c *fiber.Ctx, err error) error { // response err handle - if e, ok := err.(core.IError); ok { + if e, ok := err.(core.HttpError); ok { if e.Err == nil { - return e.HttpError(c) + return e.HandleHttpError(c) } } - return core.ServerError(c, err) + return core.HandleServerError(c, err) } func initLog(c *conf.Config) { log.SetFile(log.FileConfig{ @@ -62,11 +62,12 @@ func main() { if err != nil { panic(err) } - err = yaml.Unmarshal(yamlFile, &c) + err = yaml.Unmarshal(yamlFile, c) if err != nil { panic(err) } app := initApp(c) app.Listen(c.Server.Http.Addr) + } diff --git a/pkg/core/response.go b/pkg/core/response.go index 533d3ad..85bb7e7 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -13,10 +13,14 @@ type IError struct { Message string `json:"message"` // 提示信息 Data interface{} `json:"data"` // 返回数据 (业务接口定义具体数据结构) Err error `json:"-"` -} +} +type HttpError struct { + IError + Status int +} func (err IError) Error() (re string) { - return fmt.Sprintf("code=%v, Message=%v", err.Code, err.Message) + return fmt.Sprintf("code=%v, Message=%v,Err=%v", err.Code, err.Message,err.Err) } func NewErrorCode(code int) (err error) { @@ -66,19 +70,12 @@ func ParseRequest(c *fiber.Ctx, request interface{}) (err error) { err = ValidateRequest(request) return } -func FailResp(c *fiber.Ctx, code int) error { - return c.JSON(IError{ - Code: code, - Message: errcode.GetMsg(code), - }) -} -func ErrorResp(c *fiber.Ctx, code int, msg string) error { - return c.JSON(IError{ +func NewIError(code int,message string) IError { + return IError{ Code: code, - Message: msg, - }) - + Message: message, + } } func InvalidParamsError(c *fiber.Ctx, msg string) error { @@ -89,6 +86,14 @@ func InvalidParamsError(c *fiber.Ctx, msg string) error { } +func NotFoundError( code int) error { + + return HttpError{ + NewIError(code,errcode.GetMsg(code)), + fiber.StatusNotFound, + } + +} func SuccessResp(c *fiber.Ctx) error { return c.JSON(IError{ Code: 0, @@ -115,7 +120,7 @@ func SetPage(c *fiber.Ctx, list interface{}, totalRows int) error { }, }) } -func ServerError(c *fiber.Ctx, err error) error { +func HandleServerError(c *fiber.Ctx, err error) error { return c.JSON(IError{ Code: errcode.ServerError, @@ -123,9 +128,9 @@ func ServerError(c *fiber.Ctx, err error) error { Err: err, }) } -func (err *IError) HttpError(c *fiber.Ctx) error { - return c.JSON(IError{ - Code: err.Code, - Message: err.Message, - }) +func (err *HttpError) HandleHttpError(c *fiber.Ctx) error { + + return c.JSON(HttpError{IError{ + Code: err.Code,Message: err.Message, + },err.Status}) } diff --git a/test/user_test.go b/test/user_test.go index c6fd2a1..1f9e229 100644 --- a/test/user_test.go +++ b/test/user_test.go @@ -1,38 +1,39 @@ package test import ( + "fmt" "testing" ) +type I interface{ + F() +} + +type T struct { +} + +func (t *T) F() { +} -func testAddUsers(t *testing.T) { - - testcase := []TestCase{ - { - code: 40001, - param: `name=baibai&created_by=admin`, - errMsg: `该名称已存在`, - method: "POST", - desc: "验证插入名称已存在", - showBody: true, - url: "/api/v1/users", - ext1: 1, - }, - { - code: 0, - param: `name=5678999999&created_by=admin`, - errMsg: `创建成功`, - method: "POST", - desc: "验证创建成功", - showBody: true, - url: "/api/v1/users", - ext1: 1, - }, +func makeI() I { + var r *T + if r == nil { + fmt.Println("I am nil at makeI") + } + return r +} + + +func TestAddUsers(t *testing.T) { + i := makeI() + + if i != nil { + fmt.Println("I am not nil at main") } - call(t, testcase) + } func TestUserAll(t *testing.T) { - t.Run("TestAddUsers", testAddUsers) + //t.Run("TestEditUsers", testEditUsers) //t.Run("TestDeleteUsers", testDeleteUsers) } From 59e15a436dec136276481d80a5aebf656b6e688f Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 8 Nov 2021 15:18:52 +0800 Subject: [PATCH 28/44] fix: dispatch permissions --- api/permission.go | 3 +- docs/rest.http | 9 + docs/schema.sql | 8 + internal/biz/permission.go | 9 +- .../data/ent/schema/lin_group_permission.go | 23 - internal/data/ent/schema/lin_permission.go | 4 +- internal/data/group.go | 13 +- internal/data/groupPermission.go | 40 +- internal/data/model/book.go | 129 - internal/data/model/book/book.go | 39 - internal/data/model/book/where.go | 596 -- internal/data/model/book_create.go | 271 - internal/data/model/book_delete.go | 111 - internal/data/model/book_query.go | 960 ---- internal/data/model/book_update.go | 342 -- internal/data/model/client.go | 972 ---- internal/data/model/config.go | 66 - internal/data/model/context.go | 33 - internal/data/model/ent.go | 273 - internal/data/model/enttest/enttest.go | 77 - internal/data/model/hook/hook.go | 294 - internal/data/model/linfile.go | 151 - internal/data/model/linfile/linfile.go | 45 - internal/data/model/linfile/where.go | 762 --- internal/data/model/linfile_create.go | 305 -- internal/data/model/linfile_delete.go | 111 - internal/data/model/linfile_query.go | 960 ---- internal/data/model/linfile_update.go | 450 -- internal/data/model/lingroup.go | 164 - internal/data/model/lingroup/lingroup.go | 59 - internal/data/model/lingroup/where.go | 500 -- internal/data/model/lingroup_create.go | 324 -- internal/data/model/lingroup_delete.go | 111 - internal/data/model/lingroup_query.go | 1170 ---- internal/data/model/lingroup_update.go | 706 --- internal/data/model/lingrouppermission.go | 109 - .../lingrouppermission/lingrouppermission.go | 33 - .../data/model/lingrouppermission/where.go | 290 - .../data/model/lingrouppermission_create.go | 237 - .../data/model/lingrouppermission_delete.go | 111 - .../data/model/lingrouppermission_query.go | 960 ---- .../data/model/lingrouppermission_update.go | 346 -- internal/data/model/linlog.go | 192 - internal/data/model/linlog/linlog.go | 72 - internal/data/model/linlog/where.go | 1130 ---- internal/data/model/linlog_create.go | 416 -- internal/data/model/linlog_delete.go | 111 - internal/data/model/linlog_query.go | 960 ---- internal/data/model/linlog_update.go | 563 -- internal/data/model/linpermission.go | 148 - .../data/model/linpermission/linpermission.go | 49 - internal/data/model/linpermission/where.go | 472 -- internal/data/model/linpermission_create.go | 289 - internal/data/model/linpermission_delete.go | 111 - internal/data/model/linpermission_query.go | 1068 ---- internal/data/model/linpermission_update.go | 525 -- internal/data/model/linuser.go | 208 - internal/data/model/linuser/linuser.go | 87 - internal/data/model/linuser/where.go | 903 ---- internal/data/model/linuser_create.go | 447 -- internal/data/model/linuser_delete.go | 111 - internal/data/model/linuser_query.go | 1134 ---- internal/data/model/linuser_update.go | 807 --- internal/data/model/linuseridentiy.go | 140 - .../model/linuseridentiy/linuseridentiy.go | 50 - internal/data/model/linuseridentiy/where.go | 561 -- internal/data/model/linuseridentiy_create.go | 271 - internal/data/model/linuseridentiy_delete.go | 111 - internal/data/model/linuseridentiy_query.go | 965 ---- internal/data/model/linuseridentiy_update.go | 370 -- internal/data/model/migrate/migrate.go | 72 - internal/data/model/migrate/schema.go | 235 - internal/data/model/mutation.go | 4810 ----------------- internal/data/model/predicate/predicate.go | 31 - internal/data/model/runtime.go | 58 - internal/data/model/runtime/runtime.go | 10 - internal/data/model/tx.go | 231 - pkg/core/response.go | 22 +- 78 files changed, 63 insertions(+), 29853 deletions(-) delete mode 100644 internal/data/ent/schema/lin_group_permission.go delete mode 100644 internal/data/model/book.go delete mode 100644 internal/data/model/book/book.go delete mode 100644 internal/data/model/book/where.go delete mode 100644 internal/data/model/book_create.go delete mode 100644 internal/data/model/book_delete.go delete mode 100644 internal/data/model/book_query.go delete mode 100644 internal/data/model/book_update.go delete mode 100644 internal/data/model/client.go delete mode 100644 internal/data/model/config.go delete mode 100644 internal/data/model/context.go delete mode 100644 internal/data/model/ent.go delete mode 100644 internal/data/model/enttest/enttest.go delete mode 100644 internal/data/model/hook/hook.go delete mode 100644 internal/data/model/linfile.go delete mode 100644 internal/data/model/linfile/linfile.go delete mode 100644 internal/data/model/linfile/where.go delete mode 100644 internal/data/model/linfile_create.go delete mode 100644 internal/data/model/linfile_delete.go delete mode 100644 internal/data/model/linfile_query.go delete mode 100644 internal/data/model/linfile_update.go delete mode 100644 internal/data/model/lingroup.go delete mode 100644 internal/data/model/lingroup/lingroup.go delete mode 100644 internal/data/model/lingroup/where.go delete mode 100644 internal/data/model/lingroup_create.go delete mode 100644 internal/data/model/lingroup_delete.go delete mode 100644 internal/data/model/lingroup_query.go delete mode 100644 internal/data/model/lingroup_update.go delete mode 100644 internal/data/model/lingrouppermission.go delete mode 100644 internal/data/model/lingrouppermission/lingrouppermission.go delete mode 100644 internal/data/model/lingrouppermission/where.go delete mode 100644 internal/data/model/lingrouppermission_create.go delete mode 100644 internal/data/model/lingrouppermission_delete.go delete mode 100644 internal/data/model/lingrouppermission_query.go delete mode 100644 internal/data/model/lingrouppermission_update.go delete mode 100644 internal/data/model/linlog.go delete mode 100644 internal/data/model/linlog/linlog.go delete mode 100644 internal/data/model/linlog/where.go delete mode 100644 internal/data/model/linlog_create.go delete mode 100644 internal/data/model/linlog_delete.go delete mode 100644 internal/data/model/linlog_query.go delete mode 100644 internal/data/model/linlog_update.go delete mode 100644 internal/data/model/linpermission.go delete mode 100644 internal/data/model/linpermission/linpermission.go delete mode 100644 internal/data/model/linpermission/where.go delete mode 100644 internal/data/model/linpermission_create.go delete mode 100644 internal/data/model/linpermission_delete.go delete mode 100644 internal/data/model/linpermission_query.go delete mode 100644 internal/data/model/linpermission_update.go delete mode 100644 internal/data/model/linuser.go delete mode 100644 internal/data/model/linuser/linuser.go delete mode 100644 internal/data/model/linuser/where.go delete mode 100644 internal/data/model/linuser_create.go delete mode 100644 internal/data/model/linuser_delete.go delete mode 100644 internal/data/model/linuser_query.go delete mode 100644 internal/data/model/linuser_update.go delete mode 100644 internal/data/model/linuseridentiy.go delete mode 100644 internal/data/model/linuseridentiy/linuseridentiy.go delete mode 100644 internal/data/model/linuseridentiy/where.go delete mode 100644 internal/data/model/linuseridentiy_create.go delete mode 100644 internal/data/model/linuseridentiy_delete.go delete mode 100644 internal/data/model/linuseridentiy_query.go delete mode 100644 internal/data/model/linuseridentiy_update.go delete mode 100644 internal/data/model/migrate/migrate.go delete mode 100644 internal/data/model/migrate/schema.go delete mode 100644 internal/data/model/mutation.go delete mode 100644 internal/data/model/predicate/predicate.go delete mode 100644 internal/data/model/runtime.go delete mode 100644 internal/data/model/runtime/runtime.go delete mode 100644 internal/data/model/tx.go diff --git a/api/permission.go b/api/permission.go index 6767028..1db1b9b 100644 --- a/api/permission.go +++ b/api/permission.go @@ -19,6 +19,7 @@ func GetAllPermissions(c *fiber.Ctx) error { //TODO: 没找到必须实现该接口的业务场景,而且功能和分配多个权限重复,开发待定 func DispatchPermission(c *fiber.Ctx) error { + return nil } @@ -27,7 +28,7 @@ func DispatchPermissions(c *fiber.Ctx) error { if err := core.ParseRequest(c, &req); err != nil { return err } - err := biz.DispatchPermissions(req) + err := biz.DispatchPermissions(c.Context(), req.GroupId, req.PermissionIds) if err != nil { return err } diff --git a/docs/rest.http b/docs/rest.http index 862d2ad..723d419 100644 --- a/docs/rest.http +++ b/docs/rest.http @@ -19,6 +19,15 @@ Content-Type: application/json "password": "123456" } +### +POST http://localhost:3000/cms/admin/permissions/dispatch +Content-Type: application/json +Authorization: Bearer {{token}} + +{ + "group_id": 1, + "permission_ids": [1,2,3] +} ### GET http://localhost:3000/cms/user/permissions Content-Type: application/json diff --git a/docs/schema.sql b/docs/schema.sql index 1d5af2f..0ab4953 100644 --- a/docs/schema.sql +++ b/docs/schema.sql @@ -197,5 +197,13 @@ VALUES (2, 'guest', '游客组', 2); INSERT INTO lin_user_group(id, user_id, group_id) VALUES (1, 1, 1); +INSERT INTO `lin_permission` VALUES (1, '查看lin的信息', '信息',1, '2020-04-23 09:11:16', '2020-04-23 09:11:16', NULL); +INSERT INTO `lin_permission` VALUES (2, '查询自己信息', '用户',1, '2020-04-23 09:11:16.531', '2020-04-23 09:11:16.531', NULL); +INSERT INTO `lin_permission` VALUES (3, '查询自己拥有的权限', '用户',1, '2020-04-23 09:11:16.544', '2020-04-23 09:11:16.544', NULL); +INSERT INTO `lin_permission` VALUES (4, '查询日志记录的用户', '日志',1, '2020-04-23 09:11:16.554', '2020-04-23 09:11:16.554', NULL); +INSERT INTO `lin_permission` VALUES (5, '删除图书', '图书',1, '2020-04-23 09:11:16.562', '2020-04-23 09:11:16.562', NULL); +INSERT INTO `lin_permission` VALUES (6, '查询所有日志', '日志',1, '2020-04-23 09:11:16.571', '2020-04-23 09:11:16.571', NULL); +INSERT INTO `lin_permission` VALUES (7, '测试日志记录', '信息',1, '2020-04-23 09:11:16.580', '2020-04-23 09:11:16.580', NULL); +INSERT INTO `lin_permission` VALUES (8, '搜索日志', '日志',1, '2020-04-23 09:11:16.590', '2020-04-23 09:11:16.590', NULL); COMMIT; \ No newline at end of file diff --git a/internal/biz/permission.go b/internal/biz/permission.go index 75c4c83..6307316 100644 --- a/internal/biz/permission.go +++ b/internal/biz/permission.go @@ -1,6 +1,10 @@ package biz -import "lin-cms-go/internal/request" +import ( + "context" + "lin-cms-go/internal/data" + "lin-cms-go/internal/request" +) func GetAllPermissions() (data map[string]interface{}, err error) { return @@ -10,7 +14,8 @@ func DispatchPermission(req request.DispatchPermission) (err error) { return } -func DispatchPermissions(req request.DispatchPermissions) (err error) { +func DispatchPermissions(ctx context.Context, groupId int, permissionIds []int) (err error) { + err = data.BatchCreateGroupPermission(ctx, groupId, permissionIds) return } func RemovePermissions(req request.RemovePermissions) (err error) { diff --git a/internal/data/ent/schema/lin_group_permission.go b/internal/data/ent/schema/lin_group_permission.go deleted file mode 100644 index 43943d4..0000000 --- a/internal/data/ent/schema/lin_group_permission.go +++ /dev/null @@ -1,23 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/dialect/entsql" - "entgo.io/ent/schema" - "entgo.io/ent/schema/field" -) - -type LinGroupPermission struct { - ent.Schema -} -func (LinGroupPermission) Annotations() []schema.Annotation { - return []schema.Annotation{ - entsql.Annotation{Table: "lin_group_permission"}, - } -} -func (LinGroupPermission) Fields() []ent.Field { - return []ent.Field{ - field.Int("group_id").Comment("分组id").Unique(), - field.Int("permission_id").Comment("权限id"), - } -} diff --git a/internal/data/ent/schema/lin_permission.go b/internal/data/ent/schema/lin_permission.go index 1347875..02502bb 100644 --- a/internal/data/ent/schema/lin_permission.go +++ b/internal/data/ent/schema/lin_permission.go @@ -26,6 +26,8 @@ func (LinPermission) Fields() []ent.Field { } func (LinPermission) Edges() []ent.Edge { return []ent.Edge{ - edge.To("lin_group", LinGroup.Type), + edge.To("lin_group", LinGroup.Type).StorageKey( + edge.Table("lin_group_permission"), edge.Columns("permission_id", "group_id"), + ), } } diff --git a/internal/data/group.go b/internal/data/group.go index d885df1..e2580fd 100644 --- a/internal/data/group.go +++ b/internal/data/group.go @@ -12,18 +12,22 @@ func GetAllGroup(ctx context.Context) (groups []*model.LinGroup, err error) { return } -func GetLinGroupById(ctx context.Context, groupId int) (group *model.LinGroup, err error) { - group, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).Where(lingroup.And(lingroup.LevelGT(enum.ROOT))).First(ctx) +func GetLinGroupById(ctx context.Context, groupId int, level int8) (group *model.LinGroup, err error) { + group, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).Where(lingroup.And(lingroup.LevelGT(level))).First(ctx) return } +func GetRootLinGroup(ctx context.Context, groupId int) (group *model.LinGroup, err error) { + group, err = GetLinGroupById(ctx, groupId, enum.ROOT) + return +} func GetLinGroupByName(ctx context.Context, name string) (group *model.LinGroup, err error) { group, _ = GetDB().LinGroup.Query().Where(lingroup.Name(name)).First(ctx) return } -func CreateGroup(ctx context.Context, name string, info string) (res *model.LinGroup, err error) { - res, err = GetDB().LinGroup.Create().SetName(name).SetInfo(info).SetLevel(3).Save(ctx) +func CreateGroup(ctx context.Context, name string, info string, level int8) (res *model.LinGroup, err error) { + res, err = GetDB().LinGroup.Create().SetName(name).SetInfo(info).SetLevel(level).Save(ctx) if err != nil { return } @@ -35,6 +39,7 @@ func UpdateGroup(ctx context.Context, id int, name string, info string) (err err return } +// TODO update delete_time func DeleteGroup(ctx context.Context, id int) (err error) { return nil diff --git a/internal/data/groupPermission.go b/internal/data/groupPermission.go index 7e3ffc6..a83f385 100644 --- a/internal/data/groupPermission.go +++ b/internal/data/groupPermission.go @@ -2,33 +2,29 @@ package data import ( "context" - "lin-cms-go/internal/data/model" - "lin-cms-go/internal/data/model/lingrouppermission" + "lin-cms-go/internal/data/model/lingroup" ) func BatchCreateGroupPermission(ctx context.Context, groupId int, permissionId []int) (err error) { - bulk := make([]*model.LinGroupPermissionCreate, 0) - for _, pid := range permissionId { - bulk = append(bulk, GetDB().LinGroupPermission.Create().SetGroupID(groupId).SetPermissionID(pid)) - } - _, err = GetDB().LinGroupPermission.CreateBulk(bulk...).Save(ctx) - return -} -func GetGroupPermissionByGroupId(ctx context.Context, groupId int) (groupPermission []*model.LinGroupPermission, err error) { - groupPermission, err = GetDB().LinGroupPermission.Query().Where(lingrouppermission.GroupID(groupId)).All(ctx) + _, err = GetDB().LinGroup.Update().Where(lingroup.ID(groupId)).AddLinPermissionIDs(permissionId...).Save(ctx) return } -func DeleteGroupPermission(ctx context.Context, groupId int) (err error) { - groupPermission, err := GetGroupPermissionByGroupId(ctx, groupId) - if err != nil { - return err - } - if len(groupPermission) == 0 { - return nil - } +//func GetGroupPermissionByGroupId(ctx context.Context, groupId int) (groupPermission []*model.LinGroupPermission, err error) { +// groupPermission, err = GetDB().LinGroupPermission.Query().Where(lingrouppermission.GroupID(groupId)).All(ctx) +// return +//} - _, err = GetDB().LinGroupPermission.Delete().Where(lingrouppermission.GroupIDEQ(groupId)).Exec(ctx) - return -} +//func DeleteGroupPermission(ctx context.Context, groupId int) (err error) { +// groupPermission, err := GetGroupPermissionByGroupId(ctx, groupId) +// if err != nil { +// return err +// } +// if len(groupPermission) == 0 { +// return nil +// } +// +// _, err = GetDB().LinGroupPermission.Delete().Where(lingrouppermission.GroupIDEQ(groupId)).Exec(ctx) +// return +//} diff --git a/internal/data/model/book.go b/internal/data/model/book.go deleted file mode 100644 index 7714ba0..0000000 --- a/internal/data/model/book.go +++ /dev/null @@ -1,129 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/book" - "strings" - - "entgo.io/ent/dialect/sql" -) - -// Book is the model entity for the Book schema. -type Book struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // Title holds the value of the "title" field. - Title string `json:"title,omitempty"` - // Author holds the value of the "author" field. - Author string `json:"author,omitempty"` - // Summary holds the value of the "summary" field. - Summary string `json:"summary,omitempty"` - // Image holds the value of the "image" field. - Image string `json:"image,omitempty"` -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Book) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case book.FieldID: - values[i] = new(sql.NullInt64) - case book.FieldTitle, book.FieldAuthor, book.FieldSummary, book.FieldImage: - values[i] = new(sql.NullString) - default: - return nil, fmt.Errorf("unexpected column %q for type Book", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Book fields. -func (b *Book) assignValues(columns []string, values []interface{}) 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 book.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - b.ID = int(value.Int64) - case book.FieldTitle: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field title", values[i]) - } else if value.Valid { - b.Title = value.String - } - case book.FieldAuthor: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field author", values[i]) - } else if value.Valid { - b.Author = value.String - } - case book.FieldSummary: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field summary", values[i]) - } else if value.Valid { - b.Summary = value.String - } - case book.FieldImage: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field image", values[i]) - } else if value.Valid { - b.Image = value.String - } - } - } - return nil -} - -// Update returns a builder for updating this Book. -// Note that you need to call Book.Unwrap() before calling this method if this Book -// was returned from a transaction, and the transaction was committed or rolled back. -func (b *Book) Update() *BookUpdateOne { - return (&BookClient{config: b.config}).UpdateOne(b) -} - -// Unwrap unwraps the Book 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 (b *Book) Unwrap() *Book { - tx, ok := b.config.driver.(*txDriver) - if !ok { - panic("model: Book is not a transactional entity") - } - b.config.driver = tx.drv - return b -} - -// String implements the fmt.Stringer. -func (b *Book) String() string { - var builder strings.Builder - builder.WriteString("Book(") - builder.WriteString(fmt.Sprintf("id=%v", b.ID)) - builder.WriteString(", title=") - builder.WriteString(b.Title) - builder.WriteString(", author=") - builder.WriteString(b.Author) - builder.WriteString(", summary=") - builder.WriteString(b.Summary) - builder.WriteString(", image=") - builder.WriteString(b.Image) - builder.WriteByte(')') - return builder.String() -} - -// Books is a parsable slice of Book. -type Books []*Book - -func (b Books) config(cfg config) { - for _i := range b { - b[_i].config = cfg - } -} diff --git a/internal/data/model/book/book.go b/internal/data/model/book/book.go deleted file mode 100644 index 040d81c..0000000 --- a/internal/data/model/book/book.go +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package book - -const ( - // Label holds the string label denoting the book type in the database. - Label = "book" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldTitle holds the string denoting the title field in the database. - FieldTitle = "title" - // FieldAuthor holds the string denoting the author field in the database. - FieldAuthor = "author" - // FieldSummary holds the string denoting the summary field in the database. - FieldSummary = "summary" - // FieldImage holds the string denoting the image field in the database. - FieldImage = "image" - // Table holds the table name of the book in the database. - Table = "book" -) - -// Columns holds all SQL columns for book fields. -var Columns = []string{ - FieldID, - FieldTitle, - FieldAuthor, - FieldSummary, - FieldImage, -} - -// 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 -} diff --git a/internal/data/model/book/where.go b/internal/data/model/book/where.go deleted file mode 100644 index 7812ed5..0000000 --- a/internal/data/model/book/where.go +++ /dev/null @@ -1,596 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package book - -import ( - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. -func Title(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTitle), v)) - }) -} - -// Author applies equality check predicate on the "author" field. It's identical to AuthorEQ. -func Author(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldAuthor), v)) - }) -} - -// Summary applies equality check predicate on the "summary" field. It's identical to SummaryEQ. -func Summary(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldSummary), v)) - }) -} - -// Image applies equality check predicate on the "image" field. It's identical to ImageEQ. -func Image(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldImage), v)) - }) -} - -// TitleEQ applies the EQ predicate on the "title" field. -func TitleEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTitle), v)) - }) -} - -// TitleNEQ applies the NEQ predicate on the "title" field. -func TitleNEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldTitle), v)) - }) -} - -// TitleIn applies the In predicate on the "title" field. -func TitleIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldTitle), v...)) - }) -} - -// TitleNotIn applies the NotIn predicate on the "title" field. -func TitleNotIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldTitle), v...)) - }) -} - -// TitleGT applies the GT predicate on the "title" field. -func TitleGT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldTitle), v)) - }) -} - -// TitleGTE applies the GTE predicate on the "title" field. -func TitleGTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldTitle), v)) - }) -} - -// TitleLT applies the LT predicate on the "title" field. -func TitleLT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldTitle), v)) - }) -} - -// TitleLTE applies the LTE predicate on the "title" field. -func TitleLTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldTitle), v)) - }) -} - -// TitleContains applies the Contains predicate on the "title" field. -func TitleContains(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldTitle), v)) - }) -} - -// TitleHasPrefix applies the HasPrefix predicate on the "title" field. -func TitleHasPrefix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldTitle), v)) - }) -} - -// TitleHasSuffix applies the HasSuffix predicate on the "title" field. -func TitleHasSuffix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldTitle), v)) - }) -} - -// TitleEqualFold applies the EqualFold predicate on the "title" field. -func TitleEqualFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldTitle), v)) - }) -} - -// TitleContainsFold applies the ContainsFold predicate on the "title" field. -func TitleContainsFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldTitle), v)) - }) -} - -// AuthorEQ applies the EQ predicate on the "author" field. -func AuthorEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldAuthor), v)) - }) -} - -// AuthorNEQ applies the NEQ predicate on the "author" field. -func AuthorNEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldAuthor), v)) - }) -} - -// AuthorIn applies the In predicate on the "author" field. -func AuthorIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldAuthor), v...)) - }) -} - -// AuthorNotIn applies the NotIn predicate on the "author" field. -func AuthorNotIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldAuthor), v...)) - }) -} - -// AuthorGT applies the GT predicate on the "author" field. -func AuthorGT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldAuthor), v)) - }) -} - -// AuthorGTE applies the GTE predicate on the "author" field. -func AuthorGTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldAuthor), v)) - }) -} - -// AuthorLT applies the LT predicate on the "author" field. -func AuthorLT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldAuthor), v)) - }) -} - -// AuthorLTE applies the LTE predicate on the "author" field. -func AuthorLTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldAuthor), v)) - }) -} - -// AuthorContains applies the Contains predicate on the "author" field. -func AuthorContains(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldAuthor), v)) - }) -} - -// AuthorHasPrefix applies the HasPrefix predicate on the "author" field. -func AuthorHasPrefix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldAuthor), v)) - }) -} - -// AuthorHasSuffix applies the HasSuffix predicate on the "author" field. -func AuthorHasSuffix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldAuthor), v)) - }) -} - -// AuthorEqualFold applies the EqualFold predicate on the "author" field. -func AuthorEqualFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldAuthor), v)) - }) -} - -// AuthorContainsFold applies the ContainsFold predicate on the "author" field. -func AuthorContainsFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldAuthor), v)) - }) -} - -// SummaryEQ applies the EQ predicate on the "summary" field. -func SummaryEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldSummary), v)) - }) -} - -// SummaryNEQ applies the NEQ predicate on the "summary" field. -func SummaryNEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldSummary), v)) - }) -} - -// SummaryIn applies the In predicate on the "summary" field. -func SummaryIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldSummary), v...)) - }) -} - -// SummaryNotIn applies the NotIn predicate on the "summary" field. -func SummaryNotIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldSummary), v...)) - }) -} - -// SummaryGT applies the GT predicate on the "summary" field. -func SummaryGT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldSummary), v)) - }) -} - -// SummaryGTE applies the GTE predicate on the "summary" field. -func SummaryGTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldSummary), v)) - }) -} - -// SummaryLT applies the LT predicate on the "summary" field. -func SummaryLT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldSummary), v)) - }) -} - -// SummaryLTE applies the LTE predicate on the "summary" field. -func SummaryLTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldSummary), v)) - }) -} - -// SummaryContains applies the Contains predicate on the "summary" field. -func SummaryContains(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldSummary), v)) - }) -} - -// SummaryHasPrefix applies the HasPrefix predicate on the "summary" field. -func SummaryHasPrefix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldSummary), v)) - }) -} - -// SummaryHasSuffix applies the HasSuffix predicate on the "summary" field. -func SummaryHasSuffix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldSummary), v)) - }) -} - -// SummaryEqualFold applies the EqualFold predicate on the "summary" field. -func SummaryEqualFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldSummary), v)) - }) -} - -// SummaryContainsFold applies the ContainsFold predicate on the "summary" field. -func SummaryContainsFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldSummary), v)) - }) -} - -// ImageEQ applies the EQ predicate on the "image" field. -func ImageEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldImage), v)) - }) -} - -// ImageNEQ applies the NEQ predicate on the "image" field. -func ImageNEQ(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldImage), v)) - }) -} - -// ImageIn applies the In predicate on the "image" field. -func ImageIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldImage), v...)) - }) -} - -// ImageNotIn applies the NotIn predicate on the "image" field. -func ImageNotIn(vs ...string) predicate.Book { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Book(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldImage), v...)) - }) -} - -// ImageGT applies the GT predicate on the "image" field. -func ImageGT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldImage), v)) - }) -} - -// ImageGTE applies the GTE predicate on the "image" field. -func ImageGTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldImage), v)) - }) -} - -// ImageLT applies the LT predicate on the "image" field. -func ImageLT(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldImage), v)) - }) -} - -// ImageLTE applies the LTE predicate on the "image" field. -func ImageLTE(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldImage), v)) - }) -} - -// ImageContains applies the Contains predicate on the "image" field. -func ImageContains(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldImage), v)) - }) -} - -// ImageHasPrefix applies the HasPrefix predicate on the "image" field. -func ImageHasPrefix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldImage), v)) - }) -} - -// ImageHasSuffix applies the HasSuffix predicate on the "image" field. -func ImageHasSuffix(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldImage), v)) - }) -} - -// ImageEqualFold applies the EqualFold predicate on the "image" field. -func ImageEqualFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldImage), v)) - }) -} - -// ImageContainsFold applies the ContainsFold predicate on the "image" field. -func ImageContainsFold(v string) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldImage), v)) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Book) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Book) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Book) predicate.Book { - return predicate.Book(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/book_create.go b/internal/data/model/book_create.go deleted file mode 100644 index ba2bd4a..0000000 --- a/internal/data/model/book_create.go +++ /dev/null @@ -1,271 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/book" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// BookCreate is the builder for creating a Book entity. -type BookCreate struct { - config - mutation *BookMutation - hooks []Hook -} - -// SetTitle sets the "title" field. -func (bc *BookCreate) SetTitle(s string) *BookCreate { - bc.mutation.SetTitle(s) - return bc -} - -// SetAuthor sets the "author" field. -func (bc *BookCreate) SetAuthor(s string) *BookCreate { - bc.mutation.SetAuthor(s) - return bc -} - -// SetSummary sets the "summary" field. -func (bc *BookCreate) SetSummary(s string) *BookCreate { - bc.mutation.SetSummary(s) - return bc -} - -// SetImage sets the "image" field. -func (bc *BookCreate) SetImage(s string) *BookCreate { - bc.mutation.SetImage(s) - return bc -} - -// Mutation returns the BookMutation object of the builder. -func (bc *BookCreate) Mutation() *BookMutation { - return bc.mutation -} - -// Save creates the Book in the database. -func (bc *BookCreate) Save(ctx context.Context) (*Book, error) { - var ( - err error - node *Book - ) - if len(bc.hooks) == 0 { - if err = bc.check(); err != nil { - return nil, err - } - node, err = bc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*BookMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = bc.check(); err != nil { - return nil, err - } - bc.mutation = mutation - if node, err = bc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(bc.hooks) - 1; i >= 0; i-- { - if bc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = bc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, bc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (bc *BookCreate) SaveX(ctx context.Context) *Book { - v, err := bc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (bc *BookCreate) Exec(ctx context.Context) error { - _, err := bc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (bc *BookCreate) ExecX(ctx context.Context) { - if err := bc.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (bc *BookCreate) check() error { - if _, ok := bc.mutation.Title(); !ok { - return &ValidationError{Name: "title", err: errors.New(`model: missing required field "title"`)} - } - if _, ok := bc.mutation.Author(); !ok { - return &ValidationError{Name: "author", err: errors.New(`model: missing required field "author"`)} - } - if _, ok := bc.mutation.Summary(); !ok { - return &ValidationError{Name: "summary", err: errors.New(`model: missing required field "summary"`)} - } - if _, ok := bc.mutation.Image(); !ok { - return &ValidationError{Name: "image", err: errors.New(`model: missing required field "image"`)} - } - return nil -} - -func (bc *BookCreate) sqlSave(ctx context.Context) (*Book, error) { - _node, _spec := bc.createSpec() - if err := sqlgraph.CreateNode(ctx, bc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (bc *BookCreate) createSpec() (*Book, *sqlgraph.CreateSpec) { - var ( - _node = &Book{config: bc.config} - _spec = &sqlgraph.CreateSpec{ - Table: book.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: book.FieldID, - }, - } - ) - if value, ok := bc.mutation.Title(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldTitle, - }) - _node.Title = value - } - if value, ok := bc.mutation.Author(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldAuthor, - }) - _node.Author = value - } - if value, ok := bc.mutation.Summary(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldSummary, - }) - _node.Summary = value - } - if value, ok := bc.mutation.Image(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldImage, - }) - _node.Image = value - } - return _node, _spec -} - -// BookCreateBulk is the builder for creating many Book entities in bulk. -type BookCreateBulk struct { - config - builders []*BookCreate -} - -// Save creates the Book entities in the database. -func (bcb *BookCreateBulk) Save(ctx context.Context) ([]*Book, error) { - specs := make([]*sqlgraph.CreateSpec, len(bcb.builders)) - nodes := make([]*Book, len(bcb.builders)) - mutators := make([]Mutator, len(bcb.builders)) - for i := range bcb.builders { - func(i int, root context.Context) { - builder := bcb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*BookMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, bcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, bcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, bcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (bcb *BookCreateBulk) SaveX(ctx context.Context) []*Book { - v, err := bcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (bcb *BookCreateBulk) Exec(ctx context.Context) error { - _, err := bcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (bcb *BookCreateBulk) ExecX(ctx context.Context) { - if err := bcb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/book_delete.go b/internal/data/model/book_delete.go deleted file mode 100644 index 6813e56..0000000 --- a/internal/data/model/book_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/book" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// BookDelete is the builder for deleting a Book entity. -type BookDelete struct { - config - hooks []Hook - mutation *BookMutation -} - -// Where appends a list predicates to the BookDelete builder. -func (bd *BookDelete) Where(ps ...predicate.Book) *BookDelete { - bd.mutation.Where(ps...) - return bd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (bd *BookDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(bd.hooks) == 0 { - affected, err = bd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*BookMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - bd.mutation = mutation - affected, err = bd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(bd.hooks) - 1; i >= 0; i-- { - if bd.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = bd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, bd.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (bd *BookDelete) ExecX(ctx context.Context) int { - n, err := bd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (bd *BookDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: book.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: book.FieldID, - }, - }, - } - if ps := bd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, bd.driver, _spec) -} - -// BookDeleteOne is the builder for deleting a single Book entity. -type BookDeleteOne struct { - bd *BookDelete -} - -// Exec executes the deletion query. -func (bdo *BookDeleteOne) Exec(ctx context.Context) error { - n, err := bdo.bd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{book.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (bdo *BookDeleteOne) ExecX(ctx context.Context) { - bdo.bd.ExecX(ctx) -} diff --git a/internal/data/model/book_query.go b/internal/data/model/book_query.go deleted file mode 100644 index d27c9e7..0000000 --- a/internal/data/model/book_query.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/book" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// BookQuery is the builder for querying Book entities. -type BookQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.Book - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the BookQuery builder. -func (bq *BookQuery) Where(ps ...predicate.Book) *BookQuery { - bq.predicates = append(bq.predicates, ps...) - return bq -} - -// Limit adds a limit step to the query. -func (bq *BookQuery) Limit(limit int) *BookQuery { - bq.limit = &limit - return bq -} - -// Offset adds an offset step to the query. -func (bq *BookQuery) Offset(offset int) *BookQuery { - bq.offset = &offset - return bq -} - -// 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 (bq *BookQuery) Unique(unique bool) *BookQuery { - bq.unique = &unique - return bq -} - -// Order adds an order step to the query. -func (bq *BookQuery) Order(o ...OrderFunc) *BookQuery { - bq.order = append(bq.order, o...) - return bq -} - -// First returns the first Book entity from the query. -// Returns a *NotFoundError when no Book was found. -func (bq *BookQuery) First(ctx context.Context) (*Book, error) { - nodes, err := bq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{book.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (bq *BookQuery) FirstX(ctx context.Context) *Book { - node, err := bq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Book ID from the query. -// Returns a *NotFoundError when no Book ID was found. -func (bq *BookQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = bq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{book.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (bq *BookQuery) FirstIDX(ctx context.Context) int { - id, err := bq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last Book entity from the query. -// Returns a *NotFoundError when no Book was found. -func (bq *BookQuery) Last(ctx context.Context) (*Book, error) { - nodes, err := bq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{book.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (bq *BookQuery) LastX(ctx context.Context) *Book { - node, err := bq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last Book ID from the query. -// Returns a *NotFoundError when no Book ID was found. -func (bq *BookQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = bq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{book.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (bq *BookQuery) LastIDX(ctx context.Context) int { - id, err := bq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Book entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one Book entity is not found. -// Returns a *NotFoundError when no Book entities are found. -func (bq *BookQuery) Only(ctx context.Context) (*Book, error) { - nodes, err := bq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{book.Label} - default: - return nil, &NotSingularError{book.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (bq *BookQuery) OnlyX(ctx context.Context) *Book { - node, err := bq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Book ID in the query. -// Returns a *NotSingularError when exactly one Book ID is not found. -// Returns a *NotFoundError when no entities are found. -func (bq *BookQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = bq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{book.Label} - default: - err = &NotSingularError{book.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (bq *BookQuery) OnlyIDX(ctx context.Context) int { - id, err := bq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Books. -func (bq *BookQuery) All(ctx context.Context) ([]*Book, error) { - if err := bq.prepareQuery(ctx); err != nil { - return nil, err - } - return bq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (bq *BookQuery) AllX(ctx context.Context) []*Book { - nodes, err := bq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Book IDs. -func (bq *BookQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := bq.Select(book.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (bq *BookQuery) IDsX(ctx context.Context) []int { - ids, err := bq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (bq *BookQuery) Count(ctx context.Context) (int, error) { - if err := bq.prepareQuery(ctx); err != nil { - return 0, err - } - return bq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (bq *BookQuery) CountX(ctx context.Context) int { - count, err := bq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (bq *BookQuery) Exist(ctx context.Context) (bool, error) { - if err := bq.prepareQuery(ctx); err != nil { - return false, err - } - return bq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (bq *BookQuery) ExistX(ctx context.Context) bool { - exist, err := bq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the BookQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (bq *BookQuery) Clone() *BookQuery { - if bq == nil { - return nil - } - return &BookQuery{ - config: bq.config, - limit: bq.limit, - offset: bq.offset, - order: append([]OrderFunc{}, bq.order...), - predicates: append([]predicate.Book{}, bq.predicates...), - // clone intermediate query. - sql: bq.sql.Clone(), - path: bq.path, - } -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Title string `json:"title,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Book.Query(). -// GroupBy(book.FieldTitle). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (bq *BookQuery) GroupBy(field string, fields ...string) *BookGroupBy { - group := &BookGroupBy{config: bq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := bq.prepareQuery(ctx); err != nil { - return nil, err - } - return bq.sqlQuery(ctx), nil - } - return group -} - -// 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 { -// Title string `json:"title,omitempty"` -// } -// -// client.Book.Query(). -// Select(book.FieldTitle). -// Scan(ctx, &v) -// -func (bq *BookQuery) Select(fields ...string) *BookSelect { - bq.fields = append(bq.fields, fields...) - return &BookSelect{BookQuery: bq} -} - -func (bq *BookQuery) prepareQuery(ctx context.Context) error { - for _, f := range bq.fields { - if !book.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if bq.path != nil { - prev, err := bq.path(ctx) - if err != nil { - return err - } - bq.sql = prev - } - return nil -} - -func (bq *BookQuery) sqlAll(ctx context.Context) ([]*Book, error) { - var ( - nodes = []*Book{} - _spec = bq.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &Book{config: bq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, bq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (bq *BookQuery) sqlCount(ctx context.Context) (int, error) { - _spec := bq.querySpec() - return sqlgraph.CountNodes(ctx, bq.driver, _spec) -} - -func (bq *BookQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := bq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (bq *BookQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: book.Table, - Columns: book.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: book.FieldID, - }, - }, - From: bq.sql, - Unique: true, - } - if unique := bq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := bq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, book.FieldID) - for i := range fields { - if fields[i] != book.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := bq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := bq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := bq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := bq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (bq *BookQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(bq.driver.Dialect()) - t1 := builder.Table(book.Table) - columns := bq.fields - if len(columns) == 0 { - columns = book.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if bq.sql != nil { - selector = bq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range bq.predicates { - p(selector) - } - for _, p := range bq.order { - p(selector) - } - if offset := bq.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 := bq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// BookGroupBy is the group-by builder for Book entities. -type BookGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (bgb *BookGroupBy) Aggregate(fns ...AggregateFunc) *BookGroupBy { - bgb.fns = append(bgb.fns, fns...) - return bgb -} - -// Scan applies the group-by query and scans the result into the given value. -func (bgb *BookGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := bgb.path(ctx) - if err != nil { - return err - } - bgb.sql = query - return bgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (bgb *BookGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := bgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(bgb.fields) > 1 { - return nil, errors.New("model: BookGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := bgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (bgb *BookGroupBy) StringsX(ctx context.Context) []string { - v, err := bgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = bgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (bgb *BookGroupBy) StringX(ctx context.Context) string { - v, err := bgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(bgb.fields) > 1 { - return nil, errors.New("model: BookGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := bgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (bgb *BookGroupBy) IntsX(ctx context.Context) []int { - v, err := bgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = bgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (bgb *BookGroupBy) IntX(ctx context.Context) int { - v, err := bgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(bgb.fields) > 1 { - return nil, errors.New("model: BookGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := bgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (bgb *BookGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := bgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = bgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (bgb *BookGroupBy) Float64X(ctx context.Context) float64 { - v, err := bgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(bgb.fields) > 1 { - return nil, errors.New("model: BookGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := bgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (bgb *BookGroupBy) BoolsX(ctx context.Context) []bool { - v, err := bgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (bgb *BookGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = bgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (bgb *BookGroupBy) BoolX(ctx context.Context) bool { - v, err := bgb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (bgb *BookGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range bgb.fields { - if !book.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := bgb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := bgb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (bgb *BookGroupBy) sqlQuery() *sql.Selector { - selector := bgb.sql.Select() - aggregation := make([]string, 0, len(bgb.fns)) - for _, fn := range bgb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(bgb.fields)+len(bgb.fns)) - for _, f := range bgb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(bgb.fields...)...) -} - -// BookSelect is the builder for selecting fields of Book entities. -type BookSelect struct { - *BookQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (bs *BookSelect) Scan(ctx context.Context, v interface{}) error { - if err := bs.prepareQuery(ctx); err != nil { - return err - } - bs.sql = bs.BookQuery.sqlQuery(ctx) - return bs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (bs *BookSelect) ScanX(ctx context.Context, v interface{}) { - if err := bs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Strings(ctx context.Context) ([]string, error) { - if len(bs.fields) > 1 { - return nil, errors.New("model: BookSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := bs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (bs *BookSelect) StringsX(ctx context.Context) []string { - v, err := bs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = bs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (bs *BookSelect) StringX(ctx context.Context) string { - v, err := bs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Ints(ctx context.Context) ([]int, error) { - if len(bs.fields) > 1 { - return nil, errors.New("model: BookSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := bs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (bs *BookSelect) IntsX(ctx context.Context) []int { - v, err := bs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = bs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (bs *BookSelect) IntX(ctx context.Context) int { - v, err := bs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(bs.fields) > 1 { - return nil, errors.New("model: BookSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := bs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (bs *BookSelect) Float64sX(ctx context.Context) []float64 { - v, err := bs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = bs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (bs *BookSelect) Float64X(ctx context.Context) float64 { - v, err := bs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Bools(ctx context.Context) ([]bool, error) { - if len(bs.fields) > 1 { - return nil, errors.New("model: BookSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := bs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (bs *BookSelect) BoolsX(ctx context.Context) []bool { - v, err := bs.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (bs *BookSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = bs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{book.Label} - default: - err = fmt.Errorf("model: BookSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (bs *BookSelect) BoolX(ctx context.Context) bool { - v, err := bs.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (bs *BookSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := bs.sql.Query() - if err := bs.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/book_update.go b/internal/data/model/book_update.go deleted file mode 100644 index 1d409aa..0000000 --- a/internal/data/model/book_update.go +++ /dev/null @@ -1,342 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/book" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// BookUpdate is the builder for updating Book entities. -type BookUpdate struct { - config - hooks []Hook - mutation *BookMutation -} - -// Where appends a list predicates to the BookUpdate builder. -func (bu *BookUpdate) Where(ps ...predicate.Book) *BookUpdate { - bu.mutation.Where(ps...) - return bu -} - -// SetTitle sets the "title" field. -func (bu *BookUpdate) SetTitle(s string) *BookUpdate { - bu.mutation.SetTitle(s) - return bu -} - -// SetAuthor sets the "author" field. -func (bu *BookUpdate) SetAuthor(s string) *BookUpdate { - bu.mutation.SetAuthor(s) - return bu -} - -// SetSummary sets the "summary" field. -func (bu *BookUpdate) SetSummary(s string) *BookUpdate { - bu.mutation.SetSummary(s) - return bu -} - -// SetImage sets the "image" field. -func (bu *BookUpdate) SetImage(s string) *BookUpdate { - bu.mutation.SetImage(s) - return bu -} - -// Mutation returns the BookMutation object of the builder. -func (bu *BookUpdate) Mutation() *BookMutation { - return bu.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (bu *BookUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(bu.hooks) == 0 { - affected, err = bu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*BookMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - bu.mutation = mutation - affected, err = bu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(bu.hooks) - 1; i >= 0; i-- { - if bu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = bu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, bu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (bu *BookUpdate) SaveX(ctx context.Context) int { - affected, err := bu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (bu *BookUpdate) Exec(ctx context.Context) error { - _, err := bu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (bu *BookUpdate) ExecX(ctx context.Context) { - if err := bu.Exec(ctx); err != nil { - panic(err) - } -} - -func (bu *BookUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: book.Table, - Columns: book.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: book.FieldID, - }, - }, - } - if ps := bu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := bu.mutation.Title(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldTitle, - }) - } - if value, ok := bu.mutation.Author(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldAuthor, - }) - } - if value, ok := bu.mutation.Summary(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldSummary, - }) - } - if value, ok := bu.mutation.Image(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldImage, - }) - } - if n, err = sqlgraph.UpdateNodes(ctx, bu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{book.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// BookUpdateOne is the builder for updating a single Book entity. -type BookUpdateOne struct { - config - fields []string - hooks []Hook - mutation *BookMutation -} - -// SetTitle sets the "title" field. -func (buo *BookUpdateOne) SetTitle(s string) *BookUpdateOne { - buo.mutation.SetTitle(s) - return buo -} - -// SetAuthor sets the "author" field. -func (buo *BookUpdateOne) SetAuthor(s string) *BookUpdateOne { - buo.mutation.SetAuthor(s) - return buo -} - -// SetSummary sets the "summary" field. -func (buo *BookUpdateOne) SetSummary(s string) *BookUpdateOne { - buo.mutation.SetSummary(s) - return buo -} - -// SetImage sets the "image" field. -func (buo *BookUpdateOne) SetImage(s string) *BookUpdateOne { - buo.mutation.SetImage(s) - return buo -} - -// Mutation returns the BookMutation object of the builder. -func (buo *BookUpdateOne) Mutation() *BookMutation { - return buo.mutation -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (buo *BookUpdateOne) Select(field string, fields ...string) *BookUpdateOne { - buo.fields = append([]string{field}, fields...) - return buo -} - -// Save executes the query and returns the updated Book entity. -func (buo *BookUpdateOne) Save(ctx context.Context) (*Book, error) { - var ( - err error - node *Book - ) - if len(buo.hooks) == 0 { - node, err = buo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*BookMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - buo.mutation = mutation - node, err = buo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(buo.hooks) - 1; i >= 0; i-- { - if buo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = buo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, buo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (buo *BookUpdateOne) SaveX(ctx context.Context) *Book { - node, err := buo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (buo *BookUpdateOne) Exec(ctx context.Context) error { - _, err := buo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (buo *BookUpdateOne) ExecX(ctx context.Context) { - if err := buo.Exec(ctx); err != nil { - panic(err) - } -} - -func (buo *BookUpdateOne) sqlSave(ctx context.Context) (_node *Book, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: book.Table, - Columns: book.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: book.FieldID, - }, - }, - } - id, ok := buo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Book.ID for update")} - } - _spec.Node.ID.Value = id - if fields := buo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, book.FieldID) - for _, f := range fields { - if !book.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != book.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := buo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := buo.mutation.Title(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldTitle, - }) - } - if value, ok := buo.mutation.Author(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldAuthor, - }) - } - if value, ok := buo.mutation.Summary(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldSummary, - }) - } - if value, ok := buo.mutation.Image(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: book.FieldImage, - }) - } - _node = &Book{config: buo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, buo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{book.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/client.go b/internal/data/model/client.go deleted file mode 100644 index 98d1565..0000000 --- a/internal/data/model/client.go +++ /dev/null @@ -1,972 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "log" - - "lin-cms-go/internal/data/model/migrate" - - "lin-cms-go/internal/data/model/book" - "lin-cms-go/internal/data/model/linfile" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/lingrouppermission" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/linuseridentiy" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -// Client is the client that holds all ent builders. -type Client struct { - config - // Schema is the client for creating, migrating and dropping schema. - Schema *migrate.Schema - // Book is the client for interacting with the Book builders. - Book *BookClient - // LinFile is the client for interacting with the LinFile builders. - LinFile *LinFileClient - // LinGroup is the client for interacting with the LinGroup builders. - LinGroup *LinGroupClient - // LinGroupPermission is the client for interacting with the LinGroupPermission builders. - LinGroupPermission *LinGroupPermissionClient - // LinLog is the client for interacting with the LinLog builders. - LinLog *LinLogClient - // LinPermission is the client for interacting with the LinPermission builders. - LinPermission *LinPermissionClient - // LinUser is the client for interacting with the LinUser builders. - LinUser *LinUserClient - // LinUserIdentiy is the client for interacting with the LinUserIdentiy builders. - LinUserIdentiy *LinUserIdentiyClient -} - -// NewClient creates a new client configured with the given options. -func NewClient(opts ...Option) *Client { - cfg := config{log: log.Println, hooks: &hooks{}} - cfg.options(opts...) - client := &Client{config: cfg} - client.init() - return client -} - -func (c *Client) init() { - c.Schema = migrate.NewSchema(c.driver) - c.Book = NewBookClient(c.config) - c.LinFile = NewLinFileClient(c.config) - c.LinGroup = NewLinGroupClient(c.config) - c.LinGroupPermission = NewLinGroupPermissionClient(c.config) - c.LinLog = NewLinLogClient(c.config) - c.LinPermission = NewLinPermissionClient(c.config) - c.LinUser = NewLinUserClient(c.config) - c.LinUserIdentiy = NewLinUserIdentiyClient(c.config) -} - -// Open opens a database/sql.DB specified by the driver name and -// the data source name, and returns a new client attached to it. -// Optional parameters can be added for configuring the client. -func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { - switch driverName { - case dialect.MySQL, dialect.Postgres, dialect.SQLite: - drv, err := sql.Open(driverName, dataSourceName) - if err != nil { - return nil, err - } - return NewClient(append(options, Driver(drv))...), nil - default: - return nil, fmt.Errorf("unsupported driver: %q", driverName) - } -} - -// Tx returns a new transactional client. The provided context -// is used until the transaction is committed or rolled back. -func (c *Client) Tx(ctx context.Context) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, fmt.Errorf("model: cannot start a transaction within a transaction") - } - tx, err := newTx(ctx, c.driver) - if err != nil { - return nil, fmt.Errorf("model: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = tx - return &Tx{ - ctx: ctx, - config: cfg, - Book: NewBookClient(cfg), - LinFile: NewLinFileClient(cfg), - LinGroup: NewLinGroupClient(cfg), - LinGroupPermission: NewLinGroupPermissionClient(cfg), - LinLog: NewLinLogClient(cfg), - LinPermission: NewLinPermissionClient(cfg), - LinUser: NewLinUserClient(cfg), - LinUserIdentiy: NewLinUserIdentiyClient(cfg), - }, nil -} - -// BeginTx returns a transactional client with specified options. -func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") - } - tx, err := c.driver.(interface { - BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) - }).BeginTx(ctx, opts) - if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = &txDriver{tx: tx, drv: c.driver} - return &Tx{ - config: cfg, - Book: NewBookClient(cfg), - LinFile: NewLinFileClient(cfg), - LinGroup: NewLinGroupClient(cfg), - LinGroupPermission: NewLinGroupPermissionClient(cfg), - LinLog: NewLinLogClient(cfg), - LinPermission: NewLinPermissionClient(cfg), - LinUser: NewLinUserClient(cfg), - LinUserIdentiy: NewLinUserIdentiyClient(cfg), - }, nil -} - -// Debug returns a new debug-client. It's used to get verbose logging on specific operations. -// -// client.Debug(). -// Book. -// Query(). -// Count(ctx) -// -func (c *Client) Debug() *Client { - if c.debug { - return c - } - cfg := c.config - cfg.driver = dialect.Debug(c.driver, c.log) - client := &Client{config: cfg} - client.init() - return client -} - -// Close closes the database connection and prevents new queries from starting. -func (c *Client) Close() error { - return c.driver.Close() -} - -// Use adds the mutation hooks to all the entity clients. -// In order to add hooks to a specific client, call: `client.Node.Use(...)`. -func (c *Client) Use(hooks ...Hook) { - c.Book.Use(hooks...) - c.LinFile.Use(hooks...) - c.LinGroup.Use(hooks...) - c.LinGroupPermission.Use(hooks...) - c.LinLog.Use(hooks...) - c.LinPermission.Use(hooks...) - c.LinUser.Use(hooks...) - c.LinUserIdentiy.Use(hooks...) -} - -// BookClient is a client for the Book schema. -type BookClient struct { - config -} - -// NewBookClient returns a client for the Book from the given config. -func NewBookClient(c config) *BookClient { - return &BookClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `book.Hooks(f(g(h())))`. -func (c *BookClient) Use(hooks ...Hook) { - c.hooks.Book = append(c.hooks.Book, hooks...) -} - -// Create returns a create builder for Book. -func (c *BookClient) Create() *BookCreate { - mutation := newBookMutation(c.config, OpCreate) - return &BookCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Book entities. -func (c *BookClient) CreateBulk(builders ...*BookCreate) *BookCreateBulk { - return &BookCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Book. -func (c *BookClient) Update() *BookUpdate { - mutation := newBookMutation(c.config, OpUpdate) - return &BookUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *BookClient) UpdateOne(b *Book) *BookUpdateOne { - mutation := newBookMutation(c.config, OpUpdateOne, withBook(b)) - return &BookUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *BookClient) UpdateOneID(id int) *BookUpdateOne { - mutation := newBookMutation(c.config, OpUpdateOne, withBookID(id)) - return &BookUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Book. -func (c *BookClient) Delete() *BookDelete { - mutation := newBookMutation(c.config, OpDelete) - return &BookDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *BookClient) DeleteOne(b *Book) *BookDeleteOne { - return c.DeleteOneID(b.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *BookClient) DeleteOneID(id int) *BookDeleteOne { - builder := c.Delete().Where(book.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &BookDeleteOne{builder} -} - -// Query returns a query builder for Book. -func (c *BookClient) Query() *BookQuery { - return &BookQuery{ - config: c.config, - } -} - -// Get returns a Book entity by its id. -func (c *BookClient) Get(ctx context.Context, id int) (*Book, error) { - return c.Query().Where(book.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *BookClient) GetX(ctx context.Context, id int) *Book { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *BookClient) Hooks() []Hook { - return c.hooks.Book -} - -// LinFileClient is a client for the LinFile schema. -type LinFileClient struct { - config -} - -// NewLinFileClient returns a client for the LinFile from the given config. -func NewLinFileClient(c config) *LinFileClient { - return &LinFileClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `linfile.Hooks(f(g(h())))`. -func (c *LinFileClient) Use(hooks ...Hook) { - c.hooks.LinFile = append(c.hooks.LinFile, hooks...) -} - -// Create returns a create builder for LinFile. -func (c *LinFileClient) Create() *LinFileCreate { - mutation := newLinFileMutation(c.config, OpCreate) - return &LinFileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinFile entities. -func (c *LinFileClient) CreateBulk(builders ...*LinFileCreate) *LinFileCreateBulk { - return &LinFileCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinFile. -func (c *LinFileClient) Update() *LinFileUpdate { - mutation := newLinFileMutation(c.config, OpUpdate) - return &LinFileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinFileClient) UpdateOne(lf *LinFile) *LinFileUpdateOne { - mutation := newLinFileMutation(c.config, OpUpdateOne, withLinFile(lf)) - return &LinFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinFileClient) UpdateOneID(id int) *LinFileUpdateOne { - mutation := newLinFileMutation(c.config, OpUpdateOne, withLinFileID(id)) - return &LinFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinFile. -func (c *LinFileClient) Delete() *LinFileDelete { - mutation := newLinFileMutation(c.config, OpDelete) - return &LinFileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinFileClient) DeleteOne(lf *LinFile) *LinFileDeleteOne { - return c.DeleteOneID(lf.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinFileClient) DeleteOneID(id int) *LinFileDeleteOne { - builder := c.Delete().Where(linfile.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinFileDeleteOne{builder} -} - -// Query returns a query builder for LinFile. -func (c *LinFileClient) Query() *LinFileQuery { - return &LinFileQuery{ - config: c.config, - } -} - -// Get returns a LinFile entity by its id. -func (c *LinFileClient) Get(ctx context.Context, id int) (*LinFile, error) { - return c.Query().Where(linfile.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinFileClient) GetX(ctx context.Context, id int) *LinFile { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *LinFileClient) Hooks() []Hook { - return c.hooks.LinFile -} - -// LinGroupClient is a client for the LinGroup schema. -type LinGroupClient struct { - config -} - -// NewLinGroupClient returns a client for the LinGroup from the given config. -func NewLinGroupClient(c config) *LinGroupClient { - return &LinGroupClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `lingroup.Hooks(f(g(h())))`. -func (c *LinGroupClient) Use(hooks ...Hook) { - c.hooks.LinGroup = append(c.hooks.LinGroup, hooks...) -} - -// Create returns a create builder for LinGroup. -func (c *LinGroupClient) Create() *LinGroupCreate { - mutation := newLinGroupMutation(c.config, OpCreate) - return &LinGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinGroup entities. -func (c *LinGroupClient) CreateBulk(builders ...*LinGroupCreate) *LinGroupCreateBulk { - return &LinGroupCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinGroup. -func (c *LinGroupClient) Update() *LinGroupUpdate { - mutation := newLinGroupMutation(c.config, OpUpdate) - return &LinGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinGroupClient) UpdateOne(lg *LinGroup) *LinGroupUpdateOne { - mutation := newLinGroupMutation(c.config, OpUpdateOne, withLinGroup(lg)) - return &LinGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinGroupClient) UpdateOneID(id int) *LinGroupUpdateOne { - mutation := newLinGroupMutation(c.config, OpUpdateOne, withLinGroupID(id)) - return &LinGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinGroup. -func (c *LinGroupClient) Delete() *LinGroupDelete { - mutation := newLinGroupMutation(c.config, OpDelete) - return &LinGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinGroupClient) DeleteOne(lg *LinGroup) *LinGroupDeleteOne { - return c.DeleteOneID(lg.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinGroupClient) DeleteOneID(id int) *LinGroupDeleteOne { - builder := c.Delete().Where(lingroup.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinGroupDeleteOne{builder} -} - -// Query returns a query builder for LinGroup. -func (c *LinGroupClient) Query() *LinGroupQuery { - return &LinGroupQuery{ - config: c.config, - } -} - -// Get returns a LinGroup entity by its id. -func (c *LinGroupClient) Get(ctx context.Context, id int) (*LinGroup, error) { - return c.Query().Where(lingroup.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinGroupClient) GetX(ctx context.Context, id int) *LinGroup { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryLinUser queries the lin_user edge of a LinGroup. -func (c *LinGroupClient) QueryLinUser(lg *LinGroup) *LinUserQuery { - query := &LinUserQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { - id := lg.ID - step := sqlgraph.NewStep( - sqlgraph.From(lingroup.Table, lingroup.FieldID, id), - sqlgraph.To(linuser.Table, linuser.FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, lingroup.LinUserTable, lingroup.LinUserPrimaryKey...), - ) - fromV = sqlgraph.Neighbors(lg.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryLinPermission queries the lin_permission edge of a LinGroup. -func (c *LinGroupClient) QueryLinPermission(lg *LinGroup) *LinPermissionQuery { - query := &LinPermissionQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { - id := lg.ID - step := sqlgraph.NewStep( - sqlgraph.From(lingroup.Table, lingroup.FieldID, id), - sqlgraph.To(linpermission.Table, linpermission.FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, lingroup.LinPermissionTable, lingroup.LinPermissionPrimaryKey...), - ) - fromV = sqlgraph.Neighbors(lg.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *LinGroupClient) Hooks() []Hook { - return c.hooks.LinGroup -} - -// LinGroupPermissionClient is a client for the LinGroupPermission schema. -type LinGroupPermissionClient struct { - config -} - -// NewLinGroupPermissionClient returns a client for the LinGroupPermission from the given config. -func NewLinGroupPermissionClient(c config) *LinGroupPermissionClient { - return &LinGroupPermissionClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `lingrouppermission.Hooks(f(g(h())))`. -func (c *LinGroupPermissionClient) Use(hooks ...Hook) { - c.hooks.LinGroupPermission = append(c.hooks.LinGroupPermission, hooks...) -} - -// Create returns a create builder for LinGroupPermission. -func (c *LinGroupPermissionClient) Create() *LinGroupPermissionCreate { - mutation := newLinGroupPermissionMutation(c.config, OpCreate) - return &LinGroupPermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinGroupPermission entities. -func (c *LinGroupPermissionClient) CreateBulk(builders ...*LinGroupPermissionCreate) *LinGroupPermissionCreateBulk { - return &LinGroupPermissionCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinGroupPermission. -func (c *LinGroupPermissionClient) Update() *LinGroupPermissionUpdate { - mutation := newLinGroupPermissionMutation(c.config, OpUpdate) - return &LinGroupPermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinGroupPermissionClient) UpdateOne(lgp *LinGroupPermission) *LinGroupPermissionUpdateOne { - mutation := newLinGroupPermissionMutation(c.config, OpUpdateOne, withLinGroupPermission(lgp)) - return &LinGroupPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinGroupPermissionClient) UpdateOneID(id int) *LinGroupPermissionUpdateOne { - mutation := newLinGroupPermissionMutation(c.config, OpUpdateOne, withLinGroupPermissionID(id)) - return &LinGroupPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinGroupPermission. -func (c *LinGroupPermissionClient) Delete() *LinGroupPermissionDelete { - mutation := newLinGroupPermissionMutation(c.config, OpDelete) - return &LinGroupPermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinGroupPermissionClient) DeleteOne(lgp *LinGroupPermission) *LinGroupPermissionDeleteOne { - return c.DeleteOneID(lgp.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinGroupPermissionClient) DeleteOneID(id int) *LinGroupPermissionDeleteOne { - builder := c.Delete().Where(lingrouppermission.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinGroupPermissionDeleteOne{builder} -} - -// Query returns a query builder for LinGroupPermission. -func (c *LinGroupPermissionClient) Query() *LinGroupPermissionQuery { - return &LinGroupPermissionQuery{ - config: c.config, - } -} - -// Get returns a LinGroupPermission entity by its id. -func (c *LinGroupPermissionClient) Get(ctx context.Context, id int) (*LinGroupPermission, error) { - return c.Query().Where(lingrouppermission.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinGroupPermissionClient) GetX(ctx context.Context, id int) *LinGroupPermission { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *LinGroupPermissionClient) Hooks() []Hook { - return c.hooks.LinGroupPermission -} - -// LinLogClient is a client for the LinLog schema. -type LinLogClient struct { - config -} - -// NewLinLogClient returns a client for the LinLog from the given config. -func NewLinLogClient(c config) *LinLogClient { - return &LinLogClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `linlog.Hooks(f(g(h())))`. -func (c *LinLogClient) Use(hooks ...Hook) { - c.hooks.LinLog = append(c.hooks.LinLog, hooks...) -} - -// Create returns a create builder for LinLog. -func (c *LinLogClient) Create() *LinLogCreate { - mutation := newLinLogMutation(c.config, OpCreate) - return &LinLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinLog entities. -func (c *LinLogClient) CreateBulk(builders ...*LinLogCreate) *LinLogCreateBulk { - return &LinLogCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinLog. -func (c *LinLogClient) Update() *LinLogUpdate { - mutation := newLinLogMutation(c.config, OpUpdate) - return &LinLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinLogClient) UpdateOne(ll *LinLog) *LinLogUpdateOne { - mutation := newLinLogMutation(c.config, OpUpdateOne, withLinLog(ll)) - return &LinLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinLogClient) UpdateOneID(id int) *LinLogUpdateOne { - mutation := newLinLogMutation(c.config, OpUpdateOne, withLinLogID(id)) - return &LinLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinLog. -func (c *LinLogClient) Delete() *LinLogDelete { - mutation := newLinLogMutation(c.config, OpDelete) - return &LinLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinLogClient) DeleteOne(ll *LinLog) *LinLogDeleteOne { - return c.DeleteOneID(ll.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinLogClient) DeleteOneID(id int) *LinLogDeleteOne { - builder := c.Delete().Where(linlog.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinLogDeleteOne{builder} -} - -// Query returns a query builder for LinLog. -func (c *LinLogClient) Query() *LinLogQuery { - return &LinLogQuery{ - config: c.config, - } -} - -// Get returns a LinLog entity by its id. -func (c *LinLogClient) Get(ctx context.Context, id int) (*LinLog, error) { - return c.Query().Where(linlog.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinLogClient) GetX(ctx context.Context, id int) *LinLog { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *LinLogClient) Hooks() []Hook { - return c.hooks.LinLog -} - -// LinPermissionClient is a client for the LinPermission schema. -type LinPermissionClient struct { - config -} - -// NewLinPermissionClient returns a client for the LinPermission from the given config. -func NewLinPermissionClient(c config) *LinPermissionClient { - return &LinPermissionClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `linpermission.Hooks(f(g(h())))`. -func (c *LinPermissionClient) Use(hooks ...Hook) { - c.hooks.LinPermission = append(c.hooks.LinPermission, hooks...) -} - -// Create returns a create builder for LinPermission. -func (c *LinPermissionClient) Create() *LinPermissionCreate { - mutation := newLinPermissionMutation(c.config, OpCreate) - return &LinPermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinPermission entities. -func (c *LinPermissionClient) CreateBulk(builders ...*LinPermissionCreate) *LinPermissionCreateBulk { - return &LinPermissionCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinPermission. -func (c *LinPermissionClient) Update() *LinPermissionUpdate { - mutation := newLinPermissionMutation(c.config, OpUpdate) - return &LinPermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinPermissionClient) UpdateOne(lp *LinPermission) *LinPermissionUpdateOne { - mutation := newLinPermissionMutation(c.config, OpUpdateOne, withLinPermission(lp)) - return &LinPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinPermissionClient) UpdateOneID(id int) *LinPermissionUpdateOne { - mutation := newLinPermissionMutation(c.config, OpUpdateOne, withLinPermissionID(id)) - return &LinPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinPermission. -func (c *LinPermissionClient) Delete() *LinPermissionDelete { - mutation := newLinPermissionMutation(c.config, OpDelete) - return &LinPermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinPermissionClient) DeleteOne(lp *LinPermission) *LinPermissionDeleteOne { - return c.DeleteOneID(lp.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinPermissionClient) DeleteOneID(id int) *LinPermissionDeleteOne { - builder := c.Delete().Where(linpermission.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinPermissionDeleteOne{builder} -} - -// Query returns a query builder for LinPermission. -func (c *LinPermissionClient) Query() *LinPermissionQuery { - return &LinPermissionQuery{ - config: c.config, - } -} - -// Get returns a LinPermission entity by its id. -func (c *LinPermissionClient) Get(ctx context.Context, id int) (*LinPermission, error) { - return c.Query().Where(linpermission.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinPermissionClient) GetX(ctx context.Context, id int) *LinPermission { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryLinGroup queries the lin_group edge of a LinPermission. -func (c *LinPermissionClient) QueryLinGroup(lp *LinPermission) *LinGroupQuery { - query := &LinGroupQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { - id := lp.ID - step := sqlgraph.NewStep( - sqlgraph.From(linpermission.Table, linpermission.FieldID, id), - sqlgraph.To(lingroup.Table, lingroup.FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, linpermission.LinGroupTable, linpermission.LinGroupPrimaryKey...), - ) - fromV = sqlgraph.Neighbors(lp.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *LinPermissionClient) Hooks() []Hook { - return c.hooks.LinPermission -} - -// LinUserClient is a client for the LinUser schema. -type LinUserClient struct { - config -} - -// NewLinUserClient returns a client for the LinUser from the given config. -func NewLinUserClient(c config) *LinUserClient { - return &LinUserClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `linuser.Hooks(f(g(h())))`. -func (c *LinUserClient) Use(hooks ...Hook) { - c.hooks.LinUser = append(c.hooks.LinUser, hooks...) -} - -// Create returns a create builder for LinUser. -func (c *LinUserClient) Create() *LinUserCreate { - mutation := newLinUserMutation(c.config, OpCreate) - return &LinUserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinUser entities. -func (c *LinUserClient) CreateBulk(builders ...*LinUserCreate) *LinUserCreateBulk { - return &LinUserCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinUser. -func (c *LinUserClient) Update() *LinUserUpdate { - mutation := newLinUserMutation(c.config, OpUpdate) - return &LinUserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinUserClient) UpdateOne(lu *LinUser) *LinUserUpdateOne { - mutation := newLinUserMutation(c.config, OpUpdateOne, withLinUser(lu)) - return &LinUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinUserClient) UpdateOneID(id int) *LinUserUpdateOne { - mutation := newLinUserMutation(c.config, OpUpdateOne, withLinUserID(id)) - return &LinUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinUser. -func (c *LinUserClient) Delete() *LinUserDelete { - mutation := newLinUserMutation(c.config, OpDelete) - return &LinUserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinUserClient) DeleteOne(lu *LinUser) *LinUserDeleteOne { - return c.DeleteOneID(lu.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinUserClient) DeleteOneID(id int) *LinUserDeleteOne { - builder := c.Delete().Where(linuser.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinUserDeleteOne{builder} -} - -// Query returns a query builder for LinUser. -func (c *LinUserClient) Query() *LinUserQuery { - return &LinUserQuery{ - config: c.config, - } -} - -// Get returns a LinUser entity by its id. -func (c *LinUserClient) Get(ctx context.Context, id int) (*LinUser, error) { - return c.Query().Where(linuser.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinUserClient) GetX(ctx context.Context, id int) *LinUser { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryLinUserIdentiy queries the lin_user_identiy edge of a LinUser. -func (c *LinUserClient) QueryLinUserIdentiy(lu *LinUser) *LinUserIdentiyQuery { - query := &LinUserIdentiyQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { - id := lu.ID - step := sqlgraph.NewStep( - sqlgraph.From(linuser.Table, linuser.FieldID, id), - sqlgraph.To(linuseridentiy.Table, linuseridentiy.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, linuser.LinUserIdentiyTable, linuser.LinUserIdentiyColumn), - ) - fromV = sqlgraph.Neighbors(lu.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryLinGroup queries the lin_group edge of a LinUser. -func (c *LinUserClient) QueryLinGroup(lu *LinUser) *LinGroupQuery { - query := &LinGroupQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { - id := lu.ID - step := sqlgraph.NewStep( - sqlgraph.From(linuser.Table, linuser.FieldID, id), - sqlgraph.To(lingroup.Table, lingroup.FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, linuser.LinGroupTable, linuser.LinGroupPrimaryKey...), - ) - fromV = sqlgraph.Neighbors(lu.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *LinUserClient) Hooks() []Hook { - return c.hooks.LinUser -} - -// LinUserIdentiyClient is a client for the LinUserIdentiy schema. -type LinUserIdentiyClient struct { - config -} - -// NewLinUserIdentiyClient returns a client for the LinUserIdentiy from the given config. -func NewLinUserIdentiyClient(c config) *LinUserIdentiyClient { - return &LinUserIdentiyClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `linuseridentiy.Hooks(f(g(h())))`. -func (c *LinUserIdentiyClient) Use(hooks ...Hook) { - c.hooks.LinUserIdentiy = append(c.hooks.LinUserIdentiy, hooks...) -} - -// Create returns a create builder for LinUserIdentiy. -func (c *LinUserIdentiyClient) Create() *LinUserIdentiyCreate { - mutation := newLinUserIdentiyMutation(c.config, OpCreate) - return &LinUserIdentiyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of LinUserIdentiy entities. -func (c *LinUserIdentiyClient) CreateBulk(builders ...*LinUserIdentiyCreate) *LinUserIdentiyCreateBulk { - return &LinUserIdentiyCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for LinUserIdentiy. -func (c *LinUserIdentiyClient) Update() *LinUserIdentiyUpdate { - mutation := newLinUserIdentiyMutation(c.config, OpUpdate) - return &LinUserIdentiyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *LinUserIdentiyClient) UpdateOne(lui *LinUserIdentiy) *LinUserIdentiyUpdateOne { - mutation := newLinUserIdentiyMutation(c.config, OpUpdateOne, withLinUserIdentiy(lui)) - return &LinUserIdentiyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *LinUserIdentiyClient) UpdateOneID(id int) *LinUserIdentiyUpdateOne { - mutation := newLinUserIdentiyMutation(c.config, OpUpdateOne, withLinUserIdentiyID(id)) - return &LinUserIdentiyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for LinUserIdentiy. -func (c *LinUserIdentiyClient) Delete() *LinUserIdentiyDelete { - mutation := newLinUserIdentiyMutation(c.config, OpDelete) - return &LinUserIdentiyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a delete builder for the given entity. -func (c *LinUserIdentiyClient) DeleteOne(lui *LinUserIdentiy) *LinUserIdentiyDeleteOne { - return c.DeleteOneID(lui.ID) -} - -// DeleteOneID returns a delete builder for the given id. -func (c *LinUserIdentiyClient) DeleteOneID(id int) *LinUserIdentiyDeleteOne { - builder := c.Delete().Where(linuseridentiy.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &LinUserIdentiyDeleteOne{builder} -} - -// Query returns a query builder for LinUserIdentiy. -func (c *LinUserIdentiyClient) Query() *LinUserIdentiyQuery { - return &LinUserIdentiyQuery{ - config: c.config, - } -} - -// Get returns a LinUserIdentiy entity by its id. -func (c *LinUserIdentiyClient) Get(ctx context.Context, id int) (*LinUserIdentiy, error) { - return c.Query().Where(linuseridentiy.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *LinUserIdentiyClient) GetX(ctx context.Context, id int) *LinUserIdentiy { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *LinUserIdentiyClient) Hooks() []Hook { - return c.hooks.LinUserIdentiy -} diff --git a/internal/data/model/config.go b/internal/data/model/config.go deleted file mode 100644 index b0134f3..0000000 --- a/internal/data/model/config.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "entgo.io/ent" - "entgo.io/ent/dialect" -) - -// Option function to configure the client. -type Option func(*config) - -// Config is the configuration for the client and its builder. -type config struct { - // driver used for executing database requests. - driver dialect.Driver - // debug enable a debug logging. - debug bool - // log used for logging on debug mode. - log func(...interface{}) - // hooks to execute on mutations. - hooks *hooks -} - -// hooks per client, for fast access. -type hooks struct { - Book []ent.Hook - LinFile []ent.Hook - LinGroup []ent.Hook - LinGroupPermission []ent.Hook - LinLog []ent.Hook - LinPermission []ent.Hook - LinUser []ent.Hook - LinUserIdentiy []ent.Hook -} - -// Options applies the options on the config object. -func (c *config) options(opts ...Option) { - for _, opt := range opts { - opt(c) - } - if c.debug { - c.driver = dialect.Debug(c.driver, c.log) - } -} - -// Debug enables debug logging on the ent.Driver. -func Debug() Option { - return func(c *config) { - c.debug = true - } -} - -// Log sets the logging function for debug mode. -func Log(fn func(...interface{})) Option { - return func(c *config) { - c.log = fn - } -} - -// Driver configures the client driver. -func Driver(driver dialect.Driver) Option { - return func(c *config) { - c.driver = driver - } -} diff --git a/internal/data/model/context.go b/internal/data/model/context.go deleted file mode 100644 index 37c8e62..0000000 --- a/internal/data/model/context.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" -) - -type clientCtxKey struct{} - -// FromContext returns a Client stored inside a context, or nil if there isn't one. -func FromContext(ctx context.Context) *Client { - c, _ := ctx.Value(clientCtxKey{}).(*Client) - return c -} - -// NewContext returns a new context with the given Client attached. -func NewContext(parent context.Context, c *Client) context.Context { - return context.WithValue(parent, clientCtxKey{}, c) -} - -type txCtxKey struct{} - -// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. -func TxFromContext(ctx context.Context) *Tx { - tx, _ := ctx.Value(txCtxKey{}).(*Tx) - return tx -} - -// NewTxContext returns a new context with the given Tx attached. -func NewTxContext(parent context.Context, tx *Tx) context.Context { - return context.WithValue(parent, txCtxKey{}, tx) -} diff --git a/internal/data/model/ent.go b/internal/data/model/ent.go deleted file mode 100644 index 0706d26..0000000 --- a/internal/data/model/ent.go +++ /dev/null @@ -1,273 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "errors" - "fmt" - "lin-cms-go/internal/data/model/book" - "lin-cms-go/internal/data/model/linfile" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/lingrouppermission" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/linuseridentiy" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" -) - -// ent aliases to avoid import conflicts in user's code. -type ( - Op = ent.Op - Hook = ent.Hook - Value = ent.Value - Query = ent.Query - Policy = ent.Policy - Mutator = ent.Mutator - Mutation = ent.Mutation - MutateFunc = ent.MutateFunc -) - -// OrderFunc applies an ordering on the sql selector. -type OrderFunc func(*sql.Selector) - -// columnChecker returns a function indicates if the column exists in the given column. -func columnChecker(table string) func(string) error { - checks := map[string]func(string) bool{ - book.Table: book.ValidColumn, - linfile.Table: linfile.ValidColumn, - lingroup.Table: lingroup.ValidColumn, - lingrouppermission.Table: lingrouppermission.ValidColumn, - linlog.Table: linlog.ValidColumn, - linpermission.Table: linpermission.ValidColumn, - linuser.Table: linuser.ValidColumn, - linuseridentiy.Table: linuseridentiy.ValidColumn, - } - check, ok := checks[table] - if !ok { - return func(string) error { - return fmt.Errorf("unknown table %q", table) - } - } - return func(column string) error { - if !check(column) { - return fmt.Errorf("unknown column %q for table %q", column, table) - } - return nil - } -} - -// Asc applies the given fields in ASC order. -func Asc(fields ...string) OrderFunc { - return func(s *sql.Selector) { - check := columnChecker(s.TableName()) - for _, f := range fields { - if err := check(f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("model: %w", err)}) - } - s.OrderBy(sql.Asc(s.C(f))) - } - } -} - -// Desc applies the given fields in DESC order. -func Desc(fields ...string) OrderFunc { - return func(s *sql.Selector) { - check := columnChecker(s.TableName()) - for _, f := range fields { - if err := check(f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("model: %w", err)}) - } - s.OrderBy(sql.Desc(s.C(f))) - } - } -} - -// AggregateFunc applies an aggregation step on the group-by traversal/selector. -type AggregateFunc func(*sql.Selector) string - -// As is a pseudo aggregation function for renaming another other functions with custom names. For example: -// -// GroupBy(field1, field2). -// Aggregate(model.As(model.Sum(field1), "sum_field1"), (model.As(model.Sum(field2), "sum_field2")). -// Scan(ctx, &v) -// -func As(fn AggregateFunc, end string) AggregateFunc { - return func(s *sql.Selector) string { - return sql.As(fn(s), end) - } -} - -// Count applies the "count" aggregation function on each group. -func Count() AggregateFunc { - return func(s *sql.Selector) string { - return sql.Count("*") - } -} - -// Max applies the "max" aggregation function on the given field of each group. -func Max(field string) AggregateFunc { - return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) - return "" - } - return sql.Max(s.C(field)) - } -} - -// Mean applies the "mean" aggregation function on the given field of each group. -func Mean(field string) AggregateFunc { - return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) - return "" - } - return sql.Avg(s.C(field)) - } -} - -// Min applies the "min" aggregation function on the given field of each group. -func Min(field string) AggregateFunc { - return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) - return "" - } - return sql.Min(s.C(field)) - } -} - -// Sum applies the "sum" aggregation function on the given field of each group. -func Sum(field string) AggregateFunc { - return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) - return "" - } - return sql.Sum(s.C(field)) - } -} - -// ValidationError returns when validating a field fails. -type ValidationError struct { - Name string // Field or edge name. - err error -} - -// Error implements the error interface. -func (e *ValidationError) Error() string { - return e.err.Error() -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ValidationError) Unwrap() error { - return e.err -} - -// IsValidationError returns a boolean indicating whether the error is a validation error. -func IsValidationError(err error) bool { - if err == nil { - return false - } - var e *ValidationError - return errors.As(err, &e) -} - -// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. -type NotFoundError struct { - label string -} - -// Error implements the error interface. -func (e *NotFoundError) Error() string { - return "model: " + e.label + " not found" -} - -// IsNotFound returns a boolean indicating whether the error is a not found error. -func IsNotFound(err error) bool { - if err == nil { - return false - } - var e *NotFoundError - return errors.As(err, &e) -} - -// MaskNotFound masks not found error. -func MaskNotFound(err error) error { - if IsNotFound(err) { - return nil - } - return err -} - -// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. -type NotSingularError struct { - label string -} - -// Error implements the error interface. -func (e *NotSingularError) Error() string { - return "model: " + e.label + " not singular" -} - -// IsNotSingular returns a boolean indicating whether the error is a not singular error. -func IsNotSingular(err error) bool { - if err == nil { - return false - } - var e *NotSingularError - return errors.As(err, &e) -} - -// NotLoadedError returns when trying to get a node that was not loaded by the query. -type NotLoadedError struct { - edge string -} - -// Error implements the error interface. -func (e *NotLoadedError) Error() string { - return "model: " + e.edge + " edge was not loaded" -} - -// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. -func IsNotLoaded(err error) bool { - if err == nil { - return false - } - var e *NotLoadedError - return errors.As(err, &e) -} - -// ConstraintError returns when trying to create/update one or more entities and -// one or more of their constraints failed. For example, violation of edge or -// field uniqueness. -type ConstraintError struct { - msg string - wrap error -} - -// Error implements the error interface. -func (e ConstraintError) Error() string { - return "model: constraint failed: " + e.msg -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ConstraintError) Unwrap() error { - return e.wrap -} - -// IsConstraintError returns a boolean indicating whether the error is a constraint failure. -func IsConstraintError(err error) bool { - if err == nil { - return false - } - var e *ConstraintError - return errors.As(err, &e) -} diff --git a/internal/data/model/enttest/enttest.go b/internal/data/model/enttest/enttest.go deleted file mode 100644 index ea44042..0000000 --- a/internal/data/model/enttest/enttest.go +++ /dev/null @@ -1,77 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package enttest - -import ( - "context" - "lin-cms-go/internal/data/model" - // required by schema hooks. - _ "lin-cms-go/internal/data/model/runtime" - - "entgo.io/ent/dialect/sql/schema" -) - -type ( - // TestingT is the interface that is shared between - // testing.T and testing.B and used by enttest. - TestingT interface { - FailNow() - Error(...interface{}) - } - - // Option configures client creation. - Option func(*options) - - options struct { - opts []model.Option - migrateOpts []schema.MigrateOption - } -) - -// WithOptions forwards options to client creation. -func WithOptions(opts ...model.Option) Option { - return func(o *options) { - o.opts = append(o.opts, opts...) - } -} - -// WithMigrateOptions forwards options to auto migration. -func WithMigrateOptions(opts ...schema.MigrateOption) Option { - return func(o *options) { - o.migrateOpts = append(o.migrateOpts, opts...) - } -} - -func newOptions(opts []Option) *options { - o := &options{} - for _, opt := range opts { - opt(o) - } - return o -} - -// Open calls model.Open and auto-run migration. -func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *model.Client { - o := newOptions(opts) - c, err := model.Open(driverName, dataSourceName, o.opts...) - if err != nil { - t.Error(err) - t.FailNow() - } - if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } - return c -} - -// NewClient calls model.NewClient and auto-run migration. -func NewClient(t TestingT, opts ...Option) *model.Client { - o := newOptions(opts) - c := model.NewClient(o.opts...) - if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } - return c -} diff --git a/internal/data/model/hook/hook.go b/internal/data/model/hook/hook.go deleted file mode 100644 index 518c5f2..0000000 --- a/internal/data/model/hook/hook.go +++ /dev/null @@ -1,294 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package hook - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model" -) - -// The BookFunc type is an adapter to allow the use of ordinary -// function as Book mutator. -type BookFunc func(context.Context, *model.BookMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f BookFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.BookMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.BookMutation", m) - } - return f(ctx, mv) -} - -// The LinFileFunc type is an adapter to allow the use of ordinary -// function as LinFile mutator. -type LinFileFunc func(context.Context, *model.LinFileMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinFileFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinFileMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinFileMutation", m) - } - return f(ctx, mv) -} - -// The LinGroupFunc type is an adapter to allow the use of ordinary -// function as LinGroup mutator. -type LinGroupFunc func(context.Context, *model.LinGroupMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinGroupFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinGroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinGroupMutation", m) - } - return f(ctx, mv) -} - -// The LinGroupPermissionFunc type is an adapter to allow the use of ordinary -// function as LinGroupPermission mutator. -type LinGroupPermissionFunc func(context.Context, *model.LinGroupPermissionMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinGroupPermissionFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinGroupPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinGroupPermissionMutation", m) - } - return f(ctx, mv) -} - -// The LinLogFunc type is an adapter to allow the use of ordinary -// function as LinLog mutator. -type LinLogFunc func(context.Context, *model.LinLogMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinLogFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinLogMutation", m) - } - return f(ctx, mv) -} - -// The LinPermissionFunc type is an adapter to allow the use of ordinary -// function as LinPermission mutator. -type LinPermissionFunc func(context.Context, *model.LinPermissionMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinPermissionFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinPermissionMutation", m) - } - return f(ctx, mv) -} - -// The LinUserFunc type is an adapter to allow the use of ordinary -// function as LinUser mutator. -type LinUserFunc func(context.Context, *model.LinUserMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinUserFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinUserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinUserMutation", m) - } - return f(ctx, mv) -} - -// The LinUserIdentiyFunc type is an adapter to allow the use of ordinary -// function as LinUserIdentiy mutator. -type LinUserIdentiyFunc func(context.Context, *model.LinUserIdentiyMutation) (model.Value, error) - -// Mutate calls f(ctx, m). -func (f LinUserIdentiyFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { - mv, ok := m.(*model.LinUserIdentiyMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinUserIdentiyMutation", m) - } - return f(ctx, mv) -} - -// Condition is a hook condition function. -type Condition func(context.Context, model.Mutation) bool - -// And groups conditions with the AND operator. -func And(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m model.Mutation) bool { - if !first(ctx, m) || !second(ctx, m) { - return false - } - for _, cond := range rest { - if !cond(ctx, m) { - return false - } - } - return true - } -} - -// Or groups conditions with the OR operator. -func Or(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m model.Mutation) bool { - if first(ctx, m) || second(ctx, m) { - return true - } - for _, cond := range rest { - if cond(ctx, m) { - return true - } - } - return false - } -} - -// Not negates a given condition. -func Not(cond Condition) Condition { - return func(ctx context.Context, m model.Mutation) bool { - return !cond(ctx, m) - } -} - -// HasOp is a condition testing mutation operation. -func HasOp(op model.Op) Condition { - return func(_ context.Context, m model.Mutation) bool { - return m.Op().Is(op) - } -} - -// HasAddedFields is a condition validating `.AddedField` on fields. -func HasAddedFields(field string, fields ...string) Condition { - return func(_ context.Context, m model.Mutation) bool { - if _, exists := m.AddedField(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.AddedField(field); !exists { - return false - } - } - return true - } -} - -// HasClearedFields is a condition validating `.FieldCleared` on fields. -func HasClearedFields(field string, fields ...string) Condition { - return func(_ context.Context, m model.Mutation) bool { - if exists := m.FieldCleared(field); !exists { - return false - } - for _, field := range fields { - if exists := m.FieldCleared(field); !exists { - return false - } - } - return true - } -} - -// HasFields is a condition validating `.Field` on fields. -func HasFields(field string, fields ...string) Condition { - return func(_ context.Context, m model.Mutation) bool { - if _, exists := m.Field(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.Field(field); !exists { - return false - } - } - return true - } -} - -// If executes the given hook under condition. -// -// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) -// -func If(hk model.Hook, cond Condition) model.Hook { - return func(next model.Mutator) model.Mutator { - return model.MutateFunc(func(ctx context.Context, m model.Mutation) (model.Value, error) { - if cond(ctx, m) { - return hk(next).Mutate(ctx, m) - } - return next.Mutate(ctx, m) - }) - } -} - -// On executes the given hook only for the given operation. -// -// hook.On(Log, model.Delete|model.Create) -// -func On(hk model.Hook, op model.Op) model.Hook { - return If(hk, HasOp(op)) -} - -// Unless skips the given hook only for the given operation. -// -// hook.Unless(Log, model.Update|model.UpdateOne) -// -func Unless(hk model.Hook, op model.Op) model.Hook { - return If(hk, Not(HasOp(op))) -} - -// FixedError is a hook returning a fixed error. -func FixedError(err error) model.Hook { - return func(model.Mutator) model.Mutator { - return model.MutateFunc(func(context.Context, model.Mutation) (model.Value, error) { - return nil, err - }) - } -} - -// Reject returns a hook that rejects all operations that match op. -// -// func (T) Hooks() []model.Hook { -// return []model.Hook{ -// Reject(model.Delete|model.Update), -// } -// } -// -func Reject(op model.Op) model.Hook { - hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) - return On(hk, op) -} - -// Chain acts as a list of hooks and is effectively immutable. -// Once created, it will always hold the same set of hooks in the same order. -type Chain struct { - hooks []model.Hook -} - -// NewChain creates a new chain of hooks. -func NewChain(hooks ...model.Hook) Chain { - return Chain{append([]model.Hook(nil), hooks...)} -} - -// Hook chains the list of hooks and returns the final hook. -func (c Chain) Hook() model.Hook { - return func(mutator model.Mutator) model.Mutator { - for i := len(c.hooks) - 1; i >= 0; i-- { - mutator = c.hooks[i](mutator) - } - return mutator - } -} - -// Append extends a chain, adding the specified hook -// as the last ones in the mutation flow. -func (c Chain) Append(hooks ...model.Hook) Chain { - newHooks := make([]model.Hook, 0, len(c.hooks)+len(hooks)) - newHooks = append(newHooks, c.hooks...) - newHooks = append(newHooks, hooks...) - return Chain{newHooks} -} - -// Extend extends a chain, adding the specified chain -// as the last ones in the mutation flow. -func (c Chain) Extend(chain Chain) Chain { - return c.Append(chain.hooks...) -} diff --git a/internal/data/model/linfile.go b/internal/data/model/linfile.go deleted file mode 100644 index 56803ca..0000000 --- a/internal/data/model/linfile.go +++ /dev/null @@ -1,151 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/linfile" - "strings" - - "entgo.io/ent/dialect/sql" -) - -// LinFile is the model entity for the LinFile schema. -type LinFile struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // Path holds the value of the "path" field. - Path string `json:"path,omitempty"` - // Type holds the value of the "type" field. - // 1 LOCAL 本地,2 REMOTE 远程 - Type int8 `json:"type,omitempty"` - // Name holds the value of the "name" field. - Name string `json:"name,omitempty"` - // Extension holds the value of the "extension" field. - Extension string `json:"extension,omitempty"` - // Size holds the value of the "size" field. - Size int `json:"size,omitempty"` - // Md5 holds the value of the "md5" field. - // md5值,防止上传重复文件 - Md5 string `json:"md5,omitempty"` -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinFile) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case linfile.FieldID, linfile.FieldType, linfile.FieldSize: - values[i] = new(sql.NullInt64) - case linfile.FieldPath, linfile.FieldName, linfile.FieldExtension, linfile.FieldMd5: - values[i] = new(sql.NullString) - default: - return nil, fmt.Errorf("unexpected column %q for type LinFile", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinFile fields. -func (lf *LinFile) assignValues(columns []string, values []interface{}) 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 linfile.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - lf.ID = int(value.Int64) - case linfile.FieldPath: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field path", values[i]) - } else if value.Valid { - lf.Path = value.String - } - case linfile.FieldType: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field type", values[i]) - } else if value.Valid { - lf.Type = int8(value.Int64) - } - case linfile.FieldName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[i]) - } else if value.Valid { - lf.Name = value.String - } - case linfile.FieldExtension: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field extension", values[i]) - } else if value.Valid { - lf.Extension = value.String - } - case linfile.FieldSize: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field size", values[i]) - } else if value.Valid { - lf.Size = int(value.Int64) - } - case linfile.FieldMd5: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field md5", values[i]) - } else if value.Valid { - lf.Md5 = value.String - } - } - } - return nil -} - -// Update returns a builder for updating this LinFile. -// Note that you need to call LinFile.Unwrap() before calling this method if this LinFile -// was returned from a transaction, and the transaction was committed or rolled back. -func (lf *LinFile) Update() *LinFileUpdateOne { - return (&LinFileClient{config: lf.config}).UpdateOne(lf) -} - -// Unwrap unwraps the LinFile 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 (lf *LinFile) Unwrap() *LinFile { - tx, ok := lf.config.driver.(*txDriver) - if !ok { - panic("model: LinFile is not a transactional entity") - } - lf.config.driver = tx.drv - return lf -} - -// String implements the fmt.Stringer. -func (lf *LinFile) String() string { - var builder strings.Builder - builder.WriteString("LinFile(") - builder.WriteString(fmt.Sprintf("id=%v", lf.ID)) - builder.WriteString(", path=") - builder.WriteString(lf.Path) - builder.WriteString(", type=") - builder.WriteString(fmt.Sprintf("%v", lf.Type)) - builder.WriteString(", name=") - builder.WriteString(lf.Name) - builder.WriteString(", extension=") - builder.WriteString(lf.Extension) - builder.WriteString(", size=") - builder.WriteString(fmt.Sprintf("%v", lf.Size)) - builder.WriteString(", md5=") - builder.WriteString(lf.Md5) - builder.WriteByte(')') - return builder.String() -} - -// LinFiles is a parsable slice of LinFile. -type LinFiles []*LinFile - -func (lf LinFiles) config(cfg config) { - for _i := range lf { - lf[_i].config = cfg - } -} diff --git a/internal/data/model/linfile/linfile.go b/internal/data/model/linfile/linfile.go deleted file mode 100644 index a5da84e..0000000 --- a/internal/data/model/linfile/linfile.go +++ /dev/null @@ -1,45 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linfile - -const ( - // Label holds the string label denoting the linfile type in the database. - Label = "lin_file" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldPath holds the string denoting the path field in the database. - FieldPath = "path" - // FieldType holds the string denoting the type field in the database. - FieldType = "type" - // FieldName holds the string denoting the name field in the database. - FieldName = "name" - // FieldExtension holds the string denoting the extension field in the database. - FieldExtension = "extension" - // FieldSize holds the string denoting the size field in the database. - FieldSize = "size" - // FieldMd5 holds the string denoting the md5 field in the database. - FieldMd5 = "md5" - // Table holds the table name of the linfile in the database. - Table = "lin_file" -) - -// Columns holds all SQL columns for linfile fields. -var Columns = []string{ - FieldID, - FieldPath, - FieldType, - FieldName, - FieldExtension, - FieldSize, - FieldMd5, -} - -// 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 -} diff --git a/internal/data/model/linfile/where.go b/internal/data/model/linfile/where.go deleted file mode 100644 index 7d1c3b1..0000000 --- a/internal/data/model/linfile/where.go +++ /dev/null @@ -1,762 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linfile - -import ( - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// Path applies equality check predicate on the "path" field. It's identical to PathEQ. -func Path(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPath), v)) - }) -} - -// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. -func Type(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldType), v)) - }) -} - -// Name applies equality check predicate on the "name" field. It's identical to NameEQ. -func Name(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) -} - -// Extension applies equality check predicate on the "extension" field. It's identical to ExtensionEQ. -func Extension(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldExtension), v)) - }) -} - -// Size applies equality check predicate on the "size" field. It's identical to SizeEQ. -func Size(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldSize), v)) - }) -} - -// Md5 applies equality check predicate on the "md5" field. It's identical to Md5EQ. -func Md5(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMd5), v)) - }) -} - -// PathEQ applies the EQ predicate on the "path" field. -func PathEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPath), v)) - }) -} - -// PathNEQ applies the NEQ predicate on the "path" field. -func PathNEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldPath), v)) - }) -} - -// PathIn applies the In predicate on the "path" field. -func PathIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldPath), v...)) - }) -} - -// PathNotIn applies the NotIn predicate on the "path" field. -func PathNotIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldPath), v...)) - }) -} - -// PathGT applies the GT predicate on the "path" field. -func PathGT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldPath), v)) - }) -} - -// PathGTE applies the GTE predicate on the "path" field. -func PathGTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldPath), v)) - }) -} - -// PathLT applies the LT predicate on the "path" field. -func PathLT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldPath), v)) - }) -} - -// PathLTE applies the LTE predicate on the "path" field. -func PathLTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldPath), v)) - }) -} - -// PathContains applies the Contains predicate on the "path" field. -func PathContains(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldPath), v)) - }) -} - -// PathHasPrefix applies the HasPrefix predicate on the "path" field. -func PathHasPrefix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldPath), v)) - }) -} - -// PathHasSuffix applies the HasSuffix predicate on the "path" field. -func PathHasSuffix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldPath), v)) - }) -} - -// PathEqualFold applies the EqualFold predicate on the "path" field. -func PathEqualFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldPath), v)) - }) -} - -// PathContainsFold applies the ContainsFold predicate on the "path" field. -func PathContainsFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldPath), v)) - }) -} - -// TypeEQ applies the EQ predicate on the "type" field. -func TypeEQ(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldType), v)) - }) -} - -// TypeNEQ applies the NEQ predicate on the "type" field. -func TypeNEQ(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldType), v)) - }) -} - -// TypeIn applies the In predicate on the "type" field. -func TypeIn(vs ...int8) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldType), v...)) - }) -} - -// TypeNotIn applies the NotIn predicate on the "type" field. -func TypeNotIn(vs ...int8) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldType), v...)) - }) -} - -// TypeGT applies the GT predicate on the "type" field. -func TypeGT(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldType), v)) - }) -} - -// TypeGTE applies the GTE predicate on the "type" field. -func TypeGTE(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldType), v)) - }) -} - -// TypeLT applies the LT predicate on the "type" field. -func TypeLT(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldType), v)) - }) -} - -// TypeLTE applies the LTE predicate on the "type" field. -func TypeLTE(v int8) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldType), v)) - }) -} - -// NameEQ applies the EQ predicate on the "name" field. -func NameEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) -} - -// NameNEQ applies the NEQ predicate on the "name" field. -func NameNEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldName), v)) - }) -} - -// NameIn applies the In predicate on the "name" field. -func NameIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldName), v...)) - }) -} - -// NameNotIn applies the NotIn predicate on the "name" field. -func NameNotIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldName), v...)) - }) -} - -// NameGT applies the GT predicate on the "name" field. -func NameGT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldName), v)) - }) -} - -// NameGTE applies the GTE predicate on the "name" field. -func NameGTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldName), v)) - }) -} - -// NameLT applies the LT predicate on the "name" field. -func NameLT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldName), v)) - }) -} - -// NameLTE applies the LTE predicate on the "name" field. -func NameLTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldName), v)) - }) -} - -// NameContains applies the Contains predicate on the "name" field. -func NameContains(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldName), v)) - }) -} - -// NameHasPrefix applies the HasPrefix predicate on the "name" field. -func NameHasPrefix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldName), v)) - }) -} - -// NameHasSuffix applies the HasSuffix predicate on the "name" field. -func NameHasSuffix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldName), v)) - }) -} - -// NameEqualFold applies the EqualFold predicate on the "name" field. -func NameEqualFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldName), v)) - }) -} - -// NameContainsFold applies the ContainsFold predicate on the "name" field. -func NameContainsFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldName), v)) - }) -} - -// ExtensionEQ applies the EQ predicate on the "extension" field. -func ExtensionEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldExtension), v)) - }) -} - -// ExtensionNEQ applies the NEQ predicate on the "extension" field. -func ExtensionNEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldExtension), v)) - }) -} - -// ExtensionIn applies the In predicate on the "extension" field. -func ExtensionIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldExtension), v...)) - }) -} - -// ExtensionNotIn applies the NotIn predicate on the "extension" field. -func ExtensionNotIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldExtension), v...)) - }) -} - -// ExtensionGT applies the GT predicate on the "extension" field. -func ExtensionGT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldExtension), v)) - }) -} - -// ExtensionGTE applies the GTE predicate on the "extension" field. -func ExtensionGTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldExtension), v)) - }) -} - -// ExtensionLT applies the LT predicate on the "extension" field. -func ExtensionLT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldExtension), v)) - }) -} - -// ExtensionLTE applies the LTE predicate on the "extension" field. -func ExtensionLTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldExtension), v)) - }) -} - -// ExtensionContains applies the Contains predicate on the "extension" field. -func ExtensionContains(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldExtension), v)) - }) -} - -// ExtensionHasPrefix applies the HasPrefix predicate on the "extension" field. -func ExtensionHasPrefix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldExtension), v)) - }) -} - -// ExtensionHasSuffix applies the HasSuffix predicate on the "extension" field. -func ExtensionHasSuffix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldExtension), v)) - }) -} - -// ExtensionEqualFold applies the EqualFold predicate on the "extension" field. -func ExtensionEqualFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldExtension), v)) - }) -} - -// ExtensionContainsFold applies the ContainsFold predicate on the "extension" field. -func ExtensionContainsFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldExtension), v)) - }) -} - -// SizeEQ applies the EQ predicate on the "size" field. -func SizeEQ(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldSize), v)) - }) -} - -// SizeNEQ applies the NEQ predicate on the "size" field. -func SizeNEQ(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldSize), v)) - }) -} - -// SizeIn applies the In predicate on the "size" field. -func SizeIn(vs ...int) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldSize), v...)) - }) -} - -// SizeNotIn applies the NotIn predicate on the "size" field. -func SizeNotIn(vs ...int) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldSize), v...)) - }) -} - -// SizeGT applies the GT predicate on the "size" field. -func SizeGT(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldSize), v)) - }) -} - -// SizeGTE applies the GTE predicate on the "size" field. -func SizeGTE(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldSize), v)) - }) -} - -// SizeLT applies the LT predicate on the "size" field. -func SizeLT(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldSize), v)) - }) -} - -// SizeLTE applies the LTE predicate on the "size" field. -func SizeLTE(v int) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldSize), v)) - }) -} - -// Md5EQ applies the EQ predicate on the "md5" field. -func Md5EQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMd5), v)) - }) -} - -// Md5NEQ applies the NEQ predicate on the "md5" field. -func Md5NEQ(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMd5), v)) - }) -} - -// Md5In applies the In predicate on the "md5" field. -func Md5In(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMd5), v...)) - }) -} - -// Md5NotIn applies the NotIn predicate on the "md5" field. -func Md5NotIn(vs ...string) predicate.LinFile { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinFile(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMd5), v...)) - }) -} - -// Md5GT applies the GT predicate on the "md5" field. -func Md5GT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMd5), v)) - }) -} - -// Md5GTE applies the GTE predicate on the "md5" field. -func Md5GTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMd5), v)) - }) -} - -// Md5LT applies the LT predicate on the "md5" field. -func Md5LT(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMd5), v)) - }) -} - -// Md5LTE applies the LTE predicate on the "md5" field. -func Md5LTE(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMd5), v)) - }) -} - -// Md5Contains applies the Contains predicate on the "md5" field. -func Md5Contains(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldMd5), v)) - }) -} - -// Md5HasPrefix applies the HasPrefix predicate on the "md5" field. -func Md5HasPrefix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldMd5), v)) - }) -} - -// Md5HasSuffix applies the HasSuffix predicate on the "md5" field. -func Md5HasSuffix(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldMd5), v)) - }) -} - -// Md5EqualFold applies the EqualFold predicate on the "md5" field. -func Md5EqualFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldMd5), v)) - }) -} - -// Md5ContainsFold applies the ContainsFold predicate on the "md5" field. -func Md5ContainsFold(v string) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldMd5), v)) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.LinFile) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinFile) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinFile) predicate.LinFile { - return predicate.LinFile(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/linfile_create.go b/internal/data/model/linfile_create.go deleted file mode 100644 index 617d719..0000000 --- a/internal/data/model/linfile_create.go +++ /dev/null @@ -1,305 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/linfile" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinFileCreate is the builder for creating a LinFile entity. -type LinFileCreate struct { - config - mutation *LinFileMutation - hooks []Hook -} - -// SetPath sets the "path" field. -func (lfc *LinFileCreate) SetPath(s string) *LinFileCreate { - lfc.mutation.SetPath(s) - return lfc -} - -// SetType sets the "type" field. -func (lfc *LinFileCreate) SetType(i int8) *LinFileCreate { - lfc.mutation.SetType(i) - return lfc -} - -// SetName sets the "name" field. -func (lfc *LinFileCreate) SetName(s string) *LinFileCreate { - lfc.mutation.SetName(s) - return lfc -} - -// SetExtension sets the "extension" field. -func (lfc *LinFileCreate) SetExtension(s string) *LinFileCreate { - lfc.mutation.SetExtension(s) - return lfc -} - -// SetSize sets the "size" field. -func (lfc *LinFileCreate) SetSize(i int) *LinFileCreate { - lfc.mutation.SetSize(i) - return lfc -} - -// SetMd5 sets the "md5" field. -func (lfc *LinFileCreate) SetMd5(s string) *LinFileCreate { - lfc.mutation.SetMd5(s) - return lfc -} - -// Mutation returns the LinFileMutation object of the builder. -func (lfc *LinFileCreate) Mutation() *LinFileMutation { - return lfc.mutation -} - -// Save creates the LinFile in the database. -func (lfc *LinFileCreate) Save(ctx context.Context) (*LinFile, error) { - var ( - err error - node *LinFile - ) - if len(lfc.hooks) == 0 { - if err = lfc.check(); err != nil { - return nil, err - } - node, err = lfc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinFileMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = lfc.check(); err != nil { - return nil, err - } - lfc.mutation = mutation - if node, err = lfc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(lfc.hooks) - 1; i >= 0; i-- { - if lfc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lfc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lfc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (lfc *LinFileCreate) SaveX(ctx context.Context) *LinFile { - v, err := lfc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lfc *LinFileCreate) Exec(ctx context.Context) error { - _, err := lfc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lfc *LinFileCreate) ExecX(ctx context.Context) { - if err := lfc.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (lfc *LinFileCreate) check() error { - if _, ok := lfc.mutation.Path(); !ok { - return &ValidationError{Name: "path", err: errors.New(`model: missing required field "path"`)} - } - if _, ok := lfc.mutation.GetType(); !ok { - return &ValidationError{Name: "type", err: errors.New(`model: missing required field "type"`)} - } - if _, ok := lfc.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} - } - if _, ok := lfc.mutation.Extension(); !ok { - return &ValidationError{Name: "extension", err: errors.New(`model: missing required field "extension"`)} - } - if _, ok := lfc.mutation.Size(); !ok { - return &ValidationError{Name: "size", err: errors.New(`model: missing required field "size"`)} - } - if _, ok := lfc.mutation.Md5(); !ok { - return &ValidationError{Name: "md5", err: errors.New(`model: missing required field "md5"`)} - } - return nil -} - -func (lfc *LinFileCreate) sqlSave(ctx context.Context) (*LinFile, error) { - _node, _spec := lfc.createSpec() - if err := sqlgraph.CreateNode(ctx, lfc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (lfc *LinFileCreate) createSpec() (*LinFile, *sqlgraph.CreateSpec) { - var ( - _node = &LinFile{config: lfc.config} - _spec = &sqlgraph.CreateSpec{ - Table: linfile.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linfile.FieldID, - }, - } - ) - if value, ok := lfc.mutation.Path(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldPath, - }) - _node.Path = value - } - if value, ok := lfc.mutation.GetType(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linfile.FieldType, - }) - _node.Type = value - } - if value, ok := lfc.mutation.Name(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldName, - }) - _node.Name = value - } - if value, ok := lfc.mutation.Extension(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldExtension, - }) - _node.Extension = value - } - if value, ok := lfc.mutation.Size(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linfile.FieldSize, - }) - _node.Size = value - } - if value, ok := lfc.mutation.Md5(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldMd5, - }) - _node.Md5 = value - } - return _node, _spec -} - -// LinFileCreateBulk is the builder for creating many LinFile entities in bulk. -type LinFileCreateBulk struct { - config - builders []*LinFileCreate -} - -// Save creates the LinFile entities in the database. -func (lfcb *LinFileCreateBulk) Save(ctx context.Context) ([]*LinFile, error) { - specs := make([]*sqlgraph.CreateSpec, len(lfcb.builders)) - nodes := make([]*LinFile, len(lfcb.builders)) - mutators := make([]Mutator, len(lfcb.builders)) - for i := range lfcb.builders { - func(i int, root context.Context) { - builder := lfcb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinFileMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, lfcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, lfcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, lfcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (lfcb *LinFileCreateBulk) SaveX(ctx context.Context) []*LinFile { - v, err := lfcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lfcb *LinFileCreateBulk) Exec(ctx context.Context) error { - _, err := lfcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lfcb *LinFileCreateBulk) ExecX(ctx context.Context) { - if err := lfcb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/linfile_delete.go b/internal/data/model/linfile_delete.go deleted file mode 100644 index f767b58..0000000 --- a/internal/data/model/linfile_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linfile" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinFileDelete is the builder for deleting a LinFile entity. -type LinFileDelete struct { - config - hooks []Hook - mutation *LinFileMutation -} - -// Where appends a list predicates to the LinFileDelete builder. -func (lfd *LinFileDelete) Where(ps ...predicate.LinFile) *LinFileDelete { - lfd.mutation.Where(ps...) - return lfd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (lfd *LinFileDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lfd.hooks) == 0 { - affected, err = lfd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinFileMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lfd.mutation = mutation - affected, err = lfd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(lfd.hooks) - 1; i >= 0; i-- { - if lfd.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lfd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lfd.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lfd *LinFileDelete) ExecX(ctx context.Context) int { - n, err := lfd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (lfd *LinFileDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linfile.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linfile.FieldID, - }, - }, - } - if ps := lfd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, lfd.driver, _spec) -} - -// LinFileDeleteOne is the builder for deleting a single LinFile entity. -type LinFileDeleteOne struct { - lfd *LinFileDelete -} - -// Exec executes the deletion query. -func (lfdo *LinFileDeleteOne) Exec(ctx context.Context) error { - n, err := lfdo.lfd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{linfile.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (lfdo *LinFileDeleteOne) ExecX(ctx context.Context) { - lfdo.lfd.ExecX(ctx) -} diff --git a/internal/data/model/linfile_query.go b/internal/data/model/linfile_query.go deleted file mode 100644 index 43a7c54..0000000 --- a/internal/data/model/linfile_query.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/linfile" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinFileQuery is the builder for querying LinFile entities. -type LinFileQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinFile - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinFileQuery builder. -func (lfq *LinFileQuery) Where(ps ...predicate.LinFile) *LinFileQuery { - lfq.predicates = append(lfq.predicates, ps...) - return lfq -} - -// Limit adds a limit step to the query. -func (lfq *LinFileQuery) Limit(limit int) *LinFileQuery { - lfq.limit = &limit - return lfq -} - -// Offset adds an offset step to the query. -func (lfq *LinFileQuery) Offset(offset int) *LinFileQuery { - lfq.offset = &offset - return lfq -} - -// 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 (lfq *LinFileQuery) Unique(unique bool) *LinFileQuery { - lfq.unique = &unique - return lfq -} - -// Order adds an order step to the query. -func (lfq *LinFileQuery) Order(o ...OrderFunc) *LinFileQuery { - lfq.order = append(lfq.order, o...) - return lfq -} - -// First returns the first LinFile entity from the query. -// Returns a *NotFoundError when no LinFile was found. -func (lfq *LinFileQuery) First(ctx context.Context) (*LinFile, error) { - nodes, err := lfq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linfile.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (lfq *LinFileQuery) FirstX(ctx context.Context) *LinFile { - node, err := lfq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinFile ID from the query. -// Returns a *NotFoundError when no LinFile ID was found. -func (lfq *LinFileQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lfq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linfile.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (lfq *LinFileQuery) FirstIDX(ctx context.Context) int { - id, err := lfq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinFile entity from the query. -// Returns a *NotFoundError when no LinFile was found. -func (lfq *LinFileQuery) Last(ctx context.Context) (*LinFile, error) { - nodes, err := lfq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linfile.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (lfq *LinFileQuery) LastX(ctx context.Context) *LinFile { - node, err := lfq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinFile ID from the query. -// Returns a *NotFoundError when no LinFile ID was found. -func (lfq *LinFileQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lfq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linfile.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (lfq *LinFileQuery) LastIDX(ctx context.Context) int { - id, err := lfq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinFile entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinFile entity is not found. -// Returns a *NotFoundError when no LinFile entities are found. -func (lfq *LinFileQuery) Only(ctx context.Context) (*LinFile, error) { - nodes, err := lfq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{linfile.Label} - default: - return nil, &NotSingularError{linfile.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (lfq *LinFileQuery) OnlyX(ctx context.Context) *LinFile { - node, err := lfq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinFile ID in the query. -// Returns a *NotSingularError when exactly one LinFile ID is not found. -// Returns a *NotFoundError when no entities are found. -func (lfq *LinFileQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lfq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{linfile.Label} - default: - err = &NotSingularError{linfile.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (lfq *LinFileQuery) OnlyIDX(ctx context.Context) int { - id, err := lfq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinFiles. -func (lfq *LinFileQuery) All(ctx context.Context) ([]*LinFile, error) { - if err := lfq.prepareQuery(ctx); err != nil { - return nil, err - } - return lfq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (lfq *LinFileQuery) AllX(ctx context.Context) []*LinFile { - nodes, err := lfq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinFile IDs. -func (lfq *LinFileQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := lfq.Select(linfile.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (lfq *LinFileQuery) IDsX(ctx context.Context) []int { - ids, err := lfq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (lfq *LinFileQuery) Count(ctx context.Context) (int, error) { - if err := lfq.prepareQuery(ctx); err != nil { - return 0, err - } - return lfq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (lfq *LinFileQuery) CountX(ctx context.Context) int { - count, err := lfq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (lfq *LinFileQuery) Exist(ctx context.Context) (bool, error) { - if err := lfq.prepareQuery(ctx); err != nil { - return false, err - } - return lfq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (lfq *LinFileQuery) ExistX(ctx context.Context) bool { - exist, err := lfq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinFileQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (lfq *LinFileQuery) Clone() *LinFileQuery { - if lfq == nil { - return nil - } - return &LinFileQuery{ - config: lfq.config, - limit: lfq.limit, - offset: lfq.offset, - order: append([]OrderFunc{}, lfq.order...), - predicates: append([]predicate.LinFile{}, lfq.predicates...), - // clone intermediate query. - sql: lfq.sql.Clone(), - path: lfq.path, - } -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Path string `json:"path,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinFile.Query(). -// GroupBy(linfile.FieldPath). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (lfq *LinFileQuery) GroupBy(field string, fields ...string) *LinFileGroupBy { - group := &LinFileGroupBy{config: lfq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := lfq.prepareQuery(ctx); err != nil { - return nil, err - } - return lfq.sqlQuery(ctx), nil - } - return group -} - -// 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 { -// Path string `json:"path,omitempty"` -// } -// -// client.LinFile.Query(). -// Select(linfile.FieldPath). -// Scan(ctx, &v) -// -func (lfq *LinFileQuery) Select(fields ...string) *LinFileSelect { - lfq.fields = append(lfq.fields, fields...) - return &LinFileSelect{LinFileQuery: lfq} -} - -func (lfq *LinFileQuery) prepareQuery(ctx context.Context) error { - for _, f := range lfq.fields { - if !linfile.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if lfq.path != nil { - prev, err := lfq.path(ctx) - if err != nil { - return err - } - lfq.sql = prev - } - return nil -} - -func (lfq *LinFileQuery) sqlAll(ctx context.Context) ([]*LinFile, error) { - var ( - nodes = []*LinFile{} - _spec = lfq.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinFile{config: lfq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, lfq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (lfq *LinFileQuery) sqlCount(ctx context.Context) (int, error) { - _spec := lfq.querySpec() - return sqlgraph.CountNodes(ctx, lfq.driver, _spec) -} - -func (lfq *LinFileQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := lfq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (lfq *LinFileQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: linfile.Table, - Columns: linfile.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linfile.FieldID, - }, - }, - From: lfq.sql, - Unique: true, - } - if unique := lfq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := lfq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linfile.FieldID) - for i := range fields { - if fields[i] != linfile.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := lfq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := lfq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := lfq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := lfq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (lfq *LinFileQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(lfq.driver.Dialect()) - t1 := builder.Table(linfile.Table) - columns := lfq.fields - if len(columns) == 0 { - columns = linfile.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if lfq.sql != nil { - selector = lfq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range lfq.predicates { - p(selector) - } - for _, p := range lfq.order { - p(selector) - } - if offset := lfq.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 := lfq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinFileGroupBy is the group-by builder for LinFile entities. -type LinFileGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (lfgb *LinFileGroupBy) Aggregate(fns ...AggregateFunc) *LinFileGroupBy { - lfgb.fns = append(lfgb.fns, fns...) - return lfgb -} - -// Scan applies the group-by query and scans the result into the given value. -func (lfgb *LinFileGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := lfgb.path(ctx) - if err != nil { - return err - } - lfgb.sql = query - return lfgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lfgb *LinFileGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := lfgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(lfgb.fields) > 1 { - return nil, errors.New("model: LinFileGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := lfgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lfgb *LinFileGroupBy) StringsX(ctx context.Context) []string { - v, err := lfgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lfgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lfgb *LinFileGroupBy) StringX(ctx context.Context) string { - v, err := lfgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(lfgb.fields) > 1 { - return nil, errors.New("model: LinFileGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := lfgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lfgb *LinFileGroupBy) IntsX(ctx context.Context) []int { - v, err := lfgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lfgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lfgb *LinFileGroupBy) IntX(ctx context.Context) int { - v, err := lfgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(lfgb.fields) > 1 { - return nil, errors.New("model: LinFileGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := lfgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lfgb *LinFileGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := lfgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lfgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lfgb *LinFileGroupBy) Float64X(ctx context.Context) float64 { - v, err := lfgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(lfgb.fields) > 1 { - return nil, errors.New("model: LinFileGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := lfgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lfgb *LinFileGroupBy) BoolsX(ctx context.Context) []bool { - v, err := lfgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lfgb *LinFileGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lfgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lfgb *LinFileGroupBy) BoolX(ctx context.Context) bool { - v, err := lfgb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lfgb *LinFileGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range lfgb.fields { - if !linfile.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := lfgb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := lfgb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (lfgb *LinFileGroupBy) sqlQuery() *sql.Selector { - selector := lfgb.sql.Select() - aggregation := make([]string, 0, len(lfgb.fns)) - for _, fn := range lfgb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(lfgb.fields)+len(lfgb.fns)) - for _, f := range lfgb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(lfgb.fields...)...) -} - -// LinFileSelect is the builder for selecting fields of LinFile entities. -type LinFileSelect struct { - *LinFileQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (lfs *LinFileSelect) Scan(ctx context.Context, v interface{}) error { - if err := lfs.prepareQuery(ctx); err != nil { - return err - } - lfs.sql = lfs.LinFileQuery.sqlQuery(ctx) - return lfs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lfs *LinFileSelect) ScanX(ctx context.Context, v interface{}) { - if err := lfs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Strings(ctx context.Context) ([]string, error) { - if len(lfs.fields) > 1 { - return nil, errors.New("model: LinFileSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := lfs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lfs *LinFileSelect) StringsX(ctx context.Context) []string { - v, err := lfs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lfs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lfs *LinFileSelect) StringX(ctx context.Context) string { - v, err := lfs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Ints(ctx context.Context) ([]int, error) { - if len(lfs.fields) > 1 { - return nil, errors.New("model: LinFileSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := lfs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lfs *LinFileSelect) IntsX(ctx context.Context) []int { - v, err := lfs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lfs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lfs *LinFileSelect) IntX(ctx context.Context) int { - v, err := lfs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(lfs.fields) > 1 { - return nil, errors.New("model: LinFileSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := lfs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lfs *LinFileSelect) Float64sX(ctx context.Context) []float64 { - v, err := lfs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lfs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lfs *LinFileSelect) Float64X(ctx context.Context) float64 { - v, err := lfs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Bools(ctx context.Context) ([]bool, error) { - if len(lfs.fields) > 1 { - return nil, errors.New("model: LinFileSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := lfs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lfs *LinFileSelect) BoolsX(ctx context.Context) []bool { - v, err := lfs.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (lfs *LinFileSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lfs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linfile.Label} - default: - err = fmt.Errorf("model: LinFileSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lfs *LinFileSelect) BoolX(ctx context.Context) bool { - v, err := lfs.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lfs *LinFileSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := lfs.sql.Query() - if err := lfs.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/linfile_update.go b/internal/data/model/linfile_update.go deleted file mode 100644 index d640e3a..0000000 --- a/internal/data/model/linfile_update.go +++ /dev/null @@ -1,450 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linfile" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinFileUpdate is the builder for updating LinFile entities. -type LinFileUpdate struct { - config - hooks []Hook - mutation *LinFileMutation -} - -// Where appends a list predicates to the LinFileUpdate builder. -func (lfu *LinFileUpdate) Where(ps ...predicate.LinFile) *LinFileUpdate { - lfu.mutation.Where(ps...) - return lfu -} - -// SetPath sets the "path" field. -func (lfu *LinFileUpdate) SetPath(s string) *LinFileUpdate { - lfu.mutation.SetPath(s) - return lfu -} - -// SetType sets the "type" field. -func (lfu *LinFileUpdate) SetType(i int8) *LinFileUpdate { - lfu.mutation.ResetType() - lfu.mutation.SetType(i) - return lfu -} - -// AddType adds i to the "type" field. -func (lfu *LinFileUpdate) AddType(i int8) *LinFileUpdate { - lfu.mutation.AddType(i) - return lfu -} - -// SetName sets the "name" field. -func (lfu *LinFileUpdate) SetName(s string) *LinFileUpdate { - lfu.mutation.SetName(s) - return lfu -} - -// SetExtension sets the "extension" field. -func (lfu *LinFileUpdate) SetExtension(s string) *LinFileUpdate { - lfu.mutation.SetExtension(s) - return lfu -} - -// SetSize sets the "size" field. -func (lfu *LinFileUpdate) SetSize(i int) *LinFileUpdate { - lfu.mutation.ResetSize() - lfu.mutation.SetSize(i) - return lfu -} - -// AddSize adds i to the "size" field. -func (lfu *LinFileUpdate) AddSize(i int) *LinFileUpdate { - lfu.mutation.AddSize(i) - return lfu -} - -// SetMd5 sets the "md5" field. -func (lfu *LinFileUpdate) SetMd5(s string) *LinFileUpdate { - lfu.mutation.SetMd5(s) - return lfu -} - -// Mutation returns the LinFileMutation object of the builder. -func (lfu *LinFileUpdate) Mutation() *LinFileMutation { - return lfu.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (lfu *LinFileUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lfu.hooks) == 0 { - affected, err = lfu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinFileMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lfu.mutation = mutation - affected, err = lfu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(lfu.hooks) - 1; i >= 0; i-- { - if lfu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lfu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lfu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lfu *LinFileUpdate) SaveX(ctx context.Context) int { - affected, err := lfu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (lfu *LinFileUpdate) Exec(ctx context.Context) error { - _, err := lfu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lfu *LinFileUpdate) ExecX(ctx context.Context) { - if err := lfu.Exec(ctx); err != nil { - panic(err) - } -} - -func (lfu *LinFileUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linfile.Table, - Columns: linfile.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linfile.FieldID, - }, - }, - } - if ps := lfu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lfu.mutation.Path(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldPath, - }) - } - if value, ok := lfu.mutation.GetType(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linfile.FieldType, - }) - } - if value, ok := lfu.mutation.AddedType(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linfile.FieldType, - }) - } - if value, ok := lfu.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldName, - }) - } - if value, ok := lfu.mutation.Extension(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldExtension, - }) - } - if value, ok := lfu.mutation.Size(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linfile.FieldSize, - }) - } - if value, ok := lfu.mutation.AddedSize(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linfile.FieldSize, - }) - } - if value, ok := lfu.mutation.Md5(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldMd5, - }) - } - if n, err = sqlgraph.UpdateNodes(ctx, lfu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linfile.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinFileUpdateOne is the builder for updating a single LinFile entity. -type LinFileUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinFileMutation -} - -// SetPath sets the "path" field. -func (lfuo *LinFileUpdateOne) SetPath(s string) *LinFileUpdateOne { - lfuo.mutation.SetPath(s) - return lfuo -} - -// SetType sets the "type" field. -func (lfuo *LinFileUpdateOne) SetType(i int8) *LinFileUpdateOne { - lfuo.mutation.ResetType() - lfuo.mutation.SetType(i) - return lfuo -} - -// AddType adds i to the "type" field. -func (lfuo *LinFileUpdateOne) AddType(i int8) *LinFileUpdateOne { - lfuo.mutation.AddType(i) - return lfuo -} - -// SetName sets the "name" field. -func (lfuo *LinFileUpdateOne) SetName(s string) *LinFileUpdateOne { - lfuo.mutation.SetName(s) - return lfuo -} - -// SetExtension sets the "extension" field. -func (lfuo *LinFileUpdateOne) SetExtension(s string) *LinFileUpdateOne { - lfuo.mutation.SetExtension(s) - return lfuo -} - -// SetSize sets the "size" field. -func (lfuo *LinFileUpdateOne) SetSize(i int) *LinFileUpdateOne { - lfuo.mutation.ResetSize() - lfuo.mutation.SetSize(i) - return lfuo -} - -// AddSize adds i to the "size" field. -func (lfuo *LinFileUpdateOne) AddSize(i int) *LinFileUpdateOne { - lfuo.mutation.AddSize(i) - return lfuo -} - -// SetMd5 sets the "md5" field. -func (lfuo *LinFileUpdateOne) SetMd5(s string) *LinFileUpdateOne { - lfuo.mutation.SetMd5(s) - return lfuo -} - -// Mutation returns the LinFileMutation object of the builder. -func (lfuo *LinFileUpdateOne) Mutation() *LinFileMutation { - return lfuo.mutation -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (lfuo *LinFileUpdateOne) Select(field string, fields ...string) *LinFileUpdateOne { - lfuo.fields = append([]string{field}, fields...) - return lfuo -} - -// Save executes the query and returns the updated LinFile entity. -func (lfuo *LinFileUpdateOne) Save(ctx context.Context) (*LinFile, error) { - var ( - err error - node *LinFile - ) - if len(lfuo.hooks) == 0 { - node, err = lfuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinFileMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lfuo.mutation = mutation - node, err = lfuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(lfuo.hooks) - 1; i >= 0; i-- { - if lfuo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lfuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lfuo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lfuo *LinFileUpdateOne) SaveX(ctx context.Context) *LinFile { - node, err := lfuo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (lfuo *LinFileUpdateOne) Exec(ctx context.Context) error { - _, err := lfuo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lfuo *LinFileUpdateOne) ExecX(ctx context.Context) { - if err := lfuo.Exec(ctx); err != nil { - panic(err) - } -} - -func (lfuo *LinFileUpdateOne) sqlSave(ctx context.Context) (_node *LinFile, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linfile.Table, - Columns: linfile.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linfile.FieldID, - }, - }, - } - id, ok := lfuo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinFile.ID for update")} - } - _spec.Node.ID.Value = id - if fields := lfuo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linfile.FieldID) - for _, f := range fields { - if !linfile.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != linfile.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := lfuo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lfuo.mutation.Path(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldPath, - }) - } - if value, ok := lfuo.mutation.GetType(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linfile.FieldType, - }) - } - if value, ok := lfuo.mutation.AddedType(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linfile.FieldType, - }) - } - if value, ok := lfuo.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldName, - }) - } - if value, ok := lfuo.mutation.Extension(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldExtension, - }) - } - if value, ok := lfuo.mutation.Size(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linfile.FieldSize, - }) - } - if value, ok := lfuo.mutation.AddedSize(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linfile.FieldSize, - }) - } - if value, ok := lfuo.mutation.Md5(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linfile.FieldMd5, - }) - } - _node = &LinFile{config: lfuo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, lfuo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linfile.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/lingroup.go b/internal/data/model/lingroup.go deleted file mode 100644 index 6972969..0000000 --- a/internal/data/model/lingroup.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "strings" - - "entgo.io/ent/dialect/sql" -) - -// LinGroup is the model entity for the LinGroup schema. -type LinGroup struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // Name holds the value of the "name" field. - // 分组名称,例如:搬砖者 - Name string `json:"name,omitempty"` - // Info holds the value of the "info" field. - // 分组信息:例如:搬砖的人 - Info string `json:"info,omitempty"` - // Level holds the value of the "level" field. - // 分组级别 1:root 2:guest 3:user(root、guest分组只能存在一个) - Level int8 `json:"level,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the LinGroupQuery when eager-loading is set. - Edges LinGroupEdges `json:"edges"` -} - -// LinGroupEdges holds the relations/edges for other nodes in the graph. -type LinGroupEdges struct { - // LinUser holds the value of the lin_user edge. - LinUser []*LinUser `json:"lin_user,omitempty"` - // LinPermission holds the value of the lin_permission edge. - LinPermission []*LinPermission `json:"lin_permission,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool -} - -// LinUserOrErr returns the LinUser value or an error if the edge -// was not loaded in eager-loading. -func (e LinGroupEdges) LinUserOrErr() ([]*LinUser, error) { - if e.loadedTypes[0] { - return e.LinUser, nil - } - return nil, &NotLoadedError{edge: "lin_user"} -} - -// LinPermissionOrErr returns the LinPermission value or an error if the edge -// was not loaded in eager-loading. -func (e LinGroupEdges) LinPermissionOrErr() ([]*LinPermission, error) { - if e.loadedTypes[1] { - return e.LinPermission, nil - } - return nil, &NotLoadedError{edge: "lin_permission"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinGroup) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case lingroup.FieldID, lingroup.FieldLevel: - values[i] = new(sql.NullInt64) - case lingroup.FieldName, lingroup.FieldInfo: - values[i] = new(sql.NullString) - default: - return nil, fmt.Errorf("unexpected column %q for type LinGroup", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinGroup fields. -func (lg *LinGroup) assignValues(columns []string, values []interface{}) 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 lingroup.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - lg.ID = int(value.Int64) - case lingroup.FieldName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[i]) - } else if value.Valid { - lg.Name = value.String - } - case lingroup.FieldInfo: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field info", values[i]) - } else if value.Valid { - lg.Info = value.String - } - case lingroup.FieldLevel: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field level", values[i]) - } else if value.Valid { - lg.Level = int8(value.Int64) - } - } - } - return nil -} - -// QueryLinUser queries the "lin_user" edge of the LinGroup entity. -func (lg *LinGroup) QueryLinUser() *LinUserQuery { - return (&LinGroupClient{config: lg.config}).QueryLinUser(lg) -} - -// QueryLinPermission queries the "lin_permission" edge of the LinGroup entity. -func (lg *LinGroup) QueryLinPermission() *LinPermissionQuery { - return (&LinGroupClient{config: lg.config}).QueryLinPermission(lg) -} - -// Update returns a builder for updating this LinGroup. -// Note that you need to call LinGroup.Unwrap() before calling this method if this LinGroup -// was returned from a transaction, and the transaction was committed or rolled back. -func (lg *LinGroup) Update() *LinGroupUpdateOne { - return (&LinGroupClient{config: lg.config}).UpdateOne(lg) -} - -// Unwrap unwraps the LinGroup 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 (lg *LinGroup) Unwrap() *LinGroup { - tx, ok := lg.config.driver.(*txDriver) - if !ok { - panic("model: LinGroup is not a transactional entity") - } - lg.config.driver = tx.drv - return lg -} - -// String implements the fmt.Stringer. -func (lg *LinGroup) String() string { - var builder strings.Builder - builder.WriteString("LinGroup(") - builder.WriteString(fmt.Sprintf("id=%v", lg.ID)) - builder.WriteString(", name=") - builder.WriteString(lg.Name) - builder.WriteString(", info=") - builder.WriteString(lg.Info) - builder.WriteString(", level=") - builder.WriteString(fmt.Sprintf("%v", lg.Level)) - builder.WriteByte(')') - return builder.String() -} - -// LinGroups is a parsable slice of LinGroup. -type LinGroups []*LinGroup - -func (lg LinGroups) config(cfg config) { - for _i := range lg { - lg[_i].config = cfg - } -} diff --git a/internal/data/model/lingroup/lingroup.go b/internal/data/model/lingroup/lingroup.go deleted file mode 100644 index 5d25855..0000000 --- a/internal/data/model/lingroup/lingroup.go +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package lingroup - -const ( - // Label holds the string label denoting the lingroup type in the database. - Label = "lin_group" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldName holds the string denoting the name field in the database. - FieldName = "name" - // FieldInfo holds the string denoting the info field in the database. - FieldInfo = "info" - // FieldLevel holds the string denoting the level field in the database. - FieldLevel = "level" - // EdgeLinUser holds the string denoting the lin_user edge name in mutations. - EdgeLinUser = "lin_user" - // EdgeLinPermission holds the string denoting the lin_permission edge name in mutations. - EdgeLinPermission = "lin_permission" - // Table holds the table name of the lingroup in the database. - Table = "lin_group" - // LinUserTable is the table that holds the lin_user relation/edge. The primary key declared below. - LinUserTable = "lin_user_group" - // LinUserInverseTable is the table name for the LinUser entity. - // It exists in this package in order to avoid circular dependency with the "linuser" package. - LinUserInverseTable = "lin_user" - // LinPermissionTable is the table that holds the lin_permission relation/edge. The primary key declared below. - LinPermissionTable = "lin_permission_lin_group" - // LinPermissionInverseTable is the table name for the LinPermission entity. - // It exists in this package in order to avoid circular dependency with the "linpermission" package. - LinPermissionInverseTable = "lin_permission" -) - -// Columns holds all SQL columns for lingroup fields. -var Columns = []string{ - FieldID, - FieldName, - FieldInfo, - FieldLevel, -} - -var ( - // LinUserPrimaryKey and LinUserColumn2 are the table columns denoting the - // primary key for the lin_user relation (M2M). - LinUserPrimaryKey = []string{"user_id", "group_id"} - // LinPermissionPrimaryKey and LinPermissionColumn2 are the table columns denoting the - // primary key for the lin_permission relation (M2M). - LinPermissionPrimaryKey = []string{"lin_permission_id", "lin_group_id"} -) - -// 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 -} diff --git a/internal/data/model/lingroup/where.go b/internal/data/model/lingroup/where.go deleted file mode 100644 index d4c70dd..0000000 --- a/internal/data/model/lingroup/where.go +++ /dev/null @@ -1,500 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package lingroup - -import ( - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// Name applies equality check predicate on the "name" field. It's identical to NameEQ. -func Name(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) -} - -// Info applies equality check predicate on the "info" field. It's identical to InfoEQ. -func Info(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldInfo), v)) - }) -} - -// Level applies equality check predicate on the "level" field. It's identical to LevelEQ. -func Level(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldLevel), v)) - }) -} - -// NameEQ applies the EQ predicate on the "name" field. -func NameEQ(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) -} - -// NameNEQ applies the NEQ predicate on the "name" field. -func NameNEQ(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldName), v)) - }) -} - -// NameIn applies the In predicate on the "name" field. -func NameIn(vs ...string) predicate.LinGroup { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldName), v...)) - }) -} - -// NameNotIn applies the NotIn predicate on the "name" field. -func NameNotIn(vs ...string) predicate.LinGroup { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldName), v...)) - }) -} - -// NameGT applies the GT predicate on the "name" field. -func NameGT(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldName), v)) - }) -} - -// NameGTE applies the GTE predicate on the "name" field. -func NameGTE(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldName), v)) - }) -} - -// NameLT applies the LT predicate on the "name" field. -func NameLT(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldName), v)) - }) -} - -// NameLTE applies the LTE predicate on the "name" field. -func NameLTE(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldName), v)) - }) -} - -// NameContains applies the Contains predicate on the "name" field. -func NameContains(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldName), v)) - }) -} - -// NameHasPrefix applies the HasPrefix predicate on the "name" field. -func NameHasPrefix(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldName), v)) - }) -} - -// NameHasSuffix applies the HasSuffix predicate on the "name" field. -func NameHasSuffix(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldName), v)) - }) -} - -// NameEqualFold applies the EqualFold predicate on the "name" field. -func NameEqualFold(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldName), v)) - }) -} - -// NameContainsFold applies the ContainsFold predicate on the "name" field. -func NameContainsFold(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldName), v)) - }) -} - -// InfoEQ applies the EQ predicate on the "info" field. -func InfoEQ(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldInfo), v)) - }) -} - -// InfoNEQ applies the NEQ predicate on the "info" field. -func InfoNEQ(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldInfo), v)) - }) -} - -// InfoIn applies the In predicate on the "info" field. -func InfoIn(vs ...string) predicate.LinGroup { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldInfo), v...)) - }) -} - -// InfoNotIn applies the NotIn predicate on the "info" field. -func InfoNotIn(vs ...string) predicate.LinGroup { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldInfo), v...)) - }) -} - -// InfoGT applies the GT predicate on the "info" field. -func InfoGT(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldInfo), v)) - }) -} - -// InfoGTE applies the GTE predicate on the "info" field. -func InfoGTE(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldInfo), v)) - }) -} - -// InfoLT applies the LT predicate on the "info" field. -func InfoLT(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldInfo), v)) - }) -} - -// InfoLTE applies the LTE predicate on the "info" field. -func InfoLTE(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldInfo), v)) - }) -} - -// InfoContains applies the Contains predicate on the "info" field. -func InfoContains(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldInfo), v)) - }) -} - -// InfoHasPrefix applies the HasPrefix predicate on the "info" field. -func InfoHasPrefix(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldInfo), v)) - }) -} - -// InfoHasSuffix applies the HasSuffix predicate on the "info" field. -func InfoHasSuffix(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldInfo), v)) - }) -} - -// InfoEqualFold applies the EqualFold predicate on the "info" field. -func InfoEqualFold(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldInfo), v)) - }) -} - -// InfoContainsFold applies the ContainsFold predicate on the "info" field. -func InfoContainsFold(v string) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldInfo), v)) - }) -} - -// LevelEQ applies the EQ predicate on the "level" field. -func LevelEQ(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldLevel), v)) - }) -} - -// LevelNEQ applies the NEQ predicate on the "level" field. -func LevelNEQ(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldLevel), v)) - }) -} - -// LevelIn applies the In predicate on the "level" field. -func LevelIn(vs ...int8) predicate.LinGroup { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldLevel), v...)) - }) -} - -// LevelNotIn applies the NotIn predicate on the "level" field. -func LevelNotIn(vs ...int8) predicate.LinGroup { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroup(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldLevel), v...)) - }) -} - -// LevelGT applies the GT predicate on the "level" field. -func LevelGT(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldLevel), v)) - }) -} - -// LevelGTE applies the GTE predicate on the "level" field. -func LevelGTE(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldLevel), v)) - }) -} - -// LevelLT applies the LT predicate on the "level" field. -func LevelLT(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldLevel), v)) - }) -} - -// LevelLTE applies the LTE predicate on the "level" field. -func LevelLTE(v int8) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldLevel), v)) - }) -} - -// HasLinUser applies the HasEdge predicate on the "lin_user" edge. -func HasLinUser() predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinUserTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, LinUserTable, LinUserPrimaryKey...), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasLinUserWith applies the HasEdge predicate on the "lin_user" edge with a given conditions (other predicates). -func HasLinUserWith(preds ...predicate.LinUser) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinUserInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, LinUserTable, LinUserPrimaryKey...), - ) - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasLinPermission applies the HasEdge predicate on the "lin_permission" edge. -func HasLinPermission() predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinPermissionTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, LinPermissionTable, LinPermissionPrimaryKey...), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasLinPermissionWith applies the HasEdge predicate on the "lin_permission" edge with a given conditions (other predicates). -func HasLinPermissionWith(preds ...predicate.LinPermission) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinPermissionInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, LinPermissionTable, LinPermissionPrimaryKey...), - ) - 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.LinGroup) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinGroup) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinGroup) predicate.LinGroup { - return predicate.LinGroup(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/lingroup_create.go b/internal/data/model/lingroup_create.go deleted file mode 100644 index 9b3b354..0000000 --- a/internal/data/model/lingroup_create.go +++ /dev/null @@ -1,324 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/linuser" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupCreate is the builder for creating a LinGroup entity. -type LinGroupCreate struct { - config - mutation *LinGroupMutation - hooks []Hook -} - -// SetName sets the "name" field. -func (lgc *LinGroupCreate) SetName(s string) *LinGroupCreate { - lgc.mutation.SetName(s) - return lgc -} - -// SetInfo sets the "info" field. -func (lgc *LinGroupCreate) SetInfo(s string) *LinGroupCreate { - lgc.mutation.SetInfo(s) - return lgc -} - -// SetLevel sets the "level" field. -func (lgc *LinGroupCreate) SetLevel(i int8) *LinGroupCreate { - lgc.mutation.SetLevel(i) - return lgc -} - -// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. -func (lgc *LinGroupCreate) AddLinUserIDs(ids ...int) *LinGroupCreate { - lgc.mutation.AddLinUserIDs(ids...) - return lgc -} - -// AddLinUser adds the "lin_user" edges to the LinUser entity. -func (lgc *LinGroupCreate) AddLinUser(l ...*LinUser) *LinGroupCreate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lgc.AddLinUserIDs(ids...) -} - -// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. -func (lgc *LinGroupCreate) AddLinPermissionIDs(ids ...int) *LinGroupCreate { - lgc.mutation.AddLinPermissionIDs(ids...) - return lgc -} - -// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. -func (lgc *LinGroupCreate) AddLinPermission(l ...*LinPermission) *LinGroupCreate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lgc.AddLinPermissionIDs(ids...) -} - -// Mutation returns the LinGroupMutation object of the builder. -func (lgc *LinGroupCreate) Mutation() *LinGroupMutation { - return lgc.mutation -} - -// Save creates the LinGroup in the database. -func (lgc *LinGroupCreate) Save(ctx context.Context) (*LinGroup, error) { - var ( - err error - node *LinGroup - ) - if len(lgc.hooks) == 0 { - if err = lgc.check(); err != nil { - return nil, err - } - node, err = lgc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = lgc.check(); err != nil { - return nil, err - } - lgc.mutation = mutation - if node, err = lgc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(lgc.hooks) - 1; i >= 0; i-- { - if lgc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (lgc *LinGroupCreate) SaveX(ctx context.Context) *LinGroup { - v, err := lgc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lgc *LinGroupCreate) Exec(ctx context.Context) error { - _, err := lgc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgc *LinGroupCreate) ExecX(ctx context.Context) { - if err := lgc.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (lgc *LinGroupCreate) check() error { - if _, ok := lgc.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} - } - if _, ok := lgc.mutation.Info(); !ok { - return &ValidationError{Name: "info", err: errors.New(`model: missing required field "info"`)} - } - if _, ok := lgc.mutation.Level(); !ok { - return &ValidationError{Name: "level", err: errors.New(`model: missing required field "level"`)} - } - return nil -} - -func (lgc *LinGroupCreate) sqlSave(ctx context.Context) (*LinGroup, error) { - _node, _spec := lgc.createSpec() - if err := sqlgraph.CreateNode(ctx, lgc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (lgc *LinGroupCreate) createSpec() (*LinGroup, *sqlgraph.CreateSpec) { - var ( - _node = &LinGroup{config: lgc.config} - _spec = &sqlgraph.CreateSpec{ - Table: lingroup.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - } - ) - if value, ok := lgc.mutation.Name(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: lingroup.FieldName, - }) - _node.Name = value - } - if value, ok := lgc.mutation.Info(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: lingroup.FieldInfo, - }) - _node.Info = value - } - if value, ok := lgc.mutation.Level(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: lingroup.FieldLevel, - }) - _node.Level = value - } - if nodes := lgc.mutation.LinUserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := lgc.mutation.LinPermissionIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// LinGroupCreateBulk is the builder for creating many LinGroup entities in bulk. -type LinGroupCreateBulk struct { - config - builders []*LinGroupCreate -} - -// Save creates the LinGroup entities in the database. -func (lgcb *LinGroupCreateBulk) Save(ctx context.Context) ([]*LinGroup, error) { - specs := make([]*sqlgraph.CreateSpec, len(lgcb.builders)) - nodes := make([]*LinGroup, len(lgcb.builders)) - mutators := make([]Mutator, len(lgcb.builders)) - for i := range lgcb.builders { - func(i int, root context.Context) { - builder := lgcb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, lgcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, lgcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, lgcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (lgcb *LinGroupCreateBulk) SaveX(ctx context.Context) []*LinGroup { - v, err := lgcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lgcb *LinGroupCreateBulk) Exec(ctx context.Context) error { - _, err := lgcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgcb *LinGroupCreateBulk) ExecX(ctx context.Context) { - if err := lgcb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/lingroup_delete.go b/internal/data/model/lingroup_delete.go deleted file mode 100644 index 5e6e856..0000000 --- a/internal/data/model/lingroup_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupDelete is the builder for deleting a LinGroup entity. -type LinGroupDelete struct { - config - hooks []Hook - mutation *LinGroupMutation -} - -// Where appends a list predicates to the LinGroupDelete builder. -func (lgd *LinGroupDelete) Where(ps ...predicate.LinGroup) *LinGroupDelete { - lgd.mutation.Where(ps...) - return lgd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (lgd *LinGroupDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lgd.hooks) == 0 { - affected, err = lgd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lgd.mutation = mutation - affected, err = lgd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(lgd.hooks) - 1; i >= 0; i-- { - if lgd.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgd.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgd *LinGroupDelete) ExecX(ctx context.Context) int { - n, err := lgd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (lgd *LinGroupDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingroup.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - if ps := lgd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, lgd.driver, _spec) -} - -// LinGroupDeleteOne is the builder for deleting a single LinGroup entity. -type LinGroupDeleteOne struct { - lgd *LinGroupDelete -} - -// Exec executes the deletion query. -func (lgdo *LinGroupDeleteOne) Exec(ctx context.Context) error { - n, err := lgdo.lgd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{lingroup.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgdo *LinGroupDeleteOne) ExecX(ctx context.Context) { - lgdo.lgd.ExecX(ctx) -} diff --git a/internal/data/model/lingroup_query.go b/internal/data/model/lingroup_query.go deleted file mode 100644 index b9e8d72..0000000 --- a/internal/data/model/lingroup_query.go +++ /dev/null @@ -1,1170 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "database/sql/driver" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupQuery is the builder for querying LinGroup entities. -type LinGroupQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinGroup - // eager-loading edges. - withLinUser *LinUserQuery - withLinPermission *LinPermissionQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinGroupQuery builder. -func (lgq *LinGroupQuery) Where(ps ...predicate.LinGroup) *LinGroupQuery { - lgq.predicates = append(lgq.predicates, ps...) - return lgq -} - -// Limit adds a limit step to the query. -func (lgq *LinGroupQuery) Limit(limit int) *LinGroupQuery { - lgq.limit = &limit - return lgq -} - -// Offset adds an offset step to the query. -func (lgq *LinGroupQuery) Offset(offset int) *LinGroupQuery { - lgq.offset = &offset - return lgq -} - -// 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 (lgq *LinGroupQuery) Unique(unique bool) *LinGroupQuery { - lgq.unique = &unique - return lgq -} - -// Order adds an order step to the query. -func (lgq *LinGroupQuery) Order(o ...OrderFunc) *LinGroupQuery { - lgq.order = append(lgq.order, o...) - return lgq -} - -// QueryLinUser chains the current query on the "lin_user" edge. -func (lgq *LinGroupQuery) QueryLinUser() *LinUserQuery { - query := &LinUserQuery{config: lgq.config} - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := lgq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := lgq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(lingroup.Table, lingroup.FieldID, selector), - sqlgraph.To(linuser.Table, linuser.FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, lingroup.LinUserTable, lingroup.LinUserPrimaryKey...), - ) - fromU = sqlgraph.SetNeighbors(lgq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryLinPermission chains the current query on the "lin_permission" edge. -func (lgq *LinGroupQuery) QueryLinPermission() *LinPermissionQuery { - query := &LinPermissionQuery{config: lgq.config} - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := lgq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := lgq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(lingroup.Table, lingroup.FieldID, selector), - sqlgraph.To(linpermission.Table, linpermission.FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, lingroup.LinPermissionTable, lingroup.LinPermissionPrimaryKey...), - ) - fromU = sqlgraph.SetNeighbors(lgq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first LinGroup entity from the query. -// Returns a *NotFoundError when no LinGroup was found. -func (lgq *LinGroupQuery) First(ctx context.Context) (*LinGroup, error) { - nodes, err := lgq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{lingroup.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (lgq *LinGroupQuery) FirstX(ctx context.Context) *LinGroup { - node, err := lgq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinGroup ID from the query. -// Returns a *NotFoundError when no LinGroup ID was found. -func (lgq *LinGroupQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lgq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{lingroup.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (lgq *LinGroupQuery) FirstIDX(ctx context.Context) int { - id, err := lgq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinGroup entity from the query. -// Returns a *NotFoundError when no LinGroup was found. -func (lgq *LinGroupQuery) Last(ctx context.Context) (*LinGroup, error) { - nodes, err := lgq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{lingroup.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (lgq *LinGroupQuery) LastX(ctx context.Context) *LinGroup { - node, err := lgq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinGroup ID from the query. -// Returns a *NotFoundError when no LinGroup ID was found. -func (lgq *LinGroupQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lgq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{lingroup.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (lgq *LinGroupQuery) LastIDX(ctx context.Context) int { - id, err := lgq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinGroup entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinGroup entity is not found. -// Returns a *NotFoundError when no LinGroup entities are found. -func (lgq *LinGroupQuery) Only(ctx context.Context) (*LinGroup, error) { - nodes, err := lgq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{lingroup.Label} - default: - return nil, &NotSingularError{lingroup.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (lgq *LinGroupQuery) OnlyX(ctx context.Context) *LinGroup { - node, err := lgq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinGroup ID in the query. -// Returns a *NotSingularError when exactly one LinGroup ID is not found. -// Returns a *NotFoundError when no entities are found. -func (lgq *LinGroupQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lgq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = &NotSingularError{lingroup.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (lgq *LinGroupQuery) OnlyIDX(ctx context.Context) int { - id, err := lgq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinGroups. -func (lgq *LinGroupQuery) All(ctx context.Context) ([]*LinGroup, error) { - if err := lgq.prepareQuery(ctx); err != nil { - return nil, err - } - return lgq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (lgq *LinGroupQuery) AllX(ctx context.Context) []*LinGroup { - nodes, err := lgq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinGroup IDs. -func (lgq *LinGroupQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := lgq.Select(lingroup.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (lgq *LinGroupQuery) IDsX(ctx context.Context) []int { - ids, err := lgq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (lgq *LinGroupQuery) Count(ctx context.Context) (int, error) { - if err := lgq.prepareQuery(ctx); err != nil { - return 0, err - } - return lgq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (lgq *LinGroupQuery) CountX(ctx context.Context) int { - count, err := lgq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (lgq *LinGroupQuery) Exist(ctx context.Context) (bool, error) { - if err := lgq.prepareQuery(ctx); err != nil { - return false, err - } - return lgq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (lgq *LinGroupQuery) ExistX(ctx context.Context) bool { - exist, err := lgq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinGroupQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (lgq *LinGroupQuery) Clone() *LinGroupQuery { - if lgq == nil { - return nil - } - return &LinGroupQuery{ - config: lgq.config, - limit: lgq.limit, - offset: lgq.offset, - order: append([]OrderFunc{}, lgq.order...), - predicates: append([]predicate.LinGroup{}, lgq.predicates...), - withLinUser: lgq.withLinUser.Clone(), - withLinPermission: lgq.withLinPermission.Clone(), - // clone intermediate query. - sql: lgq.sql.Clone(), - path: lgq.path, - } -} - -// WithLinUser tells the query-builder to eager-load the nodes that are connected to -// the "lin_user" edge. The optional arguments are used to configure the query builder of the edge. -func (lgq *LinGroupQuery) WithLinUser(opts ...func(*LinUserQuery)) *LinGroupQuery { - query := &LinUserQuery{config: lgq.config} - for _, opt := range opts { - opt(query) - } - lgq.withLinUser = query - return lgq -} - -// WithLinPermission tells the query-builder to eager-load the nodes that are connected to -// the "lin_permission" edge. The optional arguments are used to configure the query builder of the edge. -func (lgq *LinGroupQuery) WithLinPermission(opts ...func(*LinPermissionQuery)) *LinGroupQuery { - query := &LinPermissionQuery{config: lgq.config} - for _, opt := range opts { - opt(query) - } - lgq.withLinPermission = query - return lgq -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinGroup.Query(). -// GroupBy(lingroup.FieldName). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (lgq *LinGroupQuery) GroupBy(field string, fields ...string) *LinGroupGroupBy { - group := &LinGroupGroupBy{config: lgq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := lgq.prepareQuery(ctx); err != nil { - return nil, err - } - return lgq.sqlQuery(ctx), nil - } - return group -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// } -// -// client.LinGroup.Query(). -// Select(lingroup.FieldName). -// Scan(ctx, &v) -// -func (lgq *LinGroupQuery) Select(fields ...string) *LinGroupSelect { - lgq.fields = append(lgq.fields, fields...) - return &LinGroupSelect{LinGroupQuery: lgq} -} - -func (lgq *LinGroupQuery) prepareQuery(ctx context.Context) error { - for _, f := range lgq.fields { - if !lingroup.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if lgq.path != nil { - prev, err := lgq.path(ctx) - if err != nil { - return err - } - lgq.sql = prev - } - return nil -} - -func (lgq *LinGroupQuery) sqlAll(ctx context.Context) ([]*LinGroup, error) { - var ( - nodes = []*LinGroup{} - _spec = lgq.querySpec() - loadedTypes = [2]bool{ - lgq.withLinUser != nil, - lgq.withLinPermission != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinGroup{config: lgq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, lgq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - - if query := lgq.withLinUser; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - ids := make(map[int]*LinGroup, len(nodes)) - for _, node := range nodes { - ids[node.ID] = node - fks = append(fks, node.ID) - node.Edges.LinUser = []*LinUser{} - } - var ( - edgeids []int - edges = make(map[int][]*LinGroup) - ) - _spec := &sqlgraph.EdgeQuerySpec{ - Edge: &sqlgraph.EdgeSpec{ - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - }, - Predicate: func(s *sql.Selector) { - s.Where(sql.InValues(lingroup.LinUserPrimaryKey[0], fks...)) - }, - ScanValues: func() [2]interface{} { - return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} - }, - Assign: func(out, in interface{}) error { - eout, ok := out.(*sql.NullInt64) - if !ok || eout == nil { - return fmt.Errorf("unexpected id value for edge-out") - } - ein, ok := in.(*sql.NullInt64) - if !ok || ein == nil { - return fmt.Errorf("unexpected id value for edge-in") - } - outValue := int(eout.Int64) - inValue := int(ein.Int64) - node, ok := ids[outValue] - if !ok { - return fmt.Errorf("unexpected node id in edges: %v", outValue) - } - if _, ok := edges[inValue]; !ok { - edgeids = append(edgeids, inValue) - } - edges[inValue] = append(edges[inValue], node) - return nil - }, - } - if err := sqlgraph.QueryEdges(ctx, lgq.driver, _spec); err != nil { - return nil, fmt.Errorf(`query edges "lin_user": %w`, err) - } - query.Where(linuser.IDIn(edgeids...)) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err - } - for _, n := range neighbors { - nodes, ok := edges[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected "lin_user" node returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.LinUser = append(nodes[i].Edges.LinUser, n) - } - } - } - - if query := lgq.withLinPermission; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - ids := make(map[int]*LinGroup, len(nodes)) - for _, node := range nodes { - ids[node.ID] = node - fks = append(fks, node.ID) - node.Edges.LinPermission = []*LinPermission{} - } - var ( - edgeids []int - edges = make(map[int][]*LinGroup) - ) - _spec := &sqlgraph.EdgeQuerySpec{ - Edge: &sqlgraph.EdgeSpec{ - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - }, - Predicate: func(s *sql.Selector) { - s.Where(sql.InValues(lingroup.LinPermissionPrimaryKey[1], fks...)) - }, - ScanValues: func() [2]interface{} { - return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} - }, - Assign: func(out, in interface{}) error { - eout, ok := out.(*sql.NullInt64) - if !ok || eout == nil { - return fmt.Errorf("unexpected id value for edge-out") - } - ein, ok := in.(*sql.NullInt64) - if !ok || ein == nil { - return fmt.Errorf("unexpected id value for edge-in") - } - outValue := int(eout.Int64) - inValue := int(ein.Int64) - node, ok := ids[outValue] - if !ok { - return fmt.Errorf("unexpected node id in edges: %v", outValue) - } - if _, ok := edges[inValue]; !ok { - edgeids = append(edgeids, inValue) - } - edges[inValue] = append(edges[inValue], node) - return nil - }, - } - if err := sqlgraph.QueryEdges(ctx, lgq.driver, _spec); err != nil { - return nil, fmt.Errorf(`query edges "lin_permission": %w`, err) - } - query.Where(linpermission.IDIn(edgeids...)) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err - } - for _, n := range neighbors { - nodes, ok := edges[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected "lin_permission" node returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.LinPermission = append(nodes[i].Edges.LinPermission, n) - } - } - } - - return nodes, nil -} - -func (lgq *LinGroupQuery) sqlCount(ctx context.Context) (int, error) { - _spec := lgq.querySpec() - return sqlgraph.CountNodes(ctx, lgq.driver, _spec) -} - -func (lgq *LinGroupQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := lgq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (lgq *LinGroupQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingroup.Table, - Columns: lingroup.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - From: lgq.sql, - Unique: true, - } - if unique := lgq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := lgq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, lingroup.FieldID) - for i := range fields { - if fields[i] != lingroup.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := lgq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := lgq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := lgq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := lgq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (lgq *LinGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(lgq.driver.Dialect()) - t1 := builder.Table(lingroup.Table) - columns := lgq.fields - if len(columns) == 0 { - columns = lingroup.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if lgq.sql != nil { - selector = lgq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range lgq.predicates { - p(selector) - } - for _, p := range lgq.order { - p(selector) - } - if offset := lgq.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 := lgq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinGroupGroupBy is the group-by builder for LinGroup entities. -type LinGroupGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (lggb *LinGroupGroupBy) Aggregate(fns ...AggregateFunc) *LinGroupGroupBy { - lggb.fns = append(lggb.fns, fns...) - return lggb -} - -// Scan applies the group-by query and scans the result into the given value. -func (lggb *LinGroupGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := lggb.path(ctx) - if err != nil { - return err - } - lggb.sql = query - return lggb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lggb *LinGroupGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := lggb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(lggb.fields) > 1 { - return nil, errors.New("model: LinGroupGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := lggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lggb *LinGroupGroupBy) StringsX(ctx context.Context) []string { - v, err := lggb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lggb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lggb *LinGroupGroupBy) StringX(ctx context.Context) string { - v, err := lggb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(lggb.fields) > 1 { - return nil, errors.New("model: LinGroupGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := lggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lggb *LinGroupGroupBy) IntsX(ctx context.Context) []int { - v, err := lggb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lggb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lggb *LinGroupGroupBy) IntX(ctx context.Context) int { - v, err := lggb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(lggb.fields) > 1 { - return nil, errors.New("model: LinGroupGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := lggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lggb *LinGroupGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := lggb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lggb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lggb *LinGroupGroupBy) Float64X(ctx context.Context) float64 { - v, err := lggb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(lggb.fields) > 1 { - return nil, errors.New("model: LinGroupGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := lggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lggb *LinGroupGroupBy) BoolsX(ctx context.Context) []bool { - v, err := lggb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lggb *LinGroupGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lggb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lggb *LinGroupGroupBy) BoolX(ctx context.Context) bool { - v, err := lggb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lggb *LinGroupGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range lggb.fields { - if !lingroup.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := lggb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := lggb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (lggb *LinGroupGroupBy) sqlQuery() *sql.Selector { - selector := lggb.sql.Select() - aggregation := make([]string, 0, len(lggb.fns)) - for _, fn := range lggb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(lggb.fields)+len(lggb.fns)) - for _, f := range lggb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(lggb.fields...)...) -} - -// LinGroupSelect is the builder for selecting fields of LinGroup entities. -type LinGroupSelect struct { - *LinGroupQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (lgs *LinGroupSelect) Scan(ctx context.Context, v interface{}) error { - if err := lgs.prepareQuery(ctx); err != nil { - return err - } - lgs.sql = lgs.LinGroupQuery.sqlQuery(ctx) - return lgs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lgs *LinGroupSelect) ScanX(ctx context.Context, v interface{}) { - if err := lgs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Strings(ctx context.Context) ([]string, error) { - if len(lgs.fields) > 1 { - return nil, errors.New("model: LinGroupSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := lgs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lgs *LinGroupSelect) StringsX(ctx context.Context) []string { - v, err := lgs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lgs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lgs *LinGroupSelect) StringX(ctx context.Context) string { - v, err := lgs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Ints(ctx context.Context) ([]int, error) { - if len(lgs.fields) > 1 { - return nil, errors.New("model: LinGroupSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := lgs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lgs *LinGroupSelect) IntsX(ctx context.Context) []int { - v, err := lgs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lgs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lgs *LinGroupSelect) IntX(ctx context.Context) int { - v, err := lgs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(lgs.fields) > 1 { - return nil, errors.New("model: LinGroupSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := lgs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lgs *LinGroupSelect) Float64sX(ctx context.Context) []float64 { - v, err := lgs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lgs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lgs *LinGroupSelect) Float64X(ctx context.Context) float64 { - v, err := lgs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Bools(ctx context.Context) ([]bool, error) { - if len(lgs.fields) > 1 { - return nil, errors.New("model: LinGroupSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := lgs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lgs *LinGroupSelect) BoolsX(ctx context.Context) []bool { - v, err := lgs.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (lgs *LinGroupSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lgs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingroup.Label} - default: - err = fmt.Errorf("model: LinGroupSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lgs *LinGroupSelect) BoolX(ctx context.Context) bool { - v, err := lgs.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lgs *LinGroupSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := lgs.sql.Query() - if err := lgs.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/lingroup_update.go b/internal/data/model/lingroup_update.go deleted file mode 100644 index 09bd286..0000000 --- a/internal/data/model/lingroup_update.go +++ /dev/null @@ -1,706 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupUpdate is the builder for updating LinGroup entities. -type LinGroupUpdate struct { - config - hooks []Hook - mutation *LinGroupMutation -} - -// Where appends a list predicates to the LinGroupUpdate builder. -func (lgu *LinGroupUpdate) Where(ps ...predicate.LinGroup) *LinGroupUpdate { - lgu.mutation.Where(ps...) - return lgu -} - -// SetName sets the "name" field. -func (lgu *LinGroupUpdate) SetName(s string) *LinGroupUpdate { - lgu.mutation.SetName(s) - return lgu -} - -// SetInfo sets the "info" field. -func (lgu *LinGroupUpdate) SetInfo(s string) *LinGroupUpdate { - lgu.mutation.SetInfo(s) - return lgu -} - -// SetLevel sets the "level" field. -func (lgu *LinGroupUpdate) SetLevel(i int8) *LinGroupUpdate { - lgu.mutation.ResetLevel() - lgu.mutation.SetLevel(i) - return lgu -} - -// AddLevel adds i to the "level" field. -func (lgu *LinGroupUpdate) AddLevel(i int8) *LinGroupUpdate { - lgu.mutation.AddLevel(i) - return lgu -} - -// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. -func (lgu *LinGroupUpdate) AddLinUserIDs(ids ...int) *LinGroupUpdate { - lgu.mutation.AddLinUserIDs(ids...) - return lgu -} - -// AddLinUser adds the "lin_user" edges to the LinUser entity. -func (lgu *LinGroupUpdate) AddLinUser(l ...*LinUser) *LinGroupUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lgu.AddLinUserIDs(ids...) -} - -// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. -func (lgu *LinGroupUpdate) AddLinPermissionIDs(ids ...int) *LinGroupUpdate { - lgu.mutation.AddLinPermissionIDs(ids...) - return lgu -} - -// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. -func (lgu *LinGroupUpdate) AddLinPermission(l ...*LinPermission) *LinGroupUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lgu.AddLinPermissionIDs(ids...) -} - -// Mutation returns the LinGroupMutation object of the builder. -func (lgu *LinGroupUpdate) Mutation() *LinGroupMutation { - return lgu.mutation -} - -// ClearLinUser clears all "lin_user" edges to the LinUser entity. -func (lgu *LinGroupUpdate) ClearLinUser() *LinGroupUpdate { - lgu.mutation.ClearLinUser() - return lgu -} - -// RemoveLinUserIDs removes the "lin_user" edge to LinUser entities by IDs. -func (lgu *LinGroupUpdate) RemoveLinUserIDs(ids ...int) *LinGroupUpdate { - lgu.mutation.RemoveLinUserIDs(ids...) - return lgu -} - -// RemoveLinUser removes "lin_user" edges to LinUser entities. -func (lgu *LinGroupUpdate) RemoveLinUser(l ...*LinUser) *LinGroupUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lgu.RemoveLinUserIDs(ids...) -} - -// ClearLinPermission clears all "lin_permission" edges to the LinPermission entity. -func (lgu *LinGroupUpdate) ClearLinPermission() *LinGroupUpdate { - lgu.mutation.ClearLinPermission() - return lgu -} - -// RemoveLinPermissionIDs removes the "lin_permission" edge to LinPermission entities by IDs. -func (lgu *LinGroupUpdate) RemoveLinPermissionIDs(ids ...int) *LinGroupUpdate { - lgu.mutation.RemoveLinPermissionIDs(ids...) - return lgu -} - -// RemoveLinPermission removes "lin_permission" edges to LinPermission entities. -func (lgu *LinGroupUpdate) RemoveLinPermission(l ...*LinPermission) *LinGroupUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lgu.RemoveLinPermissionIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (lgu *LinGroupUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lgu.hooks) == 0 { - affected, err = lgu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lgu.mutation = mutation - affected, err = lgu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(lgu.hooks) - 1; i >= 0; i-- { - if lgu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lgu *LinGroupUpdate) SaveX(ctx context.Context) int { - affected, err := lgu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (lgu *LinGroupUpdate) Exec(ctx context.Context) error { - _, err := lgu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgu *LinGroupUpdate) ExecX(ctx context.Context) { - if err := lgu.Exec(ctx); err != nil { - panic(err) - } -} - -func (lgu *LinGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingroup.Table, - Columns: lingroup.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - if ps := lgu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lgu.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: lingroup.FieldName, - }) - } - if value, ok := lgu.mutation.Info(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: lingroup.FieldInfo, - }) - } - if value, ok := lgu.mutation.Level(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: lingroup.FieldLevel, - }) - } - if value, ok := lgu.mutation.AddedLevel(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: lingroup.FieldLevel, - }) - } - if lgu.mutation.LinUserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lgu.mutation.RemovedLinUserIDs(); len(nodes) > 0 && !lgu.mutation.LinUserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lgu.mutation.LinUserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if lgu.mutation.LinPermissionCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lgu.mutation.RemovedLinPermissionIDs(); len(nodes) > 0 && !lgu.mutation.LinPermissionCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lgu.mutation.LinPermissionIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if n, err = sqlgraph.UpdateNodes(ctx, lgu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{lingroup.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinGroupUpdateOne is the builder for updating a single LinGroup entity. -type LinGroupUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinGroupMutation -} - -// SetName sets the "name" field. -func (lguo *LinGroupUpdateOne) SetName(s string) *LinGroupUpdateOne { - lguo.mutation.SetName(s) - return lguo -} - -// SetInfo sets the "info" field. -func (lguo *LinGroupUpdateOne) SetInfo(s string) *LinGroupUpdateOne { - lguo.mutation.SetInfo(s) - return lguo -} - -// SetLevel sets the "level" field. -func (lguo *LinGroupUpdateOne) SetLevel(i int8) *LinGroupUpdateOne { - lguo.mutation.ResetLevel() - lguo.mutation.SetLevel(i) - return lguo -} - -// AddLevel adds i to the "level" field. -func (lguo *LinGroupUpdateOne) AddLevel(i int8) *LinGroupUpdateOne { - lguo.mutation.AddLevel(i) - return lguo -} - -// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. -func (lguo *LinGroupUpdateOne) AddLinUserIDs(ids ...int) *LinGroupUpdateOne { - lguo.mutation.AddLinUserIDs(ids...) - return lguo -} - -// AddLinUser adds the "lin_user" edges to the LinUser entity. -func (lguo *LinGroupUpdateOne) AddLinUser(l ...*LinUser) *LinGroupUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lguo.AddLinUserIDs(ids...) -} - -// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. -func (lguo *LinGroupUpdateOne) AddLinPermissionIDs(ids ...int) *LinGroupUpdateOne { - lguo.mutation.AddLinPermissionIDs(ids...) - return lguo -} - -// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. -func (lguo *LinGroupUpdateOne) AddLinPermission(l ...*LinPermission) *LinGroupUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lguo.AddLinPermissionIDs(ids...) -} - -// Mutation returns the LinGroupMutation object of the builder. -func (lguo *LinGroupUpdateOne) Mutation() *LinGroupMutation { - return lguo.mutation -} - -// ClearLinUser clears all "lin_user" edges to the LinUser entity. -func (lguo *LinGroupUpdateOne) ClearLinUser() *LinGroupUpdateOne { - lguo.mutation.ClearLinUser() - return lguo -} - -// RemoveLinUserIDs removes the "lin_user" edge to LinUser entities by IDs. -func (lguo *LinGroupUpdateOne) RemoveLinUserIDs(ids ...int) *LinGroupUpdateOne { - lguo.mutation.RemoveLinUserIDs(ids...) - return lguo -} - -// RemoveLinUser removes "lin_user" edges to LinUser entities. -func (lguo *LinGroupUpdateOne) RemoveLinUser(l ...*LinUser) *LinGroupUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lguo.RemoveLinUserIDs(ids...) -} - -// ClearLinPermission clears all "lin_permission" edges to the LinPermission entity. -func (lguo *LinGroupUpdateOne) ClearLinPermission() *LinGroupUpdateOne { - lguo.mutation.ClearLinPermission() - return lguo -} - -// RemoveLinPermissionIDs removes the "lin_permission" edge to LinPermission entities by IDs. -func (lguo *LinGroupUpdateOne) RemoveLinPermissionIDs(ids ...int) *LinGroupUpdateOne { - lguo.mutation.RemoveLinPermissionIDs(ids...) - return lguo -} - -// RemoveLinPermission removes "lin_permission" edges to LinPermission entities. -func (lguo *LinGroupUpdateOne) RemoveLinPermission(l ...*LinPermission) *LinGroupUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lguo.RemoveLinPermissionIDs(ids...) -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (lguo *LinGroupUpdateOne) Select(field string, fields ...string) *LinGroupUpdateOne { - lguo.fields = append([]string{field}, fields...) - return lguo -} - -// Save executes the query and returns the updated LinGroup entity. -func (lguo *LinGroupUpdateOne) Save(ctx context.Context) (*LinGroup, error) { - var ( - err error - node *LinGroup - ) - if len(lguo.hooks) == 0 { - node, err = lguo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lguo.mutation = mutation - node, err = lguo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(lguo.hooks) - 1; i >= 0; i-- { - if lguo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lguo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lguo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lguo *LinGroupUpdateOne) SaveX(ctx context.Context) *LinGroup { - node, err := lguo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (lguo *LinGroupUpdateOne) Exec(ctx context.Context) error { - _, err := lguo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lguo *LinGroupUpdateOne) ExecX(ctx context.Context) { - if err := lguo.Exec(ctx); err != nil { - panic(err) - } -} - -func (lguo *LinGroupUpdateOne) sqlSave(ctx context.Context) (_node *LinGroup, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingroup.Table, - Columns: lingroup.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - id, ok := lguo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinGroup.ID for update")} - } - _spec.Node.ID.Value = id - if fields := lguo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, lingroup.FieldID) - for _, f := range fields { - if !lingroup.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != lingroup.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := lguo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lguo.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: lingroup.FieldName, - }) - } - if value, ok := lguo.mutation.Info(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: lingroup.FieldInfo, - }) - } - if value, ok := lguo.mutation.Level(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: lingroup.FieldLevel, - }) - } - if value, ok := lguo.mutation.AddedLevel(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: lingroup.FieldLevel, - }) - } - if lguo.mutation.LinUserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lguo.mutation.RemovedLinUserIDs(); len(nodes) > 0 && !lguo.mutation.LinUserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lguo.mutation.LinUserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: lingroup.LinUserTable, - Columns: lingroup.LinUserPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if lguo.mutation.LinPermissionCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lguo.mutation.RemovedLinPermissionIDs(); len(nodes) > 0 && !lguo.mutation.LinPermissionCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lguo.mutation.LinPermissionIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: lingroup.LinPermissionTable, - Columns: lingroup.LinPermissionPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &LinGroup{config: lguo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, lguo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{lingroup.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/lingrouppermission.go b/internal/data/model/lingrouppermission.go deleted file mode 100644 index 2bd8941..0000000 --- a/internal/data/model/lingrouppermission.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/lingrouppermission" - "strings" - - "entgo.io/ent/dialect/sql" -) - -// LinGroupPermission is the model entity for the LinGroupPermission schema. -type LinGroupPermission struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // GroupID holds the value of the "group_id" field. - // 分组id - GroupID int `json:"group_id,omitempty"` - // PermissionID holds the value of the "permission_id" field. - // 权限id - PermissionID int `json:"permission_id,omitempty"` -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinGroupPermission) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case lingrouppermission.FieldID, lingrouppermission.FieldGroupID, lingrouppermission.FieldPermissionID: - values[i] = new(sql.NullInt64) - default: - return nil, fmt.Errorf("unexpected column %q for type LinGroupPermission", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinGroupPermission fields. -func (lgp *LinGroupPermission) assignValues(columns []string, values []interface{}) 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 lingrouppermission.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - lgp.ID = int(value.Int64) - case lingrouppermission.FieldGroupID: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field group_id", values[i]) - } else if value.Valid { - lgp.GroupID = int(value.Int64) - } - case lingrouppermission.FieldPermissionID: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field permission_id", values[i]) - } else if value.Valid { - lgp.PermissionID = int(value.Int64) - } - } - } - return nil -} - -// Update returns a builder for updating this LinGroupPermission. -// Note that you need to call LinGroupPermission.Unwrap() before calling this method if this LinGroupPermission -// was returned from a transaction, and the transaction was committed or rolled back. -func (lgp *LinGroupPermission) Update() *LinGroupPermissionUpdateOne { - return (&LinGroupPermissionClient{config: lgp.config}).UpdateOne(lgp) -} - -// Unwrap unwraps the LinGroupPermission 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 (lgp *LinGroupPermission) Unwrap() *LinGroupPermission { - tx, ok := lgp.config.driver.(*txDriver) - if !ok { - panic("model: LinGroupPermission is not a transactional entity") - } - lgp.config.driver = tx.drv - return lgp -} - -// String implements the fmt.Stringer. -func (lgp *LinGroupPermission) String() string { - var builder strings.Builder - builder.WriteString("LinGroupPermission(") - builder.WriteString(fmt.Sprintf("id=%v", lgp.ID)) - builder.WriteString(", group_id=") - builder.WriteString(fmt.Sprintf("%v", lgp.GroupID)) - builder.WriteString(", permission_id=") - builder.WriteString(fmt.Sprintf("%v", lgp.PermissionID)) - builder.WriteByte(')') - return builder.String() -} - -// LinGroupPermissions is a parsable slice of LinGroupPermission. -type LinGroupPermissions []*LinGroupPermission - -func (lgp LinGroupPermissions) config(cfg config) { - for _i := range lgp { - lgp[_i].config = cfg - } -} diff --git a/internal/data/model/lingrouppermission/lingrouppermission.go b/internal/data/model/lingrouppermission/lingrouppermission.go deleted file mode 100644 index 9257779..0000000 --- a/internal/data/model/lingrouppermission/lingrouppermission.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package lingrouppermission - -const ( - // Label holds the string label denoting the lingrouppermission type in the database. - Label = "lin_group_permission" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldGroupID holds the string denoting the group_id field in the database. - FieldGroupID = "group_id" - // FieldPermissionID holds the string denoting the permission_id field in the database. - FieldPermissionID = "permission_id" - // Table holds the table name of the lingrouppermission in the database. - Table = "lin_group_permission" -) - -// Columns holds all SQL columns for lingrouppermission fields. -var Columns = []string{ - FieldID, - FieldGroupID, - FieldPermissionID, -} - -// 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 -} diff --git a/internal/data/model/lingrouppermission/where.go b/internal/data/model/lingrouppermission/where.go deleted file mode 100644 index 9b1496a..0000000 --- a/internal/data/model/lingrouppermission/where.go +++ /dev/null @@ -1,290 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package lingrouppermission - -import ( - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ. -func GroupID(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldGroupID), v)) - }) -} - -// PermissionID applies equality check predicate on the "permission_id" field. It's identical to PermissionIDEQ. -func PermissionID(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPermissionID), v)) - }) -} - -// GroupIDEQ applies the EQ predicate on the "group_id" field. -func GroupIDEQ(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldGroupID), v)) - }) -} - -// GroupIDNEQ applies the NEQ predicate on the "group_id" field. -func GroupIDNEQ(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldGroupID), v)) - }) -} - -// GroupIDIn applies the In predicate on the "group_id" field. -func GroupIDIn(vs ...int) predicate.LinGroupPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroupPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldGroupID), v...)) - }) -} - -// GroupIDNotIn applies the NotIn predicate on the "group_id" field. -func GroupIDNotIn(vs ...int) predicate.LinGroupPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroupPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldGroupID), v...)) - }) -} - -// GroupIDGT applies the GT predicate on the "group_id" field. -func GroupIDGT(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldGroupID), v)) - }) -} - -// GroupIDGTE applies the GTE predicate on the "group_id" field. -func GroupIDGTE(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldGroupID), v)) - }) -} - -// GroupIDLT applies the LT predicate on the "group_id" field. -func GroupIDLT(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldGroupID), v)) - }) -} - -// GroupIDLTE applies the LTE predicate on the "group_id" field. -func GroupIDLTE(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldGroupID), v)) - }) -} - -// PermissionIDEQ applies the EQ predicate on the "permission_id" field. -func PermissionIDEQ(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPermissionID), v)) - }) -} - -// PermissionIDNEQ applies the NEQ predicate on the "permission_id" field. -func PermissionIDNEQ(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldPermissionID), v)) - }) -} - -// PermissionIDIn applies the In predicate on the "permission_id" field. -func PermissionIDIn(vs ...int) predicate.LinGroupPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroupPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldPermissionID), v...)) - }) -} - -// PermissionIDNotIn applies the NotIn predicate on the "permission_id" field. -func PermissionIDNotIn(vs ...int) predicate.LinGroupPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinGroupPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldPermissionID), v...)) - }) -} - -// PermissionIDGT applies the GT predicate on the "permission_id" field. -func PermissionIDGT(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldPermissionID), v)) - }) -} - -// PermissionIDGTE applies the GTE predicate on the "permission_id" field. -func PermissionIDGTE(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldPermissionID), v)) - }) -} - -// PermissionIDLT applies the LT predicate on the "permission_id" field. -func PermissionIDLT(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldPermissionID), v)) - }) -} - -// PermissionIDLTE applies the LTE predicate on the "permission_id" field. -func PermissionIDLTE(v int) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldPermissionID), v)) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.LinGroupPermission) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinGroupPermission) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinGroupPermission) predicate.LinGroupPermission { - return predicate.LinGroupPermission(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/lingrouppermission_create.go b/internal/data/model/lingrouppermission_create.go deleted file mode 100644 index 25caf8f..0000000 --- a/internal/data/model/lingrouppermission_create.go +++ /dev/null @@ -1,237 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingrouppermission" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupPermissionCreate is the builder for creating a LinGroupPermission entity. -type LinGroupPermissionCreate struct { - config - mutation *LinGroupPermissionMutation - hooks []Hook -} - -// SetGroupID sets the "group_id" field. -func (lgpc *LinGroupPermissionCreate) SetGroupID(i int) *LinGroupPermissionCreate { - lgpc.mutation.SetGroupID(i) - return lgpc -} - -// SetPermissionID sets the "permission_id" field. -func (lgpc *LinGroupPermissionCreate) SetPermissionID(i int) *LinGroupPermissionCreate { - lgpc.mutation.SetPermissionID(i) - return lgpc -} - -// Mutation returns the LinGroupPermissionMutation object of the builder. -func (lgpc *LinGroupPermissionCreate) Mutation() *LinGroupPermissionMutation { - return lgpc.mutation -} - -// Save creates the LinGroupPermission in the database. -func (lgpc *LinGroupPermissionCreate) Save(ctx context.Context) (*LinGroupPermission, error) { - var ( - err error - node *LinGroupPermission - ) - if len(lgpc.hooks) == 0 { - if err = lgpc.check(); err != nil { - return nil, err - } - node, err = lgpc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = lgpc.check(); err != nil { - return nil, err - } - lgpc.mutation = mutation - if node, err = lgpc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(lgpc.hooks) - 1; i >= 0; i-- { - if lgpc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgpc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgpc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (lgpc *LinGroupPermissionCreate) SaveX(ctx context.Context) *LinGroupPermission { - v, err := lgpc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lgpc *LinGroupPermissionCreate) Exec(ctx context.Context) error { - _, err := lgpc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgpc *LinGroupPermissionCreate) ExecX(ctx context.Context) { - if err := lgpc.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (lgpc *LinGroupPermissionCreate) check() error { - if _, ok := lgpc.mutation.GroupID(); !ok { - return &ValidationError{Name: "group_id", err: errors.New(`model: missing required field "group_id"`)} - } - if _, ok := lgpc.mutation.PermissionID(); !ok { - return &ValidationError{Name: "permission_id", err: errors.New(`model: missing required field "permission_id"`)} - } - return nil -} - -func (lgpc *LinGroupPermissionCreate) sqlSave(ctx context.Context) (*LinGroupPermission, error) { - _node, _spec := lgpc.createSpec() - if err := sqlgraph.CreateNode(ctx, lgpc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (lgpc *LinGroupPermissionCreate) createSpec() (*LinGroupPermission, *sqlgraph.CreateSpec) { - var ( - _node = &LinGroupPermission{config: lgpc.config} - _spec = &sqlgraph.CreateSpec{ - Table: lingrouppermission.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingrouppermission.FieldID, - }, - } - ) - if value, ok := lgpc.mutation.GroupID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldGroupID, - }) - _node.GroupID = value - } - if value, ok := lgpc.mutation.PermissionID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldPermissionID, - }) - _node.PermissionID = value - } - return _node, _spec -} - -// LinGroupPermissionCreateBulk is the builder for creating many LinGroupPermission entities in bulk. -type LinGroupPermissionCreateBulk struct { - config - builders []*LinGroupPermissionCreate -} - -// Save creates the LinGroupPermission entities in the database. -func (lgpcb *LinGroupPermissionCreateBulk) Save(ctx context.Context) ([]*LinGroupPermission, error) { - specs := make([]*sqlgraph.CreateSpec, len(lgpcb.builders)) - nodes := make([]*LinGroupPermission, len(lgpcb.builders)) - mutators := make([]Mutator, len(lgpcb.builders)) - for i := range lgpcb.builders { - func(i int, root context.Context) { - builder := lgpcb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, lgpcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, lgpcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, lgpcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (lgpcb *LinGroupPermissionCreateBulk) SaveX(ctx context.Context) []*LinGroupPermission { - v, err := lgpcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lgpcb *LinGroupPermissionCreateBulk) Exec(ctx context.Context) error { - _, err := lgpcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgpcb *LinGroupPermissionCreateBulk) ExecX(ctx context.Context) { - if err := lgpcb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/lingrouppermission_delete.go b/internal/data/model/lingrouppermission_delete.go deleted file mode 100644 index ec23705..0000000 --- a/internal/data/model/lingrouppermission_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/lingrouppermission" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupPermissionDelete is the builder for deleting a LinGroupPermission entity. -type LinGroupPermissionDelete struct { - config - hooks []Hook - mutation *LinGroupPermissionMutation -} - -// Where appends a list predicates to the LinGroupPermissionDelete builder. -func (lgpd *LinGroupPermissionDelete) Where(ps ...predicate.LinGroupPermission) *LinGroupPermissionDelete { - lgpd.mutation.Where(ps...) - return lgpd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (lgpd *LinGroupPermissionDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lgpd.hooks) == 0 { - affected, err = lgpd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lgpd.mutation = mutation - affected, err = lgpd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(lgpd.hooks) - 1; i >= 0; i-- { - if lgpd.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgpd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgpd.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgpd *LinGroupPermissionDelete) ExecX(ctx context.Context) int { - n, err := lgpd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (lgpd *LinGroupPermissionDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingrouppermission.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingrouppermission.FieldID, - }, - }, - } - if ps := lgpd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, lgpd.driver, _spec) -} - -// LinGroupPermissionDeleteOne is the builder for deleting a single LinGroupPermission entity. -type LinGroupPermissionDeleteOne struct { - lgpd *LinGroupPermissionDelete -} - -// Exec executes the deletion query. -func (lgpdo *LinGroupPermissionDeleteOne) Exec(ctx context.Context) error { - n, err := lgpdo.lgpd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{lingrouppermission.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgpdo *LinGroupPermissionDeleteOne) ExecX(ctx context.Context) { - lgpdo.lgpd.ExecX(ctx) -} diff --git a/internal/data/model/lingrouppermission_query.go b/internal/data/model/lingrouppermission_query.go deleted file mode 100644 index abfdc86..0000000 --- a/internal/data/model/lingrouppermission_query.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingrouppermission" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupPermissionQuery is the builder for querying LinGroupPermission entities. -type LinGroupPermissionQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinGroupPermission - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinGroupPermissionQuery builder. -func (lgpq *LinGroupPermissionQuery) Where(ps ...predicate.LinGroupPermission) *LinGroupPermissionQuery { - lgpq.predicates = append(lgpq.predicates, ps...) - return lgpq -} - -// Limit adds a limit step to the query. -func (lgpq *LinGroupPermissionQuery) Limit(limit int) *LinGroupPermissionQuery { - lgpq.limit = &limit - return lgpq -} - -// Offset adds an offset step to the query. -func (lgpq *LinGroupPermissionQuery) Offset(offset int) *LinGroupPermissionQuery { - lgpq.offset = &offset - return lgpq -} - -// 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 (lgpq *LinGroupPermissionQuery) Unique(unique bool) *LinGroupPermissionQuery { - lgpq.unique = &unique - return lgpq -} - -// Order adds an order step to the query. -func (lgpq *LinGroupPermissionQuery) Order(o ...OrderFunc) *LinGroupPermissionQuery { - lgpq.order = append(lgpq.order, o...) - return lgpq -} - -// First returns the first LinGroupPermission entity from the query. -// Returns a *NotFoundError when no LinGroupPermission was found. -func (lgpq *LinGroupPermissionQuery) First(ctx context.Context) (*LinGroupPermission, error) { - nodes, err := lgpq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{lingrouppermission.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) FirstX(ctx context.Context) *LinGroupPermission { - node, err := lgpq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinGroupPermission ID from the query. -// Returns a *NotFoundError when no LinGroupPermission ID was found. -func (lgpq *LinGroupPermissionQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lgpq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{lingrouppermission.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) FirstIDX(ctx context.Context) int { - id, err := lgpq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinGroupPermission entity from the query. -// Returns a *NotFoundError when no LinGroupPermission was found. -func (lgpq *LinGroupPermissionQuery) Last(ctx context.Context) (*LinGroupPermission, error) { - nodes, err := lgpq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{lingrouppermission.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) LastX(ctx context.Context) *LinGroupPermission { - node, err := lgpq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinGroupPermission ID from the query. -// Returns a *NotFoundError when no LinGroupPermission ID was found. -func (lgpq *LinGroupPermissionQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lgpq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{lingrouppermission.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) LastIDX(ctx context.Context) int { - id, err := lgpq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinGroupPermission entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinGroupPermission entity is not found. -// Returns a *NotFoundError when no LinGroupPermission entities are found. -func (lgpq *LinGroupPermissionQuery) Only(ctx context.Context) (*LinGroupPermission, error) { - nodes, err := lgpq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{lingrouppermission.Label} - default: - return nil, &NotSingularError{lingrouppermission.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) OnlyX(ctx context.Context) *LinGroupPermission { - node, err := lgpq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinGroupPermission ID in the query. -// Returns a *NotSingularError when exactly one LinGroupPermission ID is not found. -// Returns a *NotFoundError when no entities are found. -func (lgpq *LinGroupPermissionQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lgpq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = &NotSingularError{lingrouppermission.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) OnlyIDX(ctx context.Context) int { - id, err := lgpq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinGroupPermissions. -func (lgpq *LinGroupPermissionQuery) All(ctx context.Context) ([]*LinGroupPermission, error) { - if err := lgpq.prepareQuery(ctx); err != nil { - return nil, err - } - return lgpq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) AllX(ctx context.Context) []*LinGroupPermission { - nodes, err := lgpq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinGroupPermission IDs. -func (lgpq *LinGroupPermissionQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := lgpq.Select(lingrouppermission.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) IDsX(ctx context.Context) []int { - ids, err := lgpq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (lgpq *LinGroupPermissionQuery) Count(ctx context.Context) (int, error) { - if err := lgpq.prepareQuery(ctx); err != nil { - return 0, err - } - return lgpq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) CountX(ctx context.Context) int { - count, err := lgpq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (lgpq *LinGroupPermissionQuery) Exist(ctx context.Context) (bool, error) { - if err := lgpq.prepareQuery(ctx); err != nil { - return false, err - } - return lgpq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (lgpq *LinGroupPermissionQuery) ExistX(ctx context.Context) bool { - exist, err := lgpq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinGroupPermissionQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (lgpq *LinGroupPermissionQuery) Clone() *LinGroupPermissionQuery { - if lgpq == nil { - return nil - } - return &LinGroupPermissionQuery{ - config: lgpq.config, - limit: lgpq.limit, - offset: lgpq.offset, - order: append([]OrderFunc{}, lgpq.order...), - predicates: append([]predicate.LinGroupPermission{}, lgpq.predicates...), - // clone intermediate query. - sql: lgpq.sql.Clone(), - path: lgpq.path, - } -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// GroupID int `json:"group_id,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinGroupPermission.Query(). -// GroupBy(lingrouppermission.FieldGroupID). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (lgpq *LinGroupPermissionQuery) GroupBy(field string, fields ...string) *LinGroupPermissionGroupBy { - group := &LinGroupPermissionGroupBy{config: lgpq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := lgpq.prepareQuery(ctx); err != nil { - return nil, err - } - return lgpq.sqlQuery(ctx), nil - } - return group -} - -// 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 { -// GroupID int `json:"group_id,omitempty"` -// } -// -// client.LinGroupPermission.Query(). -// Select(lingrouppermission.FieldGroupID). -// Scan(ctx, &v) -// -func (lgpq *LinGroupPermissionQuery) Select(fields ...string) *LinGroupPermissionSelect { - lgpq.fields = append(lgpq.fields, fields...) - return &LinGroupPermissionSelect{LinGroupPermissionQuery: lgpq} -} - -func (lgpq *LinGroupPermissionQuery) prepareQuery(ctx context.Context) error { - for _, f := range lgpq.fields { - if !lingrouppermission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if lgpq.path != nil { - prev, err := lgpq.path(ctx) - if err != nil { - return err - } - lgpq.sql = prev - } - return nil -} - -func (lgpq *LinGroupPermissionQuery) sqlAll(ctx context.Context) ([]*LinGroupPermission, error) { - var ( - nodes = []*LinGroupPermission{} - _spec = lgpq.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinGroupPermission{config: lgpq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, lgpq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (lgpq *LinGroupPermissionQuery) sqlCount(ctx context.Context) (int, error) { - _spec := lgpq.querySpec() - return sqlgraph.CountNodes(ctx, lgpq.driver, _spec) -} - -func (lgpq *LinGroupPermissionQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := lgpq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (lgpq *LinGroupPermissionQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingrouppermission.Table, - Columns: lingrouppermission.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingrouppermission.FieldID, - }, - }, - From: lgpq.sql, - Unique: true, - } - if unique := lgpq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := lgpq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, lingrouppermission.FieldID) - for i := range fields { - if fields[i] != lingrouppermission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := lgpq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := lgpq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := lgpq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := lgpq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (lgpq *LinGroupPermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(lgpq.driver.Dialect()) - t1 := builder.Table(lingrouppermission.Table) - columns := lgpq.fields - if len(columns) == 0 { - columns = lingrouppermission.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if lgpq.sql != nil { - selector = lgpq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range lgpq.predicates { - p(selector) - } - for _, p := range lgpq.order { - p(selector) - } - if offset := lgpq.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 := lgpq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinGroupPermissionGroupBy is the group-by builder for LinGroupPermission entities. -type LinGroupPermissionGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (lgpgb *LinGroupPermissionGroupBy) Aggregate(fns ...AggregateFunc) *LinGroupPermissionGroupBy { - lgpgb.fns = append(lgpgb.fns, fns...) - return lgpgb -} - -// Scan applies the group-by query and scans the result into the given value. -func (lgpgb *LinGroupPermissionGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := lgpgb.path(ctx) - if err != nil { - return err - } - lgpgb.sql = query - return lgpgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := lgpgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(lgpgb.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := lgpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) StringsX(ctx context.Context) []string { - v, err := lgpgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lgpgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) StringX(ctx context.Context) string { - v, err := lgpgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(lgpgb.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := lgpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) IntsX(ctx context.Context) []int { - v, err := lgpgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lgpgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) IntX(ctx context.Context) int { - v, err := lgpgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(lgpgb.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := lgpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := lgpgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lgpgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) Float64X(ctx context.Context) float64 { - v, err := lgpgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(lgpgb.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := lgpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) BoolsX(ctx context.Context) []bool { - v, err := lgpgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lgpgb *LinGroupPermissionGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lgpgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lgpgb *LinGroupPermissionGroupBy) BoolX(ctx context.Context) bool { - v, err := lgpgb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lgpgb *LinGroupPermissionGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range lgpgb.fields { - if !lingrouppermission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := lgpgb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := lgpgb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (lgpgb *LinGroupPermissionGroupBy) sqlQuery() *sql.Selector { - selector := lgpgb.sql.Select() - aggregation := make([]string, 0, len(lgpgb.fns)) - for _, fn := range lgpgb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(lgpgb.fields)+len(lgpgb.fns)) - for _, f := range lgpgb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(lgpgb.fields...)...) -} - -// LinGroupPermissionSelect is the builder for selecting fields of LinGroupPermission entities. -type LinGroupPermissionSelect struct { - *LinGroupPermissionQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (lgps *LinGroupPermissionSelect) Scan(ctx context.Context, v interface{}) error { - if err := lgps.prepareQuery(ctx); err != nil { - return err - } - lgps.sql = lgps.LinGroupPermissionQuery.sqlQuery(ctx) - return lgps.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) ScanX(ctx context.Context, v interface{}) { - if err := lgps.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Strings(ctx context.Context) ([]string, error) { - if len(lgps.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := lgps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) StringsX(ctx context.Context) []string { - v, err := lgps.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lgps.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) StringX(ctx context.Context) string { - v, err := lgps.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Ints(ctx context.Context) ([]int, error) { - if len(lgps.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := lgps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) IntsX(ctx context.Context) []int { - v, err := lgps.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lgps.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) IntX(ctx context.Context) int { - v, err := lgps.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(lgps.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := lgps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) Float64sX(ctx context.Context) []float64 { - v, err := lgps.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lgps.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) Float64X(ctx context.Context) float64 { - v, err := lgps.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Bools(ctx context.Context) ([]bool, error) { - if len(lgps.fields) > 1 { - return nil, errors.New("model: LinGroupPermissionSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := lgps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) BoolsX(ctx context.Context) []bool { - v, err := lgps.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (lgps *LinGroupPermissionSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lgps.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{lingrouppermission.Label} - default: - err = fmt.Errorf("model: LinGroupPermissionSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lgps *LinGroupPermissionSelect) BoolX(ctx context.Context) bool { - v, err := lgps.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lgps *LinGroupPermissionSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := lgps.sql.Query() - if err := lgps.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/lingrouppermission_update.go b/internal/data/model/lingrouppermission_update.go deleted file mode 100644 index 36cc6d5..0000000 --- a/internal/data/model/lingrouppermission_update.go +++ /dev/null @@ -1,346 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/lingrouppermission" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinGroupPermissionUpdate is the builder for updating LinGroupPermission entities. -type LinGroupPermissionUpdate struct { - config - hooks []Hook - mutation *LinGroupPermissionMutation -} - -// Where appends a list predicates to the LinGroupPermissionUpdate builder. -func (lgpu *LinGroupPermissionUpdate) Where(ps ...predicate.LinGroupPermission) *LinGroupPermissionUpdate { - lgpu.mutation.Where(ps...) - return lgpu -} - -// SetGroupID sets the "group_id" field. -func (lgpu *LinGroupPermissionUpdate) SetGroupID(i int) *LinGroupPermissionUpdate { - lgpu.mutation.ResetGroupID() - lgpu.mutation.SetGroupID(i) - return lgpu -} - -// AddGroupID adds i to the "group_id" field. -func (lgpu *LinGroupPermissionUpdate) AddGroupID(i int) *LinGroupPermissionUpdate { - lgpu.mutation.AddGroupID(i) - return lgpu -} - -// SetPermissionID sets the "permission_id" field. -func (lgpu *LinGroupPermissionUpdate) SetPermissionID(i int) *LinGroupPermissionUpdate { - lgpu.mutation.ResetPermissionID() - lgpu.mutation.SetPermissionID(i) - return lgpu -} - -// AddPermissionID adds i to the "permission_id" field. -func (lgpu *LinGroupPermissionUpdate) AddPermissionID(i int) *LinGroupPermissionUpdate { - lgpu.mutation.AddPermissionID(i) - return lgpu -} - -// Mutation returns the LinGroupPermissionMutation object of the builder. -func (lgpu *LinGroupPermissionUpdate) Mutation() *LinGroupPermissionMutation { - return lgpu.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (lgpu *LinGroupPermissionUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lgpu.hooks) == 0 { - affected, err = lgpu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lgpu.mutation = mutation - affected, err = lgpu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(lgpu.hooks) - 1; i >= 0; i-- { - if lgpu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgpu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgpu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lgpu *LinGroupPermissionUpdate) SaveX(ctx context.Context) int { - affected, err := lgpu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (lgpu *LinGroupPermissionUpdate) Exec(ctx context.Context) error { - _, err := lgpu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgpu *LinGroupPermissionUpdate) ExecX(ctx context.Context) { - if err := lgpu.Exec(ctx); err != nil { - panic(err) - } -} - -func (lgpu *LinGroupPermissionUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingrouppermission.Table, - Columns: lingrouppermission.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingrouppermission.FieldID, - }, - }, - } - if ps := lgpu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lgpu.mutation.GroupID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldGroupID, - }) - } - if value, ok := lgpu.mutation.AddedGroupID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldGroupID, - }) - } - if value, ok := lgpu.mutation.PermissionID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldPermissionID, - }) - } - if value, ok := lgpu.mutation.AddedPermissionID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldPermissionID, - }) - } - if n, err = sqlgraph.UpdateNodes(ctx, lgpu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{lingrouppermission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinGroupPermissionUpdateOne is the builder for updating a single LinGroupPermission entity. -type LinGroupPermissionUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinGroupPermissionMutation -} - -// SetGroupID sets the "group_id" field. -func (lgpuo *LinGroupPermissionUpdateOne) SetGroupID(i int) *LinGroupPermissionUpdateOne { - lgpuo.mutation.ResetGroupID() - lgpuo.mutation.SetGroupID(i) - return lgpuo -} - -// AddGroupID adds i to the "group_id" field. -func (lgpuo *LinGroupPermissionUpdateOne) AddGroupID(i int) *LinGroupPermissionUpdateOne { - lgpuo.mutation.AddGroupID(i) - return lgpuo -} - -// SetPermissionID sets the "permission_id" field. -func (lgpuo *LinGroupPermissionUpdateOne) SetPermissionID(i int) *LinGroupPermissionUpdateOne { - lgpuo.mutation.ResetPermissionID() - lgpuo.mutation.SetPermissionID(i) - return lgpuo -} - -// AddPermissionID adds i to the "permission_id" field. -func (lgpuo *LinGroupPermissionUpdateOne) AddPermissionID(i int) *LinGroupPermissionUpdateOne { - lgpuo.mutation.AddPermissionID(i) - return lgpuo -} - -// Mutation returns the LinGroupPermissionMutation object of the builder. -func (lgpuo *LinGroupPermissionUpdateOne) Mutation() *LinGroupPermissionMutation { - return lgpuo.mutation -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (lgpuo *LinGroupPermissionUpdateOne) Select(field string, fields ...string) *LinGroupPermissionUpdateOne { - lgpuo.fields = append([]string{field}, fields...) - return lgpuo -} - -// Save executes the query and returns the updated LinGroupPermission entity. -func (lgpuo *LinGroupPermissionUpdateOne) Save(ctx context.Context) (*LinGroupPermission, error) { - var ( - err error - node *LinGroupPermission - ) - if len(lgpuo.hooks) == 0 { - node, err = lgpuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinGroupPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lgpuo.mutation = mutation - node, err = lgpuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(lgpuo.hooks) - 1; i >= 0; i-- { - if lgpuo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lgpuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lgpuo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lgpuo *LinGroupPermissionUpdateOne) SaveX(ctx context.Context) *LinGroupPermission { - node, err := lgpuo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (lgpuo *LinGroupPermissionUpdateOne) Exec(ctx context.Context) error { - _, err := lgpuo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lgpuo *LinGroupPermissionUpdateOne) ExecX(ctx context.Context) { - if err := lgpuo.Exec(ctx); err != nil { - panic(err) - } -} - -func (lgpuo *LinGroupPermissionUpdateOne) sqlSave(ctx context.Context) (_node *LinGroupPermission, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: lingrouppermission.Table, - Columns: lingrouppermission.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingrouppermission.FieldID, - }, - }, - } - id, ok := lgpuo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinGroupPermission.ID for update")} - } - _spec.Node.ID.Value = id - if fields := lgpuo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, lingrouppermission.FieldID) - for _, f := range fields { - if !lingrouppermission.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != lingrouppermission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := lgpuo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lgpuo.mutation.GroupID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldGroupID, - }) - } - if value, ok := lgpuo.mutation.AddedGroupID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldGroupID, - }) - } - if value, ok := lgpuo.mutation.PermissionID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldPermissionID, - }) - } - if value, ok := lgpuo.mutation.AddedPermissionID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: lingrouppermission.FieldPermissionID, - }) - } - _node = &LinGroupPermission{config: lgpuo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, lgpuo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{lingrouppermission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/linlog.go b/internal/data/model/linlog.go deleted file mode 100644 index 8aa0545..0000000 --- a/internal/data/model/linlog.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/linlog" - "strings" - "time" - - "entgo.io/ent/dialect/sql" -) - -// LinLog is the model entity for the LinLog schema. -type LinLog struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // CreateTime holds the value of the "create_time" field. - CreateTime time.Time `json:"create_time,omitempty"` - // UpdateTime holds the value of the "update_time" field. - UpdateTime time.Time `json:"update_time,omitempty"` - // DeleteTime holds the value of the "delete_time" field. - DeleteTime time.Time `json:"delete_time,omitempty"` - // Message holds the value of the "message" field. - Message string `json:"message,omitempty"` - // UserID holds the value of the "user_id" field. - UserID int `json:"user_id,omitempty"` - // Username holds the value of the "username" field. - Username string `json:"username,omitempty"` - // StatusCode holds the value of the "status_code" field. - StatusCode int `json:"status_code,omitempty"` - // Method holds the value of the "method" field. - Method string `json:"method,omitempty"` - // Path holds the value of the "path" field. - Path string `json:"path,omitempty"` - // Permission holds the value of the "permission" field. - Permission string `json:"permission,omitempty"` -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinLog) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case linlog.FieldID, linlog.FieldUserID, linlog.FieldStatusCode: - values[i] = new(sql.NullInt64) - case linlog.FieldMessage, linlog.FieldUsername, linlog.FieldMethod, linlog.FieldPath, linlog.FieldPermission: - values[i] = new(sql.NullString) - case linlog.FieldCreateTime, linlog.FieldUpdateTime, linlog.FieldDeleteTime: - values[i] = new(sql.NullTime) - default: - return nil, fmt.Errorf("unexpected column %q for type LinLog", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinLog fields. -func (ll *LinLog) assignValues(columns []string, values []interface{}) 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 linlog.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - ll.ID = int(value.Int64) - case linlog.FieldCreateTime: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field create_time", values[i]) - } else if value.Valid { - ll.CreateTime = value.Time - } - case linlog.FieldUpdateTime: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field update_time", values[i]) - } else if value.Valid { - ll.UpdateTime = value.Time - } - case linlog.FieldDeleteTime: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field delete_time", values[i]) - } else if value.Valid { - ll.DeleteTime = value.Time - } - case linlog.FieldMessage: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field message", values[i]) - } else if value.Valid { - ll.Message = value.String - } - case linlog.FieldUserID: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field user_id", values[i]) - } else if value.Valid { - ll.UserID = int(value.Int64) - } - case linlog.FieldUsername: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field username", values[i]) - } else if value.Valid { - ll.Username = value.String - } - case linlog.FieldStatusCode: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field status_code", values[i]) - } else if value.Valid { - ll.StatusCode = int(value.Int64) - } - case linlog.FieldMethod: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field method", values[i]) - } else if value.Valid { - ll.Method = value.String - } - case linlog.FieldPath: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field path", values[i]) - } else if value.Valid { - ll.Path = value.String - } - case linlog.FieldPermission: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field permission", values[i]) - } else if value.Valid { - ll.Permission = value.String - } - } - } - return nil -} - -// Update returns a builder for updating this LinLog. -// Note that you need to call LinLog.Unwrap() before calling this method if this LinLog -// was returned from a transaction, and the transaction was committed or rolled back. -func (ll *LinLog) Update() *LinLogUpdateOne { - return (&LinLogClient{config: ll.config}).UpdateOne(ll) -} - -// Unwrap unwraps the LinLog 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 (ll *LinLog) Unwrap() *LinLog { - tx, ok := ll.config.driver.(*txDriver) - if !ok { - panic("model: LinLog is not a transactional entity") - } - ll.config.driver = tx.drv - return ll -} - -// String implements the fmt.Stringer. -func (ll *LinLog) String() string { - var builder strings.Builder - builder.WriteString("LinLog(") - builder.WriteString(fmt.Sprintf("id=%v", ll.ID)) - builder.WriteString(", create_time=") - builder.WriteString(ll.CreateTime.Format(time.ANSIC)) - builder.WriteString(", update_time=") - builder.WriteString(ll.UpdateTime.Format(time.ANSIC)) - builder.WriteString(", delete_time=") - builder.WriteString(ll.DeleteTime.Format(time.ANSIC)) - builder.WriteString(", message=") - builder.WriteString(ll.Message) - builder.WriteString(", user_id=") - builder.WriteString(fmt.Sprintf("%v", ll.UserID)) - builder.WriteString(", username=") - builder.WriteString(ll.Username) - builder.WriteString(", status_code=") - builder.WriteString(fmt.Sprintf("%v", ll.StatusCode)) - builder.WriteString(", method=") - builder.WriteString(ll.Method) - builder.WriteString(", path=") - builder.WriteString(ll.Path) - builder.WriteString(", permission=") - builder.WriteString(ll.Permission) - builder.WriteByte(')') - return builder.String() -} - -// LinLogs is a parsable slice of LinLog. -type LinLogs []*LinLog - -func (ll LinLogs) config(cfg config) { - for _i := range ll { - ll[_i].config = cfg - } -} diff --git a/internal/data/model/linlog/linlog.go b/internal/data/model/linlog/linlog.go deleted file mode 100644 index 14f4ab7..0000000 --- a/internal/data/model/linlog/linlog.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linlog - -import ( - "time" -) - -const ( - // Label holds the string label denoting the linlog type in the database. - Label = "lin_log" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldCreateTime holds the string denoting the create_time field in the database. - FieldCreateTime = "create_time" - // FieldUpdateTime holds the string denoting the update_time field in the database. - FieldUpdateTime = "update_time" - // FieldDeleteTime holds the string denoting the delete_time field in the database. - FieldDeleteTime = "delete_time" - // FieldMessage holds the string denoting the message field in the database. - FieldMessage = "message" - // FieldUserID holds the string denoting the user_id field in the database. - FieldUserID = "user_id" - // FieldUsername holds the string denoting the username field in the database. - FieldUsername = "username" - // FieldStatusCode holds the string denoting the status_code field in the database. - FieldStatusCode = "status_code" - // FieldMethod holds the string denoting the method field in the database. - FieldMethod = "method" - // FieldPath holds the string denoting the path field in the database. - FieldPath = "path" - // FieldPermission holds the string denoting the permission field in the database. - FieldPermission = "permission" - // Table holds the table name of the linlog in the database. - Table = "lin_log" -) - -// Columns holds all SQL columns for linlog fields. -var Columns = []string{ - FieldID, - FieldCreateTime, - FieldUpdateTime, - FieldDeleteTime, - FieldMessage, - FieldUserID, - FieldUsername, - FieldStatusCode, - FieldMethod, - FieldPath, - FieldPermission, -} - -// 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 ( - // DefaultCreateTime holds the default value on creation for the "create_time" field. - DefaultCreateTime func() time.Time - // DefaultUpdateTime holds the default value on creation for the "update_time" field. - DefaultUpdateTime func() time.Time - // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. - UpdateDefaultUpdateTime func() time.Time - // DefaultDeleteTime holds the default value on creation for the "delete_time" field. - DefaultDeleteTime func() time.Time -) diff --git a/internal/data/model/linlog/where.go b/internal/data/model/linlog/where.go deleted file mode 100644 index c877f50..0000000 --- a/internal/data/model/linlog/where.go +++ /dev/null @@ -1,1130 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linlog - -import ( - "lin-cms-go/internal/data/model/predicate" - "time" - - "entgo.io/ent/dialect/sql" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. -func CreateTime(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCreateTime), v)) - }) -} - -// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. -func UpdateTime(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUpdateTime), v)) - }) -} - -// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. -func DeleteTime(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldDeleteTime), v)) - }) -} - -// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. -func Message(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMessage), v)) - }) -} - -// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. -func UserID(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUserID), v)) - }) -} - -// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. -func Username(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUsername), v)) - }) -} - -// StatusCode applies equality check predicate on the "status_code" field. It's identical to StatusCodeEQ. -func StatusCode(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStatusCode), v)) - }) -} - -// Method applies equality check predicate on the "method" field. It's identical to MethodEQ. -func Method(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMethod), v)) - }) -} - -// Path applies equality check predicate on the "path" field. It's identical to PathEQ. -func Path(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPath), v)) - }) -} - -// Permission applies equality check predicate on the "permission" field. It's identical to PermissionEQ. -func Permission(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPermission), v)) - }) -} - -// CreateTimeEQ applies the EQ predicate on the "create_time" field. -func CreateTimeEQ(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. -func CreateTimeNEQ(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeIn applies the In predicate on the "create_time" field. -func CreateTimeIn(vs ...time.Time) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldCreateTime), v...)) - }) -} - -// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. -func CreateTimeNotIn(vs ...time.Time) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) - }) -} - -// CreateTimeGT applies the GT predicate on the "create_time" field. -func CreateTimeGT(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeGTE applies the GTE predicate on the "create_time" field. -func CreateTimeGTE(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeLT applies the LT predicate on the "create_time" field. -func CreateTimeLT(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeLTE applies the LTE predicate on the "create_time" field. -func CreateTimeLTE(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldCreateTime), v)) - }) -} - -// UpdateTimeEQ applies the EQ predicate on the "update_time" field. -func UpdateTimeEQ(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. -func UpdateTimeNEQ(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeIn applies the In predicate on the "update_time" field. -func UpdateTimeIn(vs ...time.Time) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUpdateTime), v...)) - }) -} - -// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. -func UpdateTimeNotIn(vs ...time.Time) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) - }) -} - -// UpdateTimeGT applies the GT predicate on the "update_time" field. -func UpdateTimeGT(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeGTE applies the GTE predicate on the "update_time" field. -func UpdateTimeGTE(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeLT applies the LT predicate on the "update_time" field. -func UpdateTimeLT(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeLTE applies the LTE predicate on the "update_time" field. -func UpdateTimeLTE(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUpdateTime), v)) - }) -} - -// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. -func DeleteTimeEQ(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. -func DeleteTimeNEQ(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeIn applies the In predicate on the "delete_time" field. -func DeleteTimeIn(vs ...time.Time) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldDeleteTime), v...)) - }) -} - -// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. -func DeleteTimeNotIn(vs ...time.Time) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) - }) -} - -// DeleteTimeGT applies the GT predicate on the "delete_time" field. -func DeleteTimeGT(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. -func DeleteTimeGTE(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeLT applies the LT predicate on the "delete_time" field. -func DeleteTimeLT(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. -func DeleteTimeLTE(v time.Time) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldDeleteTime), v)) - }) -} - -// MessageEQ applies the EQ predicate on the "message" field. -func MessageEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMessage), v)) - }) -} - -// MessageNEQ applies the NEQ predicate on the "message" field. -func MessageNEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMessage), v)) - }) -} - -// MessageIn applies the In predicate on the "message" field. -func MessageIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMessage), v...)) - }) -} - -// MessageNotIn applies the NotIn predicate on the "message" field. -func MessageNotIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMessage), v...)) - }) -} - -// MessageGT applies the GT predicate on the "message" field. -func MessageGT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMessage), v)) - }) -} - -// MessageGTE applies the GTE predicate on the "message" field. -func MessageGTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMessage), v)) - }) -} - -// MessageLT applies the LT predicate on the "message" field. -func MessageLT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMessage), v)) - }) -} - -// MessageLTE applies the LTE predicate on the "message" field. -func MessageLTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMessage), v)) - }) -} - -// MessageContains applies the Contains predicate on the "message" field. -func MessageContains(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldMessage), v)) - }) -} - -// MessageHasPrefix applies the HasPrefix predicate on the "message" field. -func MessageHasPrefix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldMessage), v)) - }) -} - -// MessageHasSuffix applies the HasSuffix predicate on the "message" field. -func MessageHasSuffix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldMessage), v)) - }) -} - -// MessageEqualFold applies the EqualFold predicate on the "message" field. -func MessageEqualFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldMessage), v)) - }) -} - -// MessageContainsFold applies the ContainsFold predicate on the "message" field. -func MessageContainsFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldMessage), v)) - }) -} - -// UserIDEQ applies the EQ predicate on the "user_id" field. -func UserIDEQ(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUserID), v)) - }) -} - -// UserIDNEQ applies the NEQ predicate on the "user_id" field. -func UserIDNEQ(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUserID), v)) - }) -} - -// UserIDIn applies the In predicate on the "user_id" field. -func UserIDIn(vs ...int) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUserID), v...)) - }) -} - -// UserIDNotIn applies the NotIn predicate on the "user_id" field. -func UserIDNotIn(vs ...int) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUserID), v...)) - }) -} - -// UserIDGT applies the GT predicate on the "user_id" field. -func UserIDGT(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUserID), v)) - }) -} - -// UserIDGTE applies the GTE predicate on the "user_id" field. -func UserIDGTE(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUserID), v)) - }) -} - -// UserIDLT applies the LT predicate on the "user_id" field. -func UserIDLT(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUserID), v)) - }) -} - -// UserIDLTE applies the LTE predicate on the "user_id" field. -func UserIDLTE(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUserID), v)) - }) -} - -// UsernameEQ applies the EQ predicate on the "username" field. -func UsernameEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUsername), v)) - }) -} - -// UsernameNEQ applies the NEQ predicate on the "username" field. -func UsernameNEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUsername), v)) - }) -} - -// UsernameIn applies the In predicate on the "username" field. -func UsernameIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUsername), v...)) - }) -} - -// UsernameNotIn applies the NotIn predicate on the "username" field. -func UsernameNotIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUsername), v...)) - }) -} - -// UsernameGT applies the GT predicate on the "username" field. -func UsernameGT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUsername), v)) - }) -} - -// UsernameGTE applies the GTE predicate on the "username" field. -func UsernameGTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUsername), v)) - }) -} - -// UsernameLT applies the LT predicate on the "username" field. -func UsernameLT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUsername), v)) - }) -} - -// UsernameLTE applies the LTE predicate on the "username" field. -func UsernameLTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUsername), v)) - }) -} - -// UsernameContains applies the Contains predicate on the "username" field. -func UsernameContains(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldUsername), v)) - }) -} - -// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. -func UsernameHasPrefix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldUsername), v)) - }) -} - -// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. -func UsernameHasSuffix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldUsername), v)) - }) -} - -// UsernameEqualFold applies the EqualFold predicate on the "username" field. -func UsernameEqualFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldUsername), v)) - }) -} - -// UsernameContainsFold applies the ContainsFold predicate on the "username" field. -func UsernameContainsFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldUsername), v)) - }) -} - -// StatusCodeEQ applies the EQ predicate on the "status_code" field. -func StatusCodeEQ(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStatusCode), v)) - }) -} - -// StatusCodeNEQ applies the NEQ predicate on the "status_code" field. -func StatusCodeNEQ(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldStatusCode), v)) - }) -} - -// StatusCodeIn applies the In predicate on the "status_code" field. -func StatusCodeIn(vs ...int) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldStatusCode), v...)) - }) -} - -// StatusCodeNotIn applies the NotIn predicate on the "status_code" field. -func StatusCodeNotIn(vs ...int) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldStatusCode), v...)) - }) -} - -// StatusCodeGT applies the GT predicate on the "status_code" field. -func StatusCodeGT(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldStatusCode), v)) - }) -} - -// StatusCodeGTE applies the GTE predicate on the "status_code" field. -func StatusCodeGTE(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldStatusCode), v)) - }) -} - -// StatusCodeLT applies the LT predicate on the "status_code" field. -func StatusCodeLT(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldStatusCode), v)) - }) -} - -// StatusCodeLTE applies the LTE predicate on the "status_code" field. -func StatusCodeLTE(v int) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldStatusCode), v)) - }) -} - -// MethodEQ applies the EQ predicate on the "method" field. -func MethodEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMethod), v)) - }) -} - -// MethodNEQ applies the NEQ predicate on the "method" field. -func MethodNEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMethod), v)) - }) -} - -// MethodIn applies the In predicate on the "method" field. -func MethodIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMethod), v...)) - }) -} - -// MethodNotIn applies the NotIn predicate on the "method" field. -func MethodNotIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMethod), v...)) - }) -} - -// MethodGT applies the GT predicate on the "method" field. -func MethodGT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMethod), v)) - }) -} - -// MethodGTE applies the GTE predicate on the "method" field. -func MethodGTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMethod), v)) - }) -} - -// MethodLT applies the LT predicate on the "method" field. -func MethodLT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMethod), v)) - }) -} - -// MethodLTE applies the LTE predicate on the "method" field. -func MethodLTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMethod), v)) - }) -} - -// MethodContains applies the Contains predicate on the "method" field. -func MethodContains(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldMethod), v)) - }) -} - -// MethodHasPrefix applies the HasPrefix predicate on the "method" field. -func MethodHasPrefix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldMethod), v)) - }) -} - -// MethodHasSuffix applies the HasSuffix predicate on the "method" field. -func MethodHasSuffix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldMethod), v)) - }) -} - -// MethodEqualFold applies the EqualFold predicate on the "method" field. -func MethodEqualFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldMethod), v)) - }) -} - -// MethodContainsFold applies the ContainsFold predicate on the "method" field. -func MethodContainsFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldMethod), v)) - }) -} - -// PathEQ applies the EQ predicate on the "path" field. -func PathEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPath), v)) - }) -} - -// PathNEQ applies the NEQ predicate on the "path" field. -func PathNEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldPath), v)) - }) -} - -// PathIn applies the In predicate on the "path" field. -func PathIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldPath), v...)) - }) -} - -// PathNotIn applies the NotIn predicate on the "path" field. -func PathNotIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldPath), v...)) - }) -} - -// PathGT applies the GT predicate on the "path" field. -func PathGT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldPath), v)) - }) -} - -// PathGTE applies the GTE predicate on the "path" field. -func PathGTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldPath), v)) - }) -} - -// PathLT applies the LT predicate on the "path" field. -func PathLT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldPath), v)) - }) -} - -// PathLTE applies the LTE predicate on the "path" field. -func PathLTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldPath), v)) - }) -} - -// PathContains applies the Contains predicate on the "path" field. -func PathContains(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldPath), v)) - }) -} - -// PathHasPrefix applies the HasPrefix predicate on the "path" field. -func PathHasPrefix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldPath), v)) - }) -} - -// PathHasSuffix applies the HasSuffix predicate on the "path" field. -func PathHasSuffix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldPath), v)) - }) -} - -// PathEqualFold applies the EqualFold predicate on the "path" field. -func PathEqualFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldPath), v)) - }) -} - -// PathContainsFold applies the ContainsFold predicate on the "path" field. -func PathContainsFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldPath), v)) - }) -} - -// PermissionEQ applies the EQ predicate on the "permission" field. -func PermissionEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPermission), v)) - }) -} - -// PermissionNEQ applies the NEQ predicate on the "permission" field. -func PermissionNEQ(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldPermission), v)) - }) -} - -// PermissionIn applies the In predicate on the "permission" field. -func PermissionIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldPermission), v...)) - }) -} - -// PermissionNotIn applies the NotIn predicate on the "permission" field. -func PermissionNotIn(vs ...string) predicate.LinLog { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinLog(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldPermission), v...)) - }) -} - -// PermissionGT applies the GT predicate on the "permission" field. -func PermissionGT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldPermission), v)) - }) -} - -// PermissionGTE applies the GTE predicate on the "permission" field. -func PermissionGTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldPermission), v)) - }) -} - -// PermissionLT applies the LT predicate on the "permission" field. -func PermissionLT(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldPermission), v)) - }) -} - -// PermissionLTE applies the LTE predicate on the "permission" field. -func PermissionLTE(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldPermission), v)) - }) -} - -// PermissionContains applies the Contains predicate on the "permission" field. -func PermissionContains(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldPermission), v)) - }) -} - -// PermissionHasPrefix applies the HasPrefix predicate on the "permission" field. -func PermissionHasPrefix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldPermission), v)) - }) -} - -// PermissionHasSuffix applies the HasSuffix predicate on the "permission" field. -func PermissionHasSuffix(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldPermission), v)) - }) -} - -// PermissionEqualFold applies the EqualFold predicate on the "permission" field. -func PermissionEqualFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldPermission), v)) - }) -} - -// PermissionContainsFold applies the ContainsFold predicate on the "permission" field. -func PermissionContainsFold(v string) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldPermission), v)) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.LinLog) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinLog) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinLog) predicate.LinLog { - return predicate.LinLog(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/linlog_create.go b/internal/data/model/linlog_create.go deleted file mode 100644 index 9b9b76d..0000000 --- a/internal/data/model/linlog_create.go +++ /dev/null @@ -1,416 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/linlog" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinLogCreate is the builder for creating a LinLog entity. -type LinLogCreate struct { - config - mutation *LinLogMutation - hooks []Hook -} - -// SetCreateTime sets the "create_time" field. -func (llc *LinLogCreate) SetCreateTime(t time.Time) *LinLogCreate { - llc.mutation.SetCreateTime(t) - return llc -} - -// SetNillableCreateTime sets the "create_time" field if the given value is not nil. -func (llc *LinLogCreate) SetNillableCreateTime(t *time.Time) *LinLogCreate { - if t != nil { - llc.SetCreateTime(*t) - } - return llc -} - -// SetUpdateTime sets the "update_time" field. -func (llc *LinLogCreate) SetUpdateTime(t time.Time) *LinLogCreate { - llc.mutation.SetUpdateTime(t) - return llc -} - -// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. -func (llc *LinLogCreate) SetNillableUpdateTime(t *time.Time) *LinLogCreate { - if t != nil { - llc.SetUpdateTime(*t) - } - return llc -} - -// SetDeleteTime sets the "delete_time" field. -func (llc *LinLogCreate) SetDeleteTime(t time.Time) *LinLogCreate { - llc.mutation.SetDeleteTime(t) - return llc -} - -// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. -func (llc *LinLogCreate) SetNillableDeleteTime(t *time.Time) *LinLogCreate { - if t != nil { - llc.SetDeleteTime(*t) - } - return llc -} - -// SetMessage sets the "message" field. -func (llc *LinLogCreate) SetMessage(s string) *LinLogCreate { - llc.mutation.SetMessage(s) - return llc -} - -// SetUserID sets the "user_id" field. -func (llc *LinLogCreate) SetUserID(i int) *LinLogCreate { - llc.mutation.SetUserID(i) - return llc -} - -// SetUsername sets the "username" field. -func (llc *LinLogCreate) SetUsername(s string) *LinLogCreate { - llc.mutation.SetUsername(s) - return llc -} - -// SetStatusCode sets the "status_code" field. -func (llc *LinLogCreate) SetStatusCode(i int) *LinLogCreate { - llc.mutation.SetStatusCode(i) - return llc -} - -// SetMethod sets the "method" field. -func (llc *LinLogCreate) SetMethod(s string) *LinLogCreate { - llc.mutation.SetMethod(s) - return llc -} - -// SetPath sets the "path" field. -func (llc *LinLogCreate) SetPath(s string) *LinLogCreate { - llc.mutation.SetPath(s) - return llc -} - -// SetPermission sets the "permission" field. -func (llc *LinLogCreate) SetPermission(s string) *LinLogCreate { - llc.mutation.SetPermission(s) - return llc -} - -// Mutation returns the LinLogMutation object of the builder. -func (llc *LinLogCreate) Mutation() *LinLogMutation { - return llc.mutation -} - -// Save creates the LinLog in the database. -func (llc *LinLogCreate) Save(ctx context.Context) (*LinLog, error) { - var ( - err error - node *LinLog - ) - llc.defaults() - if len(llc.hooks) == 0 { - if err = llc.check(); err != nil { - return nil, err - } - node, err = llc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = llc.check(); err != nil { - return nil, err - } - llc.mutation = mutation - if node, err = llc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(llc.hooks) - 1; i >= 0; i-- { - if llc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = llc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, llc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (llc *LinLogCreate) SaveX(ctx context.Context) *LinLog { - v, err := llc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (llc *LinLogCreate) Exec(ctx context.Context) error { - _, err := llc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (llc *LinLogCreate) ExecX(ctx context.Context) { - if err := llc.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (llc *LinLogCreate) defaults() { - if _, ok := llc.mutation.CreateTime(); !ok { - v := linlog.DefaultCreateTime() - llc.mutation.SetCreateTime(v) - } - if _, ok := llc.mutation.UpdateTime(); !ok { - v := linlog.DefaultUpdateTime() - llc.mutation.SetUpdateTime(v) - } - if _, ok := llc.mutation.DeleteTime(); !ok { - v := linlog.DefaultDeleteTime() - llc.mutation.SetDeleteTime(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (llc *LinLogCreate) check() error { - if _, ok := llc.mutation.CreateTime(); !ok { - return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} - } - if _, ok := llc.mutation.UpdateTime(); !ok { - return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} - } - if _, ok := llc.mutation.DeleteTime(); !ok { - return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} - } - if _, ok := llc.mutation.Message(); !ok { - return &ValidationError{Name: "message", err: errors.New(`model: missing required field "message"`)} - } - if _, ok := llc.mutation.UserID(); !ok { - return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} - } - if _, ok := llc.mutation.Username(); !ok { - return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} - } - if _, ok := llc.mutation.StatusCode(); !ok { - return &ValidationError{Name: "status_code", err: errors.New(`model: missing required field "status_code"`)} - } - if _, ok := llc.mutation.Method(); !ok { - return &ValidationError{Name: "method", err: errors.New(`model: missing required field "method"`)} - } - if _, ok := llc.mutation.Path(); !ok { - return &ValidationError{Name: "path", err: errors.New(`model: missing required field "path"`)} - } - if _, ok := llc.mutation.Permission(); !ok { - return &ValidationError{Name: "permission", err: errors.New(`model: missing required field "permission"`)} - } - return nil -} - -func (llc *LinLogCreate) sqlSave(ctx context.Context) (*LinLog, error) { - _node, _spec := llc.createSpec() - if err := sqlgraph.CreateNode(ctx, llc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (llc *LinLogCreate) createSpec() (*LinLog, *sqlgraph.CreateSpec) { - var ( - _node = &LinLog{config: llc.config} - _spec = &sqlgraph.CreateSpec{ - Table: linlog.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linlog.FieldID, - }, - } - ) - if value, ok := llc.mutation.CreateTime(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldCreateTime, - }) - _node.CreateTime = value - } - if value, ok := llc.mutation.UpdateTime(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldUpdateTime, - }) - _node.UpdateTime = value - } - if value, ok := llc.mutation.DeleteTime(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldDeleteTime, - }) - _node.DeleteTime = value - } - if value, ok := llc.mutation.Message(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldMessage, - }) - _node.Message = value - } - if value, ok := llc.mutation.UserID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldUserID, - }) - _node.UserID = value - } - if value, ok := llc.mutation.Username(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldUsername, - }) - _node.Username = value - } - if value, ok := llc.mutation.StatusCode(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldStatusCode, - }) - _node.StatusCode = value - } - if value, ok := llc.mutation.Method(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldMethod, - }) - _node.Method = value - } - if value, ok := llc.mutation.Path(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldPath, - }) - _node.Path = value - } - if value, ok := llc.mutation.Permission(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldPermission, - }) - _node.Permission = value - } - return _node, _spec -} - -// LinLogCreateBulk is the builder for creating many LinLog entities in bulk. -type LinLogCreateBulk struct { - config - builders []*LinLogCreate -} - -// Save creates the LinLog entities in the database. -func (llcb *LinLogCreateBulk) Save(ctx context.Context) ([]*LinLog, error) { - specs := make([]*sqlgraph.CreateSpec, len(llcb.builders)) - nodes := make([]*LinLog, len(llcb.builders)) - mutators := make([]Mutator, len(llcb.builders)) - for i := range llcb.builders { - func(i int, root context.Context) { - builder := llcb.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, llcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, llcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, llcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (llcb *LinLogCreateBulk) SaveX(ctx context.Context) []*LinLog { - v, err := llcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (llcb *LinLogCreateBulk) Exec(ctx context.Context) error { - _, err := llcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (llcb *LinLogCreateBulk) ExecX(ctx context.Context) { - if err := llcb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/linlog_delete.go b/internal/data/model/linlog_delete.go deleted file mode 100644 index 7b370d2..0000000 --- a/internal/data/model/linlog_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinLogDelete is the builder for deleting a LinLog entity. -type LinLogDelete struct { - config - hooks []Hook - mutation *LinLogMutation -} - -// Where appends a list predicates to the LinLogDelete builder. -func (lld *LinLogDelete) Where(ps ...predicate.LinLog) *LinLogDelete { - lld.mutation.Where(ps...) - return lld -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (lld *LinLogDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lld.hooks) == 0 { - affected, err = lld.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lld.mutation = mutation - affected, err = lld.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(lld.hooks) - 1; i >= 0; i-- { - if lld.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lld.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lld.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lld *LinLogDelete) ExecX(ctx context.Context) int { - n, err := lld.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (lld *LinLogDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linlog.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linlog.FieldID, - }, - }, - } - if ps := lld.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, lld.driver, _spec) -} - -// LinLogDeleteOne is the builder for deleting a single LinLog entity. -type LinLogDeleteOne struct { - lld *LinLogDelete -} - -// Exec executes the deletion query. -func (lldo *LinLogDeleteOne) Exec(ctx context.Context) error { - n, err := lldo.lld.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{linlog.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (lldo *LinLogDeleteOne) ExecX(ctx context.Context) { - lldo.lld.ExecX(ctx) -} diff --git a/internal/data/model/linlog_query.go b/internal/data/model/linlog_query.go deleted file mode 100644 index c734c14..0000000 --- a/internal/data/model/linlog_query.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinLogQuery is the builder for querying LinLog entities. -type LinLogQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinLog - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinLogQuery builder. -func (llq *LinLogQuery) Where(ps ...predicate.LinLog) *LinLogQuery { - llq.predicates = append(llq.predicates, ps...) - return llq -} - -// Limit adds a limit step to the query. -func (llq *LinLogQuery) Limit(limit int) *LinLogQuery { - llq.limit = &limit - return llq -} - -// Offset adds an offset step to the query. -func (llq *LinLogQuery) Offset(offset int) *LinLogQuery { - llq.offset = &offset - return llq -} - -// 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 (llq *LinLogQuery) Unique(unique bool) *LinLogQuery { - llq.unique = &unique - return llq -} - -// Order adds an order step to the query. -func (llq *LinLogQuery) Order(o ...OrderFunc) *LinLogQuery { - llq.order = append(llq.order, o...) - return llq -} - -// First returns the first LinLog entity from the query. -// Returns a *NotFoundError when no LinLog was found. -func (llq *LinLogQuery) First(ctx context.Context) (*LinLog, error) { - nodes, err := llq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linlog.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (llq *LinLogQuery) FirstX(ctx context.Context) *LinLog { - node, err := llq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinLog ID from the query. -// Returns a *NotFoundError when no LinLog ID was found. -func (llq *LinLogQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = llq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linlog.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (llq *LinLogQuery) FirstIDX(ctx context.Context) int { - id, err := llq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinLog entity from the query. -// Returns a *NotFoundError when no LinLog was found. -func (llq *LinLogQuery) Last(ctx context.Context) (*LinLog, error) { - nodes, err := llq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linlog.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (llq *LinLogQuery) LastX(ctx context.Context) *LinLog { - node, err := llq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinLog ID from the query. -// Returns a *NotFoundError when no LinLog ID was found. -func (llq *LinLogQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = llq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linlog.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (llq *LinLogQuery) LastIDX(ctx context.Context) int { - id, err := llq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinLog entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinLog entity is not found. -// Returns a *NotFoundError when no LinLog entities are found. -func (llq *LinLogQuery) Only(ctx context.Context) (*LinLog, error) { - nodes, err := llq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{linlog.Label} - default: - return nil, &NotSingularError{linlog.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (llq *LinLogQuery) OnlyX(ctx context.Context) *LinLog { - node, err := llq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinLog ID in the query. -// Returns a *NotSingularError when exactly one LinLog ID is not found. -// Returns a *NotFoundError when no entities are found. -func (llq *LinLogQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = llq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{linlog.Label} - default: - err = &NotSingularError{linlog.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (llq *LinLogQuery) OnlyIDX(ctx context.Context) int { - id, err := llq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinLogs. -func (llq *LinLogQuery) All(ctx context.Context) ([]*LinLog, error) { - if err := llq.prepareQuery(ctx); err != nil { - return nil, err - } - return llq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (llq *LinLogQuery) AllX(ctx context.Context) []*LinLog { - nodes, err := llq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinLog IDs. -func (llq *LinLogQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := llq.Select(linlog.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (llq *LinLogQuery) IDsX(ctx context.Context) []int { - ids, err := llq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (llq *LinLogQuery) Count(ctx context.Context) (int, error) { - if err := llq.prepareQuery(ctx); err != nil { - return 0, err - } - return llq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (llq *LinLogQuery) CountX(ctx context.Context) int { - count, err := llq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (llq *LinLogQuery) Exist(ctx context.Context) (bool, error) { - if err := llq.prepareQuery(ctx); err != nil { - return false, err - } - return llq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (llq *LinLogQuery) ExistX(ctx context.Context) bool { - exist, err := llq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinLogQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (llq *LinLogQuery) Clone() *LinLogQuery { - if llq == nil { - return nil - } - return &LinLogQuery{ - config: llq.config, - limit: llq.limit, - offset: llq.offset, - order: append([]OrderFunc{}, llq.order...), - predicates: append([]predicate.LinLog{}, llq.predicates...), - // clone intermediate query. - sql: llq.sql.Clone(), - path: llq.path, - } -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// CreateTime time.Time `json:"create_time,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinLog.Query(). -// GroupBy(linlog.FieldCreateTime). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (llq *LinLogQuery) GroupBy(field string, fields ...string) *LinLogGroupBy { - group := &LinLogGroupBy{config: llq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := llq.prepareQuery(ctx); err != nil { - return nil, err - } - return llq.sqlQuery(ctx), nil - } - return group -} - -// 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 { -// CreateTime time.Time `json:"create_time,omitempty"` -// } -// -// client.LinLog.Query(). -// Select(linlog.FieldCreateTime). -// Scan(ctx, &v) -// -func (llq *LinLogQuery) Select(fields ...string) *LinLogSelect { - llq.fields = append(llq.fields, fields...) - return &LinLogSelect{LinLogQuery: llq} -} - -func (llq *LinLogQuery) prepareQuery(ctx context.Context) error { - for _, f := range llq.fields { - if !linlog.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if llq.path != nil { - prev, err := llq.path(ctx) - if err != nil { - return err - } - llq.sql = prev - } - return nil -} - -func (llq *LinLogQuery) sqlAll(ctx context.Context) ([]*LinLog, error) { - var ( - nodes = []*LinLog{} - _spec = llq.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinLog{config: llq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, llq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (llq *LinLogQuery) sqlCount(ctx context.Context) (int, error) { - _spec := llq.querySpec() - return sqlgraph.CountNodes(ctx, llq.driver, _spec) -} - -func (llq *LinLogQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := llq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (llq *LinLogQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: linlog.Table, - Columns: linlog.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linlog.FieldID, - }, - }, - From: llq.sql, - Unique: true, - } - if unique := llq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := llq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linlog.FieldID) - for i := range fields { - if fields[i] != linlog.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := llq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := llq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := llq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := llq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (llq *LinLogQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(llq.driver.Dialect()) - t1 := builder.Table(linlog.Table) - columns := llq.fields - if len(columns) == 0 { - columns = linlog.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if llq.sql != nil { - selector = llq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range llq.predicates { - p(selector) - } - for _, p := range llq.order { - p(selector) - } - if offset := llq.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 := llq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinLogGroupBy is the group-by builder for LinLog entities. -type LinLogGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (llgb *LinLogGroupBy) Aggregate(fns ...AggregateFunc) *LinLogGroupBy { - llgb.fns = append(llgb.fns, fns...) - return llgb -} - -// Scan applies the group-by query and scans the result into the given value. -func (llgb *LinLogGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := llgb.path(ctx) - if err != nil { - return err - } - llgb.sql = query - return llgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (llgb *LinLogGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := llgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(llgb.fields) > 1 { - return nil, errors.New("model: LinLogGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := llgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (llgb *LinLogGroupBy) StringsX(ctx context.Context) []string { - v, err := llgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = llgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (llgb *LinLogGroupBy) StringX(ctx context.Context) string { - v, err := llgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(llgb.fields) > 1 { - return nil, errors.New("model: LinLogGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := llgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (llgb *LinLogGroupBy) IntsX(ctx context.Context) []int { - v, err := llgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = llgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (llgb *LinLogGroupBy) IntX(ctx context.Context) int { - v, err := llgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(llgb.fields) > 1 { - return nil, errors.New("model: LinLogGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := llgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (llgb *LinLogGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := llgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = llgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (llgb *LinLogGroupBy) Float64X(ctx context.Context) float64 { - v, err := llgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(llgb.fields) > 1 { - return nil, errors.New("model: LinLogGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := llgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (llgb *LinLogGroupBy) BoolsX(ctx context.Context) []bool { - v, err := llgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (llgb *LinLogGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = llgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (llgb *LinLogGroupBy) BoolX(ctx context.Context) bool { - v, err := llgb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (llgb *LinLogGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range llgb.fields { - if !linlog.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := llgb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := llgb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (llgb *LinLogGroupBy) sqlQuery() *sql.Selector { - selector := llgb.sql.Select() - aggregation := make([]string, 0, len(llgb.fns)) - for _, fn := range llgb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(llgb.fields)+len(llgb.fns)) - for _, f := range llgb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(llgb.fields...)...) -} - -// LinLogSelect is the builder for selecting fields of LinLog entities. -type LinLogSelect struct { - *LinLogQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (lls *LinLogSelect) Scan(ctx context.Context, v interface{}) error { - if err := lls.prepareQuery(ctx); err != nil { - return err - } - lls.sql = lls.LinLogQuery.sqlQuery(ctx) - return lls.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lls *LinLogSelect) ScanX(ctx context.Context, v interface{}) { - if err := lls.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Strings(ctx context.Context) ([]string, error) { - if len(lls.fields) > 1 { - return nil, errors.New("model: LinLogSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := lls.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lls *LinLogSelect) StringsX(ctx context.Context) []string { - v, err := lls.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lls.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lls *LinLogSelect) StringX(ctx context.Context) string { - v, err := lls.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Ints(ctx context.Context) ([]int, error) { - if len(lls.fields) > 1 { - return nil, errors.New("model: LinLogSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := lls.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lls *LinLogSelect) IntsX(ctx context.Context) []int { - v, err := lls.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lls.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lls *LinLogSelect) IntX(ctx context.Context) int { - v, err := lls.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(lls.fields) > 1 { - return nil, errors.New("model: LinLogSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := lls.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lls *LinLogSelect) Float64sX(ctx context.Context) []float64 { - v, err := lls.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lls.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lls *LinLogSelect) Float64X(ctx context.Context) float64 { - v, err := lls.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Bools(ctx context.Context) ([]bool, error) { - if len(lls.fields) > 1 { - return nil, errors.New("model: LinLogSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := lls.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lls *LinLogSelect) BoolsX(ctx context.Context) []bool { - v, err := lls.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (lls *LinLogSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lls.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linlog.Label} - default: - err = fmt.Errorf("model: LinLogSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lls *LinLogSelect) BoolX(ctx context.Context) bool { - v, err := lls.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lls *LinLogSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := lls.sql.Query() - if err := lls.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/linlog_update.go b/internal/data/model/linlog_update.go deleted file mode 100644 index 7b53bc4..0000000 --- a/internal/data/model/linlog_update.go +++ /dev/null @@ -1,563 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/predicate" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinLogUpdate is the builder for updating LinLog entities. -type LinLogUpdate struct { - config - hooks []Hook - mutation *LinLogMutation -} - -// Where appends a list predicates to the LinLogUpdate builder. -func (llu *LinLogUpdate) Where(ps ...predicate.LinLog) *LinLogUpdate { - llu.mutation.Where(ps...) - return llu -} - -// SetUpdateTime sets the "update_time" field. -func (llu *LinLogUpdate) SetUpdateTime(t time.Time) *LinLogUpdate { - llu.mutation.SetUpdateTime(t) - return llu -} - -// SetDeleteTime sets the "delete_time" field. -func (llu *LinLogUpdate) SetDeleteTime(t time.Time) *LinLogUpdate { - llu.mutation.SetDeleteTime(t) - return llu -} - -// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. -func (llu *LinLogUpdate) SetNillableDeleteTime(t *time.Time) *LinLogUpdate { - if t != nil { - llu.SetDeleteTime(*t) - } - return llu -} - -// SetMessage sets the "message" field. -func (llu *LinLogUpdate) SetMessage(s string) *LinLogUpdate { - llu.mutation.SetMessage(s) - return llu -} - -// SetUserID sets the "user_id" field. -func (llu *LinLogUpdate) SetUserID(i int) *LinLogUpdate { - llu.mutation.ResetUserID() - llu.mutation.SetUserID(i) - return llu -} - -// AddUserID adds i to the "user_id" field. -func (llu *LinLogUpdate) AddUserID(i int) *LinLogUpdate { - llu.mutation.AddUserID(i) - return llu -} - -// SetUsername sets the "username" field. -func (llu *LinLogUpdate) SetUsername(s string) *LinLogUpdate { - llu.mutation.SetUsername(s) - return llu -} - -// SetStatusCode sets the "status_code" field. -func (llu *LinLogUpdate) SetStatusCode(i int) *LinLogUpdate { - llu.mutation.ResetStatusCode() - llu.mutation.SetStatusCode(i) - return llu -} - -// AddStatusCode adds i to the "status_code" field. -func (llu *LinLogUpdate) AddStatusCode(i int) *LinLogUpdate { - llu.mutation.AddStatusCode(i) - return llu -} - -// SetMethod sets the "method" field. -func (llu *LinLogUpdate) SetMethod(s string) *LinLogUpdate { - llu.mutation.SetMethod(s) - return llu -} - -// SetPath sets the "path" field. -func (llu *LinLogUpdate) SetPath(s string) *LinLogUpdate { - llu.mutation.SetPath(s) - return llu -} - -// SetPermission sets the "permission" field. -func (llu *LinLogUpdate) SetPermission(s string) *LinLogUpdate { - llu.mutation.SetPermission(s) - return llu -} - -// Mutation returns the LinLogMutation object of the builder. -func (llu *LinLogUpdate) Mutation() *LinLogMutation { - return llu.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (llu *LinLogUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - llu.defaults() - if len(llu.hooks) == 0 { - affected, err = llu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - llu.mutation = mutation - affected, err = llu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(llu.hooks) - 1; i >= 0; i-- { - if llu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = llu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, llu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (llu *LinLogUpdate) SaveX(ctx context.Context) int { - affected, err := llu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (llu *LinLogUpdate) Exec(ctx context.Context) error { - _, err := llu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (llu *LinLogUpdate) ExecX(ctx context.Context) { - if err := llu.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (llu *LinLogUpdate) defaults() { - if _, ok := llu.mutation.UpdateTime(); !ok { - v := linlog.UpdateDefaultUpdateTime() - llu.mutation.SetUpdateTime(v) - } -} - -func (llu *LinLogUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linlog.Table, - Columns: linlog.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linlog.FieldID, - }, - }, - } - if ps := llu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := llu.mutation.UpdateTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldUpdateTime, - }) - } - if value, ok := llu.mutation.DeleteTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldDeleteTime, - }) - } - if value, ok := llu.mutation.Message(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldMessage, - }) - } - if value, ok := llu.mutation.UserID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldUserID, - }) - } - if value, ok := llu.mutation.AddedUserID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldUserID, - }) - } - if value, ok := llu.mutation.Username(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldUsername, - }) - } - if value, ok := llu.mutation.StatusCode(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldStatusCode, - }) - } - if value, ok := llu.mutation.AddedStatusCode(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldStatusCode, - }) - } - if value, ok := llu.mutation.Method(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldMethod, - }) - } - if value, ok := llu.mutation.Path(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldPath, - }) - } - if value, ok := llu.mutation.Permission(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldPermission, - }) - } - if n, err = sqlgraph.UpdateNodes(ctx, llu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linlog.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinLogUpdateOne is the builder for updating a single LinLog entity. -type LinLogUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinLogMutation -} - -// SetUpdateTime sets the "update_time" field. -func (lluo *LinLogUpdateOne) SetUpdateTime(t time.Time) *LinLogUpdateOne { - lluo.mutation.SetUpdateTime(t) - return lluo -} - -// SetDeleteTime sets the "delete_time" field. -func (lluo *LinLogUpdateOne) SetDeleteTime(t time.Time) *LinLogUpdateOne { - lluo.mutation.SetDeleteTime(t) - return lluo -} - -// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. -func (lluo *LinLogUpdateOne) SetNillableDeleteTime(t *time.Time) *LinLogUpdateOne { - if t != nil { - lluo.SetDeleteTime(*t) - } - return lluo -} - -// SetMessage sets the "message" field. -func (lluo *LinLogUpdateOne) SetMessage(s string) *LinLogUpdateOne { - lluo.mutation.SetMessage(s) - return lluo -} - -// SetUserID sets the "user_id" field. -func (lluo *LinLogUpdateOne) SetUserID(i int) *LinLogUpdateOne { - lluo.mutation.ResetUserID() - lluo.mutation.SetUserID(i) - return lluo -} - -// AddUserID adds i to the "user_id" field. -func (lluo *LinLogUpdateOne) AddUserID(i int) *LinLogUpdateOne { - lluo.mutation.AddUserID(i) - return lluo -} - -// SetUsername sets the "username" field. -func (lluo *LinLogUpdateOne) SetUsername(s string) *LinLogUpdateOne { - lluo.mutation.SetUsername(s) - return lluo -} - -// SetStatusCode sets the "status_code" field. -func (lluo *LinLogUpdateOne) SetStatusCode(i int) *LinLogUpdateOne { - lluo.mutation.ResetStatusCode() - lluo.mutation.SetStatusCode(i) - return lluo -} - -// AddStatusCode adds i to the "status_code" field. -func (lluo *LinLogUpdateOne) AddStatusCode(i int) *LinLogUpdateOne { - lluo.mutation.AddStatusCode(i) - return lluo -} - -// SetMethod sets the "method" field. -func (lluo *LinLogUpdateOne) SetMethod(s string) *LinLogUpdateOne { - lluo.mutation.SetMethod(s) - return lluo -} - -// SetPath sets the "path" field. -func (lluo *LinLogUpdateOne) SetPath(s string) *LinLogUpdateOne { - lluo.mutation.SetPath(s) - return lluo -} - -// SetPermission sets the "permission" field. -func (lluo *LinLogUpdateOne) SetPermission(s string) *LinLogUpdateOne { - lluo.mutation.SetPermission(s) - return lluo -} - -// Mutation returns the LinLogMutation object of the builder. -func (lluo *LinLogUpdateOne) Mutation() *LinLogMutation { - return lluo.mutation -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (lluo *LinLogUpdateOne) Select(field string, fields ...string) *LinLogUpdateOne { - lluo.fields = append([]string{field}, fields...) - return lluo -} - -// Save executes the query and returns the updated LinLog entity. -func (lluo *LinLogUpdateOne) Save(ctx context.Context) (*LinLog, error) { - var ( - err error - node *LinLog - ) - lluo.defaults() - if len(lluo.hooks) == 0 { - node, err = lluo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lluo.mutation = mutation - node, err = lluo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(lluo.hooks) - 1; i >= 0; i-- { - if lluo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lluo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lluo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lluo *LinLogUpdateOne) SaveX(ctx context.Context) *LinLog { - node, err := lluo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (lluo *LinLogUpdateOne) Exec(ctx context.Context) error { - _, err := lluo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lluo *LinLogUpdateOne) ExecX(ctx context.Context) { - if err := lluo.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (lluo *LinLogUpdateOne) defaults() { - if _, ok := lluo.mutation.UpdateTime(); !ok { - v := linlog.UpdateDefaultUpdateTime() - lluo.mutation.SetUpdateTime(v) - } -} - -func (lluo *LinLogUpdateOne) sqlSave(ctx context.Context) (_node *LinLog, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linlog.Table, - Columns: linlog.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linlog.FieldID, - }, - }, - } - id, ok := lluo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinLog.ID for update")} - } - _spec.Node.ID.Value = id - if fields := lluo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linlog.FieldID) - for _, f := range fields { - if !linlog.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != linlog.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := lluo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lluo.mutation.UpdateTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldUpdateTime, - }) - } - if value, ok := lluo.mutation.DeleteTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linlog.FieldDeleteTime, - }) - } - if value, ok := lluo.mutation.Message(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldMessage, - }) - } - if value, ok := lluo.mutation.UserID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldUserID, - }) - } - if value, ok := lluo.mutation.AddedUserID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldUserID, - }) - } - if value, ok := lluo.mutation.Username(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldUsername, - }) - } - if value, ok := lluo.mutation.StatusCode(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldStatusCode, - }) - } - if value, ok := lluo.mutation.AddedStatusCode(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linlog.FieldStatusCode, - }) - } - if value, ok := lluo.mutation.Method(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldMethod, - }) - } - if value, ok := lluo.mutation.Path(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldPath, - }) - } - if value, ok := lluo.mutation.Permission(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linlog.FieldPermission, - }) - } - _node = &LinLog{config: lluo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, lluo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linlog.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/linpermission.go b/internal/data/model/linpermission.go deleted file mode 100644 index f2acd85..0000000 --- a/internal/data/model/linpermission.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/linpermission" - "strings" - - "entgo.io/ent/dialect/sql" -) - -// LinPermission is the model entity for the LinPermission schema. -type LinPermission struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // Name holds the value of the "name" field. - // 权限名称,例如:访问首页 - Name string `json:"name,omitempty"` - // Module holds the value of the "module" field. - // 权限所属模块,例如:人员管理 - Module string `json:"module,omitempty"` - // Mount holds the value of the "mount" field. - // 0:关闭 1:开启 - Mount int8 `json:"mount,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the LinPermissionQuery when eager-loading is set. - Edges LinPermissionEdges `json:"edges"` -} - -// LinPermissionEdges holds the relations/edges for other nodes in the graph. -type LinPermissionEdges struct { - // LinGroup holds the value of the lin_group edge. - LinGroup []*LinGroup `json:"lin_group,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool -} - -// LinGroupOrErr returns the LinGroup value or an error if the edge -// was not loaded in eager-loading. -func (e LinPermissionEdges) LinGroupOrErr() ([]*LinGroup, error) { - if e.loadedTypes[0] { - return e.LinGroup, nil - } - return nil, &NotLoadedError{edge: "lin_group"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinPermission) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case linpermission.FieldID, linpermission.FieldMount: - values[i] = new(sql.NullInt64) - case linpermission.FieldName, linpermission.FieldModule: - values[i] = new(sql.NullString) - default: - return nil, fmt.Errorf("unexpected column %q for type LinPermission", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinPermission fields. -func (lp *LinPermission) assignValues(columns []string, values []interface{}) 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 linpermission.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - lp.ID = int(value.Int64) - case linpermission.FieldName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[i]) - } else if value.Valid { - lp.Name = value.String - } - case linpermission.FieldModule: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field module", values[i]) - } else if value.Valid { - lp.Module = value.String - } - case linpermission.FieldMount: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field mount", values[i]) - } else if value.Valid { - lp.Mount = int8(value.Int64) - } - } - } - return nil -} - -// QueryLinGroup queries the "lin_group" edge of the LinPermission entity. -func (lp *LinPermission) QueryLinGroup() *LinGroupQuery { - return (&LinPermissionClient{config: lp.config}).QueryLinGroup(lp) -} - -// Update returns a builder for updating this LinPermission. -// Note that you need to call LinPermission.Unwrap() before calling this method if this LinPermission -// was returned from a transaction, and the transaction was committed or rolled back. -func (lp *LinPermission) Update() *LinPermissionUpdateOne { - return (&LinPermissionClient{config: lp.config}).UpdateOne(lp) -} - -// Unwrap unwraps the LinPermission 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 (lp *LinPermission) Unwrap() *LinPermission { - tx, ok := lp.config.driver.(*txDriver) - if !ok { - panic("model: LinPermission is not a transactional entity") - } - lp.config.driver = tx.drv - return lp -} - -// String implements the fmt.Stringer. -func (lp *LinPermission) String() string { - var builder strings.Builder - builder.WriteString("LinPermission(") - builder.WriteString(fmt.Sprintf("id=%v", lp.ID)) - builder.WriteString(", name=") - builder.WriteString(lp.Name) - builder.WriteString(", module=") - builder.WriteString(lp.Module) - builder.WriteString(", mount=") - builder.WriteString(fmt.Sprintf("%v", lp.Mount)) - builder.WriteByte(')') - return builder.String() -} - -// LinPermissions is a parsable slice of LinPermission. -type LinPermissions []*LinPermission - -func (lp LinPermissions) config(cfg config) { - for _i := range lp { - lp[_i].config = cfg - } -} diff --git a/internal/data/model/linpermission/linpermission.go b/internal/data/model/linpermission/linpermission.go deleted file mode 100644 index 09861cc..0000000 --- a/internal/data/model/linpermission/linpermission.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linpermission - -const ( - // Label holds the string label denoting the linpermission type in the database. - Label = "lin_permission" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldName holds the string denoting the name field in the database. - FieldName = "name" - // FieldModule holds the string denoting the module field in the database. - FieldModule = "module" - // FieldMount holds the string denoting the mount field in the database. - FieldMount = "mount" - // EdgeLinGroup holds the string denoting the lin_group edge name in mutations. - EdgeLinGroup = "lin_group" - // Table holds the table name of the linpermission in the database. - Table = "lin_permission" - // LinGroupTable is the table that holds the lin_group relation/edge. The primary key declared below. - LinGroupTable = "lin_permission_lin_group" - // LinGroupInverseTable is the table name for the LinGroup entity. - // It exists in this package in order to avoid circular dependency with the "lingroup" package. - LinGroupInverseTable = "lin_group" -) - -// Columns holds all SQL columns for linpermission fields. -var Columns = []string{ - FieldID, - FieldName, - FieldModule, - FieldMount, -} - -var ( - // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the - // primary key for the lin_group relation (M2M). - LinGroupPrimaryKey = []string{"lin_permission_id", "lin_group_id"} -) - -// 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 -} diff --git a/internal/data/model/linpermission/where.go b/internal/data/model/linpermission/where.go deleted file mode 100644 index a28e920..0000000 --- a/internal/data/model/linpermission/where.go +++ /dev/null @@ -1,472 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linpermission - -import ( - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// Name applies equality check predicate on the "name" field. It's identical to NameEQ. -func Name(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) -} - -// Module applies equality check predicate on the "module" field. It's identical to ModuleEQ. -func Module(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldModule), v)) - }) -} - -// Mount applies equality check predicate on the "mount" field. It's identical to MountEQ. -func Mount(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMount), v)) - }) -} - -// NameEQ applies the EQ predicate on the "name" field. -func NameEQ(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) -} - -// NameNEQ applies the NEQ predicate on the "name" field. -func NameNEQ(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldName), v)) - }) -} - -// NameIn applies the In predicate on the "name" field. -func NameIn(vs ...string) predicate.LinPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldName), v...)) - }) -} - -// NameNotIn applies the NotIn predicate on the "name" field. -func NameNotIn(vs ...string) predicate.LinPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldName), v...)) - }) -} - -// NameGT applies the GT predicate on the "name" field. -func NameGT(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldName), v)) - }) -} - -// NameGTE applies the GTE predicate on the "name" field. -func NameGTE(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldName), v)) - }) -} - -// NameLT applies the LT predicate on the "name" field. -func NameLT(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldName), v)) - }) -} - -// NameLTE applies the LTE predicate on the "name" field. -func NameLTE(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldName), v)) - }) -} - -// NameContains applies the Contains predicate on the "name" field. -func NameContains(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldName), v)) - }) -} - -// NameHasPrefix applies the HasPrefix predicate on the "name" field. -func NameHasPrefix(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldName), v)) - }) -} - -// NameHasSuffix applies the HasSuffix predicate on the "name" field. -func NameHasSuffix(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldName), v)) - }) -} - -// NameEqualFold applies the EqualFold predicate on the "name" field. -func NameEqualFold(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldName), v)) - }) -} - -// NameContainsFold applies the ContainsFold predicate on the "name" field. -func NameContainsFold(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldName), v)) - }) -} - -// ModuleEQ applies the EQ predicate on the "module" field. -func ModuleEQ(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldModule), v)) - }) -} - -// ModuleNEQ applies the NEQ predicate on the "module" field. -func ModuleNEQ(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldModule), v)) - }) -} - -// ModuleIn applies the In predicate on the "module" field. -func ModuleIn(vs ...string) predicate.LinPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldModule), v...)) - }) -} - -// ModuleNotIn applies the NotIn predicate on the "module" field. -func ModuleNotIn(vs ...string) predicate.LinPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldModule), v...)) - }) -} - -// ModuleGT applies the GT predicate on the "module" field. -func ModuleGT(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldModule), v)) - }) -} - -// ModuleGTE applies the GTE predicate on the "module" field. -func ModuleGTE(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldModule), v)) - }) -} - -// ModuleLT applies the LT predicate on the "module" field. -func ModuleLT(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldModule), v)) - }) -} - -// ModuleLTE applies the LTE predicate on the "module" field. -func ModuleLTE(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldModule), v)) - }) -} - -// ModuleContains applies the Contains predicate on the "module" field. -func ModuleContains(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldModule), v)) - }) -} - -// ModuleHasPrefix applies the HasPrefix predicate on the "module" field. -func ModuleHasPrefix(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldModule), v)) - }) -} - -// ModuleHasSuffix applies the HasSuffix predicate on the "module" field. -func ModuleHasSuffix(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldModule), v)) - }) -} - -// ModuleEqualFold applies the EqualFold predicate on the "module" field. -func ModuleEqualFold(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldModule), v)) - }) -} - -// ModuleContainsFold applies the ContainsFold predicate on the "module" field. -func ModuleContainsFold(v string) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldModule), v)) - }) -} - -// MountEQ applies the EQ predicate on the "mount" field. -func MountEQ(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMount), v)) - }) -} - -// MountNEQ applies the NEQ predicate on the "mount" field. -func MountNEQ(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMount), v)) - }) -} - -// MountIn applies the In predicate on the "mount" field. -func MountIn(vs ...int8) predicate.LinPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMount), v...)) - }) -} - -// MountNotIn applies the NotIn predicate on the "mount" field. -func MountNotIn(vs ...int8) predicate.LinPermission { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinPermission(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMount), v...)) - }) -} - -// MountGT applies the GT predicate on the "mount" field. -func MountGT(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMount), v)) - }) -} - -// MountGTE applies the GTE predicate on the "mount" field. -func MountGTE(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMount), v)) - }) -} - -// MountLT applies the LT predicate on the "mount" field. -func MountLT(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMount), v)) - }) -} - -// MountLTE applies the LTE predicate on the "mount" field. -func MountLTE(v int8) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMount), v)) - }) -} - -// HasLinGroup applies the HasEdge predicate on the "lin_group" edge. -func HasLinGroup() predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinGroupTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, LinGroupTable, LinGroupPrimaryKey...), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasLinGroupWith applies the HasEdge predicate on the "lin_group" edge with a given conditions (other predicates). -func HasLinGroupWith(preds ...predicate.LinGroup) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinGroupInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, LinGroupTable, LinGroupPrimaryKey...), - ) - 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.LinPermission) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinPermission) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinPermission) predicate.LinPermission { - return predicate.LinPermission(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/linpermission_create.go b/internal/data/model/linpermission_create.go deleted file mode 100644 index 01e3d9b..0000000 --- a/internal/data/model/linpermission_create.go +++ /dev/null @@ -1,289 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linpermission" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinPermissionCreate is the builder for creating a LinPermission entity. -type LinPermissionCreate struct { - config - mutation *LinPermissionMutation - hooks []Hook -} - -// SetName sets the "name" field. -func (lpc *LinPermissionCreate) SetName(s string) *LinPermissionCreate { - lpc.mutation.SetName(s) - return lpc -} - -// SetModule sets the "module" field. -func (lpc *LinPermissionCreate) SetModule(s string) *LinPermissionCreate { - lpc.mutation.SetModule(s) - return lpc -} - -// SetMount sets the "mount" field. -func (lpc *LinPermissionCreate) SetMount(i int8) *LinPermissionCreate { - lpc.mutation.SetMount(i) - return lpc -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. -func (lpc *LinPermissionCreate) AddLinGroupIDs(ids ...int) *LinPermissionCreate { - lpc.mutation.AddLinGroupIDs(ids...) - return lpc -} - -// AddLinGroup adds the "lin_group" edges to the LinGroup entity. -func (lpc *LinPermissionCreate) AddLinGroup(l ...*LinGroup) *LinPermissionCreate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lpc.AddLinGroupIDs(ids...) -} - -// Mutation returns the LinPermissionMutation object of the builder. -func (lpc *LinPermissionCreate) Mutation() *LinPermissionMutation { - return lpc.mutation -} - -// Save creates the LinPermission in the database. -func (lpc *LinPermissionCreate) Save(ctx context.Context) (*LinPermission, error) { - var ( - err error - node *LinPermission - ) - if len(lpc.hooks) == 0 { - if err = lpc.check(); err != nil { - return nil, err - } - node, err = lpc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = lpc.check(); err != nil { - return nil, err - } - lpc.mutation = mutation - if node, err = lpc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(lpc.hooks) - 1; i >= 0; i-- { - if lpc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lpc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lpc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (lpc *LinPermissionCreate) SaveX(ctx context.Context) *LinPermission { - v, err := lpc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lpc *LinPermissionCreate) Exec(ctx context.Context) error { - _, err := lpc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lpc *LinPermissionCreate) ExecX(ctx context.Context) { - if err := lpc.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (lpc *LinPermissionCreate) check() error { - if _, ok := lpc.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} - } - if _, ok := lpc.mutation.Module(); !ok { - return &ValidationError{Name: "module", err: errors.New(`model: missing required field "module"`)} - } - if _, ok := lpc.mutation.Mount(); !ok { - return &ValidationError{Name: "mount", err: errors.New(`model: missing required field "mount"`)} - } - return nil -} - -func (lpc *LinPermissionCreate) sqlSave(ctx context.Context) (*LinPermission, error) { - _node, _spec := lpc.createSpec() - if err := sqlgraph.CreateNode(ctx, lpc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (lpc *LinPermissionCreate) createSpec() (*LinPermission, *sqlgraph.CreateSpec) { - var ( - _node = &LinPermission{config: lpc.config} - _spec = &sqlgraph.CreateSpec{ - Table: linpermission.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - } - ) - if value, ok := lpc.mutation.Name(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linpermission.FieldName, - }) - _node.Name = value - } - if value, ok := lpc.mutation.Module(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linpermission.FieldModule, - }) - _node.Module = value - } - if value, ok := lpc.mutation.Mount(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linpermission.FieldMount, - }) - _node.Mount = value - } - if nodes := lpc.mutation.LinGroupIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// LinPermissionCreateBulk is the builder for creating many LinPermission entities in bulk. -type LinPermissionCreateBulk struct { - config - builders []*LinPermissionCreate -} - -// Save creates the LinPermission entities in the database. -func (lpcb *LinPermissionCreateBulk) Save(ctx context.Context) ([]*LinPermission, error) { - specs := make([]*sqlgraph.CreateSpec, len(lpcb.builders)) - nodes := make([]*LinPermission, len(lpcb.builders)) - mutators := make([]Mutator, len(lpcb.builders)) - for i := range lpcb.builders { - func(i int, root context.Context) { - builder := lpcb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, lpcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, lpcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, lpcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (lpcb *LinPermissionCreateBulk) SaveX(ctx context.Context) []*LinPermission { - v, err := lpcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lpcb *LinPermissionCreateBulk) Exec(ctx context.Context) error { - _, err := lpcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lpcb *LinPermissionCreateBulk) ExecX(ctx context.Context) { - if err := lpcb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/linpermission_delete.go b/internal/data/model/linpermission_delete.go deleted file mode 100644 index 46660ba..0000000 --- a/internal/data/model/linpermission_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinPermissionDelete is the builder for deleting a LinPermission entity. -type LinPermissionDelete struct { - config - hooks []Hook - mutation *LinPermissionMutation -} - -// Where appends a list predicates to the LinPermissionDelete builder. -func (lpd *LinPermissionDelete) Where(ps ...predicate.LinPermission) *LinPermissionDelete { - lpd.mutation.Where(ps...) - return lpd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (lpd *LinPermissionDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lpd.hooks) == 0 { - affected, err = lpd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lpd.mutation = mutation - affected, err = lpd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(lpd.hooks) - 1; i >= 0; i-- { - if lpd.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lpd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lpd.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lpd *LinPermissionDelete) ExecX(ctx context.Context) int { - n, err := lpd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (lpd *LinPermissionDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linpermission.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - if ps := lpd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, lpd.driver, _spec) -} - -// LinPermissionDeleteOne is the builder for deleting a single LinPermission entity. -type LinPermissionDeleteOne struct { - lpd *LinPermissionDelete -} - -// Exec executes the deletion query. -func (lpdo *LinPermissionDeleteOne) Exec(ctx context.Context) error { - n, err := lpdo.lpd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{linpermission.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (lpdo *LinPermissionDeleteOne) ExecX(ctx context.Context) { - lpdo.lpd.ExecX(ctx) -} diff --git a/internal/data/model/linpermission_query.go b/internal/data/model/linpermission_query.go deleted file mode 100644 index 9ae25bc..0000000 --- a/internal/data/model/linpermission_query.go +++ /dev/null @@ -1,1068 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "database/sql/driver" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinPermissionQuery is the builder for querying LinPermission entities. -type LinPermissionQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinPermission - // eager-loading edges. - withLinGroup *LinGroupQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinPermissionQuery builder. -func (lpq *LinPermissionQuery) Where(ps ...predicate.LinPermission) *LinPermissionQuery { - lpq.predicates = append(lpq.predicates, ps...) - return lpq -} - -// Limit adds a limit step to the query. -func (lpq *LinPermissionQuery) Limit(limit int) *LinPermissionQuery { - lpq.limit = &limit - return lpq -} - -// Offset adds an offset step to the query. -func (lpq *LinPermissionQuery) Offset(offset int) *LinPermissionQuery { - lpq.offset = &offset - return lpq -} - -// 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 (lpq *LinPermissionQuery) Unique(unique bool) *LinPermissionQuery { - lpq.unique = &unique - return lpq -} - -// Order adds an order step to the query. -func (lpq *LinPermissionQuery) Order(o ...OrderFunc) *LinPermissionQuery { - lpq.order = append(lpq.order, o...) - return lpq -} - -// QueryLinGroup chains the current query on the "lin_group" edge. -func (lpq *LinPermissionQuery) QueryLinGroup() *LinGroupQuery { - query := &LinGroupQuery{config: lpq.config} - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := lpq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := lpq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(linpermission.Table, linpermission.FieldID, selector), - sqlgraph.To(lingroup.Table, lingroup.FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, linpermission.LinGroupTable, linpermission.LinGroupPrimaryKey...), - ) - fromU = sqlgraph.SetNeighbors(lpq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first LinPermission entity from the query. -// Returns a *NotFoundError when no LinPermission was found. -func (lpq *LinPermissionQuery) First(ctx context.Context) (*LinPermission, error) { - nodes, err := lpq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linpermission.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (lpq *LinPermissionQuery) FirstX(ctx context.Context) *LinPermission { - node, err := lpq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinPermission ID from the query. -// Returns a *NotFoundError when no LinPermission ID was found. -func (lpq *LinPermissionQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lpq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linpermission.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (lpq *LinPermissionQuery) FirstIDX(ctx context.Context) int { - id, err := lpq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinPermission entity from the query. -// Returns a *NotFoundError when no LinPermission was found. -func (lpq *LinPermissionQuery) Last(ctx context.Context) (*LinPermission, error) { - nodes, err := lpq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linpermission.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (lpq *LinPermissionQuery) LastX(ctx context.Context) *LinPermission { - node, err := lpq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinPermission ID from the query. -// Returns a *NotFoundError when no LinPermission ID was found. -func (lpq *LinPermissionQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lpq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linpermission.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (lpq *LinPermissionQuery) LastIDX(ctx context.Context) int { - id, err := lpq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinPermission entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinPermission entity is not found. -// Returns a *NotFoundError when no LinPermission entities are found. -func (lpq *LinPermissionQuery) Only(ctx context.Context) (*LinPermission, error) { - nodes, err := lpq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{linpermission.Label} - default: - return nil, &NotSingularError{linpermission.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (lpq *LinPermissionQuery) OnlyX(ctx context.Context) *LinPermission { - node, err := lpq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinPermission ID in the query. -// Returns a *NotSingularError when exactly one LinPermission ID is not found. -// Returns a *NotFoundError when no entities are found. -func (lpq *LinPermissionQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = lpq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = &NotSingularError{linpermission.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (lpq *LinPermissionQuery) OnlyIDX(ctx context.Context) int { - id, err := lpq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinPermissions. -func (lpq *LinPermissionQuery) All(ctx context.Context) ([]*LinPermission, error) { - if err := lpq.prepareQuery(ctx); err != nil { - return nil, err - } - return lpq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (lpq *LinPermissionQuery) AllX(ctx context.Context) []*LinPermission { - nodes, err := lpq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinPermission IDs. -func (lpq *LinPermissionQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := lpq.Select(linpermission.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (lpq *LinPermissionQuery) IDsX(ctx context.Context) []int { - ids, err := lpq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (lpq *LinPermissionQuery) Count(ctx context.Context) (int, error) { - if err := lpq.prepareQuery(ctx); err != nil { - return 0, err - } - return lpq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (lpq *LinPermissionQuery) CountX(ctx context.Context) int { - count, err := lpq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (lpq *LinPermissionQuery) Exist(ctx context.Context) (bool, error) { - if err := lpq.prepareQuery(ctx); err != nil { - return false, err - } - return lpq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (lpq *LinPermissionQuery) ExistX(ctx context.Context) bool { - exist, err := lpq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinPermissionQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (lpq *LinPermissionQuery) Clone() *LinPermissionQuery { - if lpq == nil { - return nil - } - return &LinPermissionQuery{ - config: lpq.config, - limit: lpq.limit, - offset: lpq.offset, - order: append([]OrderFunc{}, lpq.order...), - predicates: append([]predicate.LinPermission{}, lpq.predicates...), - withLinGroup: lpq.withLinGroup.Clone(), - // clone intermediate query. - sql: lpq.sql.Clone(), - path: lpq.path, - } -} - -// WithLinGroup tells the query-builder to eager-load the nodes that are connected to -// the "lin_group" edge. The optional arguments are used to configure the query builder of the edge. -func (lpq *LinPermissionQuery) WithLinGroup(opts ...func(*LinGroupQuery)) *LinPermissionQuery { - query := &LinGroupQuery{config: lpq.config} - for _, opt := range opts { - opt(query) - } - lpq.withLinGroup = query - return lpq -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinPermission.Query(). -// GroupBy(linpermission.FieldName). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (lpq *LinPermissionQuery) GroupBy(field string, fields ...string) *LinPermissionGroupBy { - group := &LinPermissionGroupBy{config: lpq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := lpq.prepareQuery(ctx); err != nil { - return nil, err - } - return lpq.sqlQuery(ctx), nil - } - return group -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// } -// -// client.LinPermission.Query(). -// Select(linpermission.FieldName). -// Scan(ctx, &v) -// -func (lpq *LinPermissionQuery) Select(fields ...string) *LinPermissionSelect { - lpq.fields = append(lpq.fields, fields...) - return &LinPermissionSelect{LinPermissionQuery: lpq} -} - -func (lpq *LinPermissionQuery) prepareQuery(ctx context.Context) error { - for _, f := range lpq.fields { - if !linpermission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if lpq.path != nil { - prev, err := lpq.path(ctx) - if err != nil { - return err - } - lpq.sql = prev - } - return nil -} - -func (lpq *LinPermissionQuery) sqlAll(ctx context.Context) ([]*LinPermission, error) { - var ( - nodes = []*LinPermission{} - _spec = lpq.querySpec() - loadedTypes = [1]bool{ - lpq.withLinGroup != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinPermission{config: lpq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, lpq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - - if query := lpq.withLinGroup; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - ids := make(map[int]*LinPermission, len(nodes)) - for _, node := range nodes { - ids[node.ID] = node - fks = append(fks, node.ID) - node.Edges.LinGroup = []*LinGroup{} - } - var ( - edgeids []int - edges = make(map[int][]*LinPermission) - ) - _spec := &sqlgraph.EdgeQuerySpec{ - Edge: &sqlgraph.EdgeSpec{ - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - }, - Predicate: func(s *sql.Selector) { - s.Where(sql.InValues(linpermission.LinGroupPrimaryKey[0], fks...)) - }, - ScanValues: func() [2]interface{} { - return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} - }, - Assign: func(out, in interface{}) error { - eout, ok := out.(*sql.NullInt64) - if !ok || eout == nil { - return fmt.Errorf("unexpected id value for edge-out") - } - ein, ok := in.(*sql.NullInt64) - if !ok || ein == nil { - return fmt.Errorf("unexpected id value for edge-in") - } - outValue := int(eout.Int64) - inValue := int(ein.Int64) - node, ok := ids[outValue] - if !ok { - return fmt.Errorf("unexpected node id in edges: %v", outValue) - } - if _, ok := edges[inValue]; !ok { - edgeids = append(edgeids, inValue) - } - edges[inValue] = append(edges[inValue], node) - return nil - }, - } - if err := sqlgraph.QueryEdges(ctx, lpq.driver, _spec); err != nil { - return nil, fmt.Errorf(`query edges "lin_group": %w`, err) - } - query.Where(lingroup.IDIn(edgeids...)) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err - } - for _, n := range neighbors { - nodes, ok := edges[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected "lin_group" node returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.LinGroup = append(nodes[i].Edges.LinGroup, n) - } - } - } - - return nodes, nil -} - -func (lpq *LinPermissionQuery) sqlCount(ctx context.Context) (int, error) { - _spec := lpq.querySpec() - return sqlgraph.CountNodes(ctx, lpq.driver, _spec) -} - -func (lpq *LinPermissionQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := lpq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (lpq *LinPermissionQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: linpermission.Table, - Columns: linpermission.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - From: lpq.sql, - Unique: true, - } - if unique := lpq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := lpq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linpermission.FieldID) - for i := range fields { - if fields[i] != linpermission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := lpq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := lpq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := lpq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := lpq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (lpq *LinPermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(lpq.driver.Dialect()) - t1 := builder.Table(linpermission.Table) - columns := lpq.fields - if len(columns) == 0 { - columns = linpermission.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if lpq.sql != nil { - selector = lpq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range lpq.predicates { - p(selector) - } - for _, p := range lpq.order { - p(selector) - } - if offset := lpq.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 := lpq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinPermissionGroupBy is the group-by builder for LinPermission entities. -type LinPermissionGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (lpgb *LinPermissionGroupBy) Aggregate(fns ...AggregateFunc) *LinPermissionGroupBy { - lpgb.fns = append(lpgb.fns, fns...) - return lpgb -} - -// Scan applies the group-by query and scans the result into the given value. -func (lpgb *LinPermissionGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := lpgb.path(ctx) - if err != nil { - return err - } - lpgb.sql = query - return lpgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := lpgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(lpgb.fields) > 1 { - return nil, errors.New("model: LinPermissionGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := lpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) StringsX(ctx context.Context) []string { - v, err := lpgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lpgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) StringX(ctx context.Context) string { - v, err := lpgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(lpgb.fields) > 1 { - return nil, errors.New("model: LinPermissionGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := lpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) IntsX(ctx context.Context) []int { - v, err := lpgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lpgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) IntX(ctx context.Context) int { - v, err := lpgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(lpgb.fields) > 1 { - return nil, errors.New("model: LinPermissionGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := lpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := lpgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lpgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) Float64X(ctx context.Context) float64 { - v, err := lpgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(lpgb.fields) > 1 { - return nil, errors.New("model: LinPermissionGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := lpgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) BoolsX(ctx context.Context) []bool { - v, err := lpgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lpgb *LinPermissionGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lpgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lpgb *LinPermissionGroupBy) BoolX(ctx context.Context) bool { - v, err := lpgb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lpgb *LinPermissionGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range lpgb.fields { - if !linpermission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := lpgb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := lpgb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (lpgb *LinPermissionGroupBy) sqlQuery() *sql.Selector { - selector := lpgb.sql.Select() - aggregation := make([]string, 0, len(lpgb.fns)) - for _, fn := range lpgb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(lpgb.fields)+len(lpgb.fns)) - for _, f := range lpgb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(lpgb.fields...)...) -} - -// LinPermissionSelect is the builder for selecting fields of LinPermission entities. -type LinPermissionSelect struct { - *LinPermissionQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (lps *LinPermissionSelect) Scan(ctx context.Context, v interface{}) error { - if err := lps.prepareQuery(ctx); err != nil { - return err - } - lps.sql = lps.LinPermissionQuery.sqlQuery(ctx) - return lps.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lps *LinPermissionSelect) ScanX(ctx context.Context, v interface{}) { - if err := lps.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Strings(ctx context.Context) ([]string, error) { - if len(lps.fields) > 1 { - return nil, errors.New("model: LinPermissionSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := lps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lps *LinPermissionSelect) StringsX(ctx context.Context) []string { - v, err := lps.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lps.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lps *LinPermissionSelect) StringX(ctx context.Context) string { - v, err := lps.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Ints(ctx context.Context) ([]int, error) { - if len(lps.fields) > 1 { - return nil, errors.New("model: LinPermissionSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := lps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lps *LinPermissionSelect) IntsX(ctx context.Context) []int { - v, err := lps.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lps.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lps *LinPermissionSelect) IntX(ctx context.Context) int { - v, err := lps.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(lps.fields) > 1 { - return nil, errors.New("model: LinPermissionSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := lps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lps *LinPermissionSelect) Float64sX(ctx context.Context) []float64 { - v, err := lps.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lps.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lps *LinPermissionSelect) Float64X(ctx context.Context) float64 { - v, err := lps.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Bools(ctx context.Context) ([]bool, error) { - if len(lps.fields) > 1 { - return nil, errors.New("model: LinPermissionSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := lps.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lps *LinPermissionSelect) BoolsX(ctx context.Context) []bool { - v, err := lps.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (lps *LinPermissionSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lps.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linpermission.Label} - default: - err = fmt.Errorf("model: LinPermissionSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lps *LinPermissionSelect) BoolX(ctx context.Context) bool { - v, err := lps.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lps *LinPermissionSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := lps.sql.Query() - if err := lps.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/linpermission_update.go b/internal/data/model/linpermission_update.go deleted file mode 100644 index cbc1e37..0000000 --- a/internal/data/model/linpermission_update.go +++ /dev/null @@ -1,525 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinPermissionUpdate is the builder for updating LinPermission entities. -type LinPermissionUpdate struct { - config - hooks []Hook - mutation *LinPermissionMutation -} - -// Where appends a list predicates to the LinPermissionUpdate builder. -func (lpu *LinPermissionUpdate) Where(ps ...predicate.LinPermission) *LinPermissionUpdate { - lpu.mutation.Where(ps...) - return lpu -} - -// SetName sets the "name" field. -func (lpu *LinPermissionUpdate) SetName(s string) *LinPermissionUpdate { - lpu.mutation.SetName(s) - return lpu -} - -// SetModule sets the "module" field. -func (lpu *LinPermissionUpdate) SetModule(s string) *LinPermissionUpdate { - lpu.mutation.SetModule(s) - return lpu -} - -// SetMount sets the "mount" field. -func (lpu *LinPermissionUpdate) SetMount(i int8) *LinPermissionUpdate { - lpu.mutation.ResetMount() - lpu.mutation.SetMount(i) - return lpu -} - -// AddMount adds i to the "mount" field. -func (lpu *LinPermissionUpdate) AddMount(i int8) *LinPermissionUpdate { - lpu.mutation.AddMount(i) - return lpu -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. -func (lpu *LinPermissionUpdate) AddLinGroupIDs(ids ...int) *LinPermissionUpdate { - lpu.mutation.AddLinGroupIDs(ids...) - return lpu -} - -// AddLinGroup adds the "lin_group" edges to the LinGroup entity. -func (lpu *LinPermissionUpdate) AddLinGroup(l ...*LinGroup) *LinPermissionUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lpu.AddLinGroupIDs(ids...) -} - -// Mutation returns the LinPermissionMutation object of the builder. -func (lpu *LinPermissionUpdate) Mutation() *LinPermissionMutation { - return lpu.mutation -} - -// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. -func (lpu *LinPermissionUpdate) ClearLinGroup() *LinPermissionUpdate { - lpu.mutation.ClearLinGroup() - return lpu -} - -// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. -func (lpu *LinPermissionUpdate) RemoveLinGroupIDs(ids ...int) *LinPermissionUpdate { - lpu.mutation.RemoveLinGroupIDs(ids...) - return lpu -} - -// RemoveLinGroup removes "lin_group" edges to LinGroup entities. -func (lpu *LinPermissionUpdate) RemoveLinGroup(l ...*LinGroup) *LinPermissionUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lpu.RemoveLinGroupIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (lpu *LinPermissionUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lpu.hooks) == 0 { - affected, err = lpu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lpu.mutation = mutation - affected, err = lpu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(lpu.hooks) - 1; i >= 0; i-- { - if lpu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lpu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lpu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lpu *LinPermissionUpdate) SaveX(ctx context.Context) int { - affected, err := lpu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (lpu *LinPermissionUpdate) Exec(ctx context.Context) error { - _, err := lpu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lpu *LinPermissionUpdate) ExecX(ctx context.Context) { - if err := lpu.Exec(ctx); err != nil { - panic(err) - } -} - -func (lpu *LinPermissionUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linpermission.Table, - Columns: linpermission.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - if ps := lpu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lpu.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linpermission.FieldName, - }) - } - if value, ok := lpu.mutation.Module(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linpermission.FieldModule, - }) - } - if value, ok := lpu.mutation.Mount(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linpermission.FieldMount, - }) - } - if value, ok := lpu.mutation.AddedMount(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linpermission.FieldMount, - }) - } - if lpu.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lpu.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !lpu.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lpu.mutation.LinGroupIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if n, err = sqlgraph.UpdateNodes(ctx, lpu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linpermission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinPermissionUpdateOne is the builder for updating a single LinPermission entity. -type LinPermissionUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinPermissionMutation -} - -// SetName sets the "name" field. -func (lpuo *LinPermissionUpdateOne) SetName(s string) *LinPermissionUpdateOne { - lpuo.mutation.SetName(s) - return lpuo -} - -// SetModule sets the "module" field. -func (lpuo *LinPermissionUpdateOne) SetModule(s string) *LinPermissionUpdateOne { - lpuo.mutation.SetModule(s) - return lpuo -} - -// SetMount sets the "mount" field. -func (lpuo *LinPermissionUpdateOne) SetMount(i int8) *LinPermissionUpdateOne { - lpuo.mutation.ResetMount() - lpuo.mutation.SetMount(i) - return lpuo -} - -// AddMount adds i to the "mount" field. -func (lpuo *LinPermissionUpdateOne) AddMount(i int8) *LinPermissionUpdateOne { - lpuo.mutation.AddMount(i) - return lpuo -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. -func (lpuo *LinPermissionUpdateOne) AddLinGroupIDs(ids ...int) *LinPermissionUpdateOne { - lpuo.mutation.AddLinGroupIDs(ids...) - return lpuo -} - -// AddLinGroup adds the "lin_group" edges to the LinGroup entity. -func (lpuo *LinPermissionUpdateOne) AddLinGroup(l ...*LinGroup) *LinPermissionUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lpuo.AddLinGroupIDs(ids...) -} - -// Mutation returns the LinPermissionMutation object of the builder. -func (lpuo *LinPermissionUpdateOne) Mutation() *LinPermissionMutation { - return lpuo.mutation -} - -// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. -func (lpuo *LinPermissionUpdateOne) ClearLinGroup() *LinPermissionUpdateOne { - lpuo.mutation.ClearLinGroup() - return lpuo -} - -// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. -func (lpuo *LinPermissionUpdateOne) RemoveLinGroupIDs(ids ...int) *LinPermissionUpdateOne { - lpuo.mutation.RemoveLinGroupIDs(ids...) - return lpuo -} - -// RemoveLinGroup removes "lin_group" edges to LinGroup entities. -func (lpuo *LinPermissionUpdateOne) RemoveLinGroup(l ...*LinGroup) *LinPermissionUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return lpuo.RemoveLinGroupIDs(ids...) -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (lpuo *LinPermissionUpdateOne) Select(field string, fields ...string) *LinPermissionUpdateOne { - lpuo.fields = append([]string{field}, fields...) - return lpuo -} - -// Save executes the query and returns the updated LinPermission entity. -func (lpuo *LinPermissionUpdateOne) Save(ctx context.Context) (*LinPermission, error) { - var ( - err error - node *LinPermission - ) - if len(lpuo.hooks) == 0 { - node, err = lpuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinPermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lpuo.mutation = mutation - node, err = lpuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(lpuo.hooks) - 1; i >= 0; i-- { - if lpuo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lpuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lpuo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (lpuo *LinPermissionUpdateOne) SaveX(ctx context.Context) *LinPermission { - node, err := lpuo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (lpuo *LinPermissionUpdateOne) Exec(ctx context.Context) error { - _, err := lpuo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lpuo *LinPermissionUpdateOne) ExecX(ctx context.Context) { - if err := lpuo.Exec(ctx); err != nil { - panic(err) - } -} - -func (lpuo *LinPermissionUpdateOne) sqlSave(ctx context.Context) (_node *LinPermission, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linpermission.Table, - Columns: linpermission.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linpermission.FieldID, - }, - }, - } - id, ok := lpuo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinPermission.ID for update")} - } - _spec.Node.ID.Value = id - if fields := lpuo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linpermission.FieldID) - for _, f := range fields { - if !linpermission.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != linpermission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := lpuo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := lpuo.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linpermission.FieldName, - }) - } - if value, ok := lpuo.mutation.Module(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linpermission.FieldModule, - }) - } - if value, ok := lpuo.mutation.Mount(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linpermission.FieldMount, - }) - } - if value, ok := lpuo.mutation.AddedMount(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt8, - Value: value, - Column: linpermission.FieldMount, - }) - } - if lpuo.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lpuo.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !lpuo.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := lpuo.mutation.LinGroupIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: linpermission.LinGroupTable, - Columns: linpermission.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &LinPermission{config: lpuo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, lpuo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linpermission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/linuser.go b/internal/data/model/linuser.go deleted file mode 100644 index 1a587e7..0000000 --- a/internal/data/model/linuser.go +++ /dev/null @@ -1,208 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/linuser" - "strings" - "time" - - "entgo.io/ent/dialect/sql" -) - -// LinUser is the model entity for the LinUser schema. -type LinUser struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // CreateTime holds the value of the "create_time" field. - CreateTime time.Time `json:"create_time,omitempty"` - // UpdateTime holds the value of the "update_time" field. - UpdateTime time.Time `json:"update_time,omitempty"` - // DeleteTime holds the value of the "delete_time" field. - DeleteTime time.Time `json:"delete_time,omitempty"` - // Username holds the value of the "username" field. - // 用户名,唯一 - Username string `json:"username,omitempty"` - // Nickname holds the value of the "nickname" field. - // 用户昵称 - Nickname string `json:"nickname,omitempty"` - // Avatar holds the value of the "avatar" field. - // 头像url - Avatar string `json:"avatar,omitempty"` - // Email holds the value of the "email" field. - // 邮箱 - Email string `json:"email,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the LinUserQuery when eager-loading is set. - Edges LinUserEdges `json:"edges"` -} - -// LinUserEdges holds the relations/edges for other nodes in the graph. -type LinUserEdges struct { - // LinUserIdentiy holds the value of the lin_user_identiy edge. - LinUserIdentiy []*LinUserIdentiy `json:"lin_user_identiy,omitempty"` - // LinGroup holds the value of the lin_group edge. - LinGroup []*LinGroup `json:"lin_group,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool -} - -// LinUserIdentiyOrErr returns the LinUserIdentiy value or an error if the edge -// was not loaded in eager-loading. -func (e LinUserEdges) LinUserIdentiyOrErr() ([]*LinUserIdentiy, error) { - if e.loadedTypes[0] { - return e.LinUserIdentiy, nil - } - return nil, &NotLoadedError{edge: "lin_user_identiy"} -} - -// LinGroupOrErr returns the LinGroup value or an error if the edge -// was not loaded in eager-loading. -func (e LinUserEdges) LinGroupOrErr() ([]*LinGroup, error) { - if e.loadedTypes[1] { - return e.LinGroup, nil - } - return nil, &NotLoadedError{edge: "lin_group"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinUser) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case linuser.FieldID: - values[i] = new(sql.NullInt64) - case linuser.FieldUsername, linuser.FieldNickname, linuser.FieldAvatar, linuser.FieldEmail: - values[i] = new(sql.NullString) - case linuser.FieldCreateTime, linuser.FieldUpdateTime, linuser.FieldDeleteTime: - values[i] = new(sql.NullTime) - default: - return nil, fmt.Errorf("unexpected column %q for type LinUser", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinUser fields. -func (lu *LinUser) assignValues(columns []string, values []interface{}) 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 linuser.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - lu.ID = int(value.Int64) - case linuser.FieldCreateTime: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field create_time", values[i]) - } else if value.Valid { - lu.CreateTime = value.Time - } - case linuser.FieldUpdateTime: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field update_time", values[i]) - } else if value.Valid { - lu.UpdateTime = value.Time - } - case linuser.FieldDeleteTime: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field delete_time", values[i]) - } else if value.Valid { - lu.DeleteTime = value.Time - } - case linuser.FieldUsername: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field username", values[i]) - } else if value.Valid { - lu.Username = value.String - } - case linuser.FieldNickname: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field nickname", values[i]) - } else if value.Valid { - lu.Nickname = value.String - } - case linuser.FieldAvatar: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field avatar", values[i]) - } else if value.Valid { - lu.Avatar = value.String - } - case linuser.FieldEmail: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field email", values[i]) - } else if value.Valid { - lu.Email = value.String - } - } - } - return nil -} - -// QueryLinUserIdentiy queries the "lin_user_identiy" edge of the LinUser entity. -func (lu *LinUser) QueryLinUserIdentiy() *LinUserIdentiyQuery { - return (&LinUserClient{config: lu.config}).QueryLinUserIdentiy(lu) -} - -// QueryLinGroup queries the "lin_group" edge of the LinUser entity. -func (lu *LinUser) QueryLinGroup() *LinGroupQuery { - return (&LinUserClient{config: lu.config}).QueryLinGroup(lu) -} - -// Update returns a builder for updating this LinUser. -// Note that you need to call LinUser.Unwrap() before calling this method if this LinUser -// was returned from a transaction, and the transaction was committed or rolled back. -func (lu *LinUser) Update() *LinUserUpdateOne { - return (&LinUserClient{config: lu.config}).UpdateOne(lu) -} - -// Unwrap unwraps the LinUser 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 (lu *LinUser) Unwrap() *LinUser { - tx, ok := lu.config.driver.(*txDriver) - if !ok { - panic("model: LinUser is not a transactional entity") - } - lu.config.driver = tx.drv - return lu -} - -// String implements the fmt.Stringer. -func (lu *LinUser) String() string { - var builder strings.Builder - builder.WriteString("LinUser(") - builder.WriteString(fmt.Sprintf("id=%v", lu.ID)) - builder.WriteString(", create_time=") - builder.WriteString(lu.CreateTime.Format(time.ANSIC)) - builder.WriteString(", update_time=") - builder.WriteString(lu.UpdateTime.Format(time.ANSIC)) - builder.WriteString(", delete_time=") - builder.WriteString(lu.DeleteTime.Format(time.ANSIC)) - builder.WriteString(", username=") - builder.WriteString(lu.Username) - builder.WriteString(", nickname=") - builder.WriteString(lu.Nickname) - builder.WriteString(", avatar=") - builder.WriteString(lu.Avatar) - builder.WriteString(", email=") - builder.WriteString(lu.Email) - builder.WriteByte(')') - return builder.String() -} - -// LinUsers is a parsable slice of LinUser. -type LinUsers []*LinUser - -func (lu LinUsers) config(cfg config) { - for _i := range lu { - lu[_i].config = cfg - } -} diff --git a/internal/data/model/linuser/linuser.go b/internal/data/model/linuser/linuser.go deleted file mode 100644 index 8943e07..0000000 --- a/internal/data/model/linuser/linuser.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linuser - -import ( - "time" -) - -const ( - // Label holds the string label denoting the linuser type in the database. - Label = "lin_user" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldCreateTime holds the string denoting the create_time field in the database. - FieldCreateTime = "create_time" - // FieldUpdateTime holds the string denoting the update_time field in the database. - FieldUpdateTime = "update_time" - // FieldDeleteTime holds the string denoting the delete_time field in the database. - FieldDeleteTime = "delete_time" - // FieldUsername holds the string denoting the username field in the database. - FieldUsername = "username" - // FieldNickname holds the string denoting the nickname field in the database. - FieldNickname = "nickname" - // FieldAvatar holds the string denoting the avatar field in the database. - FieldAvatar = "avatar" - // FieldEmail holds the string denoting the email field in the database. - FieldEmail = "email" - // EdgeLinUserIdentiy holds the string denoting the lin_user_identiy edge name in mutations. - EdgeLinUserIdentiy = "lin_user_identiy" - // EdgeLinGroup holds the string denoting the lin_group edge name in mutations. - EdgeLinGroup = "lin_group" - // Table holds the table name of the linuser in the database. - Table = "lin_user" - // LinUserIdentiyTable is the table that holds the lin_user_identiy relation/edge. - LinUserIdentiyTable = "lin_user_identiy" - // LinUserIdentiyInverseTable is the table name for the LinUserIdentiy entity. - // It exists in this package in order to avoid circular dependency with the "linuseridentiy" package. - LinUserIdentiyInverseTable = "lin_user_identiy" - // LinUserIdentiyColumn is the table column denoting the lin_user_identiy relation/edge. - LinUserIdentiyColumn = "lin_user_lin_user_identiy" - // LinGroupTable is the table that holds the lin_group relation/edge. The primary key declared below. - LinGroupTable = "lin_user_group" - // LinGroupInverseTable is the table name for the LinGroup entity. - // It exists in this package in order to avoid circular dependency with the "lingroup" package. - LinGroupInverseTable = "lin_group" -) - -// Columns holds all SQL columns for linuser fields. -var Columns = []string{ - FieldID, - FieldCreateTime, - FieldUpdateTime, - FieldDeleteTime, - FieldUsername, - FieldNickname, - FieldAvatar, - FieldEmail, -} - -var ( - // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the - // primary key for the lin_group relation (M2M). - LinGroupPrimaryKey = []string{"user_id", "group_id"} -) - -// 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 ( - // DefaultCreateTime holds the default value on creation for the "create_time" field. - DefaultCreateTime func() time.Time - // DefaultUpdateTime holds the default value on creation for the "update_time" field. - DefaultUpdateTime func() time.Time - // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. - UpdateDefaultUpdateTime func() time.Time - // DefaultDeleteTime holds the default value on creation for the "delete_time" field. - DefaultDeleteTime func() time.Time - // DefaultAvatar holds the default value on creation for the "avatar" field. - DefaultAvatar string -) diff --git a/internal/data/model/linuser/where.go b/internal/data/model/linuser/where.go deleted file mode 100644 index 2b13f11..0000000 --- a/internal/data/model/linuser/where.go +++ /dev/null @@ -1,903 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linuser - -import ( - "lin-cms-go/internal/data/model/predicate" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. -func CreateTime(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCreateTime), v)) - }) -} - -// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. -func UpdateTime(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUpdateTime), v)) - }) -} - -// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. -func DeleteTime(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldDeleteTime), v)) - }) -} - -// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. -func Username(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUsername), v)) - }) -} - -// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ. -func Nickname(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldNickname), v)) - }) -} - -// Avatar applies equality check predicate on the "avatar" field. It's identical to AvatarEQ. -func Avatar(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldAvatar), v)) - }) -} - -// Email applies equality check predicate on the "email" field. It's identical to EmailEQ. -func Email(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldEmail), v)) - }) -} - -// CreateTimeEQ applies the EQ predicate on the "create_time" field. -func CreateTimeEQ(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. -func CreateTimeNEQ(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeIn applies the In predicate on the "create_time" field. -func CreateTimeIn(vs ...time.Time) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldCreateTime), v...)) - }) -} - -// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. -func CreateTimeNotIn(vs ...time.Time) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) - }) -} - -// CreateTimeGT applies the GT predicate on the "create_time" field. -func CreateTimeGT(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeGTE applies the GTE predicate on the "create_time" field. -func CreateTimeGTE(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeLT applies the LT predicate on the "create_time" field. -func CreateTimeLT(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldCreateTime), v)) - }) -} - -// CreateTimeLTE applies the LTE predicate on the "create_time" field. -func CreateTimeLTE(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldCreateTime), v)) - }) -} - -// UpdateTimeEQ applies the EQ predicate on the "update_time" field. -func UpdateTimeEQ(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. -func UpdateTimeNEQ(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeIn applies the In predicate on the "update_time" field. -func UpdateTimeIn(vs ...time.Time) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUpdateTime), v...)) - }) -} - -// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. -func UpdateTimeNotIn(vs ...time.Time) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) - }) -} - -// UpdateTimeGT applies the GT predicate on the "update_time" field. -func UpdateTimeGT(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeGTE applies the GTE predicate on the "update_time" field. -func UpdateTimeGTE(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeLT applies the LT predicate on the "update_time" field. -func UpdateTimeLT(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUpdateTime), v)) - }) -} - -// UpdateTimeLTE applies the LTE predicate on the "update_time" field. -func UpdateTimeLTE(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUpdateTime), v)) - }) -} - -// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. -func DeleteTimeEQ(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. -func DeleteTimeNEQ(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeIn applies the In predicate on the "delete_time" field. -func DeleteTimeIn(vs ...time.Time) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldDeleteTime), v...)) - }) -} - -// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. -func DeleteTimeNotIn(vs ...time.Time) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) - }) -} - -// DeleteTimeGT applies the GT predicate on the "delete_time" field. -func DeleteTimeGT(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. -func DeleteTimeGTE(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeLT applies the LT predicate on the "delete_time" field. -func DeleteTimeLT(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldDeleteTime), v)) - }) -} - -// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. -func DeleteTimeLTE(v time.Time) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldDeleteTime), v)) - }) -} - -// UsernameEQ applies the EQ predicate on the "username" field. -func UsernameEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUsername), v)) - }) -} - -// UsernameNEQ applies the NEQ predicate on the "username" field. -func UsernameNEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUsername), v)) - }) -} - -// UsernameIn applies the In predicate on the "username" field. -func UsernameIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUsername), v...)) - }) -} - -// UsernameNotIn applies the NotIn predicate on the "username" field. -func UsernameNotIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUsername), v...)) - }) -} - -// UsernameGT applies the GT predicate on the "username" field. -func UsernameGT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUsername), v)) - }) -} - -// UsernameGTE applies the GTE predicate on the "username" field. -func UsernameGTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUsername), v)) - }) -} - -// UsernameLT applies the LT predicate on the "username" field. -func UsernameLT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUsername), v)) - }) -} - -// UsernameLTE applies the LTE predicate on the "username" field. -func UsernameLTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUsername), v)) - }) -} - -// UsernameContains applies the Contains predicate on the "username" field. -func UsernameContains(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldUsername), v)) - }) -} - -// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. -func UsernameHasPrefix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldUsername), v)) - }) -} - -// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. -func UsernameHasSuffix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldUsername), v)) - }) -} - -// UsernameEqualFold applies the EqualFold predicate on the "username" field. -func UsernameEqualFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldUsername), v)) - }) -} - -// UsernameContainsFold applies the ContainsFold predicate on the "username" field. -func UsernameContainsFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldUsername), v)) - }) -} - -// NicknameEQ applies the EQ predicate on the "nickname" field. -func NicknameEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldNickname), v)) - }) -} - -// NicknameNEQ applies the NEQ predicate on the "nickname" field. -func NicknameNEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldNickname), v)) - }) -} - -// NicknameIn applies the In predicate on the "nickname" field. -func NicknameIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldNickname), v...)) - }) -} - -// NicknameNotIn applies the NotIn predicate on the "nickname" field. -func NicknameNotIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldNickname), v...)) - }) -} - -// NicknameGT applies the GT predicate on the "nickname" field. -func NicknameGT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldNickname), v)) - }) -} - -// NicknameGTE applies the GTE predicate on the "nickname" field. -func NicknameGTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldNickname), v)) - }) -} - -// NicknameLT applies the LT predicate on the "nickname" field. -func NicknameLT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldNickname), v)) - }) -} - -// NicknameLTE applies the LTE predicate on the "nickname" field. -func NicknameLTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldNickname), v)) - }) -} - -// NicknameContains applies the Contains predicate on the "nickname" field. -func NicknameContains(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldNickname), v)) - }) -} - -// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field. -func NicknameHasPrefix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldNickname), v)) - }) -} - -// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field. -func NicknameHasSuffix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldNickname), v)) - }) -} - -// NicknameEqualFold applies the EqualFold predicate on the "nickname" field. -func NicknameEqualFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldNickname), v)) - }) -} - -// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field. -func NicknameContainsFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldNickname), v)) - }) -} - -// AvatarEQ applies the EQ predicate on the "avatar" field. -func AvatarEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldAvatar), v)) - }) -} - -// AvatarNEQ applies the NEQ predicate on the "avatar" field. -func AvatarNEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldAvatar), v)) - }) -} - -// AvatarIn applies the In predicate on the "avatar" field. -func AvatarIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldAvatar), v...)) - }) -} - -// AvatarNotIn applies the NotIn predicate on the "avatar" field. -func AvatarNotIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldAvatar), v...)) - }) -} - -// AvatarGT applies the GT predicate on the "avatar" field. -func AvatarGT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldAvatar), v)) - }) -} - -// AvatarGTE applies the GTE predicate on the "avatar" field. -func AvatarGTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldAvatar), v)) - }) -} - -// AvatarLT applies the LT predicate on the "avatar" field. -func AvatarLT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldAvatar), v)) - }) -} - -// AvatarLTE applies the LTE predicate on the "avatar" field. -func AvatarLTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldAvatar), v)) - }) -} - -// AvatarContains applies the Contains predicate on the "avatar" field. -func AvatarContains(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldAvatar), v)) - }) -} - -// AvatarHasPrefix applies the HasPrefix predicate on the "avatar" field. -func AvatarHasPrefix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldAvatar), v)) - }) -} - -// AvatarHasSuffix applies the HasSuffix predicate on the "avatar" field. -func AvatarHasSuffix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldAvatar), v)) - }) -} - -// AvatarEqualFold applies the EqualFold predicate on the "avatar" field. -func AvatarEqualFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldAvatar), v)) - }) -} - -// AvatarContainsFold applies the ContainsFold predicate on the "avatar" field. -func AvatarContainsFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldAvatar), v)) - }) -} - -// EmailEQ applies the EQ predicate on the "email" field. -func EmailEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldEmail), v)) - }) -} - -// EmailNEQ applies the NEQ predicate on the "email" field. -func EmailNEQ(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldEmail), v)) - }) -} - -// EmailIn applies the In predicate on the "email" field. -func EmailIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldEmail), v...)) - }) -} - -// EmailNotIn applies the NotIn predicate on the "email" field. -func EmailNotIn(vs ...string) predicate.LinUser { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUser(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldEmail), v...)) - }) -} - -// EmailGT applies the GT predicate on the "email" field. -func EmailGT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldEmail), v)) - }) -} - -// EmailGTE applies the GTE predicate on the "email" field. -func EmailGTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldEmail), v)) - }) -} - -// EmailLT applies the LT predicate on the "email" field. -func EmailLT(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldEmail), v)) - }) -} - -// EmailLTE applies the LTE predicate on the "email" field. -func EmailLTE(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldEmail), v)) - }) -} - -// EmailContains applies the Contains predicate on the "email" field. -func EmailContains(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldEmail), v)) - }) -} - -// EmailHasPrefix applies the HasPrefix predicate on the "email" field. -func EmailHasPrefix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldEmail), v)) - }) -} - -// EmailHasSuffix applies the HasSuffix predicate on the "email" field. -func EmailHasSuffix(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldEmail), v)) - }) -} - -// EmailEqualFold applies the EqualFold predicate on the "email" field. -func EmailEqualFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldEmail), v)) - }) -} - -// EmailContainsFold applies the ContainsFold predicate on the "email" field. -func EmailContainsFold(v string) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldEmail), v)) - }) -} - -// HasLinUserIdentiy applies the HasEdge predicate on the "lin_user_identiy" edge. -func HasLinUserIdentiy() predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinUserIdentiyTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, LinUserIdentiyTable, LinUserIdentiyColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasLinUserIdentiyWith applies the HasEdge predicate on the "lin_user_identiy" edge with a given conditions (other predicates). -func HasLinUserIdentiyWith(preds ...predicate.LinUserIdentiy) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinUserIdentiyInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, LinUserIdentiyTable, LinUserIdentiyColumn), - ) - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasLinGroup applies the HasEdge predicate on the "lin_group" edge. -func HasLinGroup() predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinGroupTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, LinGroupTable, LinGroupPrimaryKey...), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasLinGroupWith applies the HasEdge predicate on the "lin_group" edge with a given conditions (other predicates). -func HasLinGroupWith(preds ...predicate.LinGroup) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(LinGroupInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, LinGroupTable, LinGroupPrimaryKey...), - ) - 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.LinUser) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinUser) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinUser) predicate.LinUser { - return predicate.LinUser(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/linuser_create.go b/internal/data/model/linuser_create.go deleted file mode 100644 index 60825f5..0000000 --- a/internal/data/model/linuser_create.go +++ /dev/null @@ -1,447 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/linuseridentiy" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserCreate is the builder for creating a LinUser entity. -type LinUserCreate struct { - config - mutation *LinUserMutation - hooks []Hook -} - -// SetCreateTime sets the "create_time" field. -func (luc *LinUserCreate) SetCreateTime(t time.Time) *LinUserCreate { - luc.mutation.SetCreateTime(t) - return luc -} - -// SetNillableCreateTime sets the "create_time" field if the given value is not nil. -func (luc *LinUserCreate) SetNillableCreateTime(t *time.Time) *LinUserCreate { - if t != nil { - luc.SetCreateTime(*t) - } - return luc -} - -// SetUpdateTime sets the "update_time" field. -func (luc *LinUserCreate) SetUpdateTime(t time.Time) *LinUserCreate { - luc.mutation.SetUpdateTime(t) - return luc -} - -// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. -func (luc *LinUserCreate) SetNillableUpdateTime(t *time.Time) *LinUserCreate { - if t != nil { - luc.SetUpdateTime(*t) - } - return luc -} - -// SetDeleteTime sets the "delete_time" field. -func (luc *LinUserCreate) SetDeleteTime(t time.Time) *LinUserCreate { - luc.mutation.SetDeleteTime(t) - return luc -} - -// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. -func (luc *LinUserCreate) SetNillableDeleteTime(t *time.Time) *LinUserCreate { - if t != nil { - luc.SetDeleteTime(*t) - } - return luc -} - -// SetUsername sets the "username" field. -func (luc *LinUserCreate) SetUsername(s string) *LinUserCreate { - luc.mutation.SetUsername(s) - return luc -} - -// SetNickname sets the "nickname" field. -func (luc *LinUserCreate) SetNickname(s string) *LinUserCreate { - luc.mutation.SetNickname(s) - return luc -} - -// SetAvatar sets the "avatar" field. -func (luc *LinUserCreate) SetAvatar(s string) *LinUserCreate { - luc.mutation.SetAvatar(s) - return luc -} - -// SetNillableAvatar sets the "avatar" field if the given value is not nil. -func (luc *LinUserCreate) SetNillableAvatar(s *string) *LinUserCreate { - if s != nil { - luc.SetAvatar(*s) - } - return luc -} - -// SetEmail sets the "email" field. -func (luc *LinUserCreate) SetEmail(s string) *LinUserCreate { - luc.mutation.SetEmail(s) - return luc -} - -// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. -func (luc *LinUserCreate) AddLinUserIdentiyIDs(ids ...int) *LinUserCreate { - luc.mutation.AddLinUserIdentiyIDs(ids...) - return luc -} - -// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. -func (luc *LinUserCreate) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserCreate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luc.AddLinUserIdentiyIDs(ids...) -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. -func (luc *LinUserCreate) AddLinGroupIDs(ids ...int) *LinUserCreate { - luc.mutation.AddLinGroupIDs(ids...) - return luc -} - -// AddLinGroup adds the "lin_group" edges to the LinGroup entity. -func (luc *LinUserCreate) AddLinGroup(l ...*LinGroup) *LinUserCreate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luc.AddLinGroupIDs(ids...) -} - -// Mutation returns the LinUserMutation object of the builder. -func (luc *LinUserCreate) Mutation() *LinUserMutation { - return luc.mutation -} - -// Save creates the LinUser in the database. -func (luc *LinUserCreate) Save(ctx context.Context) (*LinUser, error) { - var ( - err error - node *LinUser - ) - luc.defaults() - if len(luc.hooks) == 0 { - if err = luc.check(); err != nil { - return nil, err - } - node, err = luc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = luc.check(); err != nil { - return nil, err - } - luc.mutation = mutation - if node, err = luc.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(luc.hooks) - 1; i >= 0; i-- { - if luc.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luc.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (luc *LinUserCreate) SaveX(ctx context.Context) *LinUser { - v, err := luc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (luc *LinUserCreate) Exec(ctx context.Context) error { - _, err := luc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luc *LinUserCreate) ExecX(ctx context.Context) { - if err := luc.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (luc *LinUserCreate) defaults() { - if _, ok := luc.mutation.CreateTime(); !ok { - v := linuser.DefaultCreateTime() - luc.mutation.SetCreateTime(v) - } - if _, ok := luc.mutation.UpdateTime(); !ok { - v := linuser.DefaultUpdateTime() - luc.mutation.SetUpdateTime(v) - } - if _, ok := luc.mutation.DeleteTime(); !ok { - v := linuser.DefaultDeleteTime() - luc.mutation.SetDeleteTime(v) - } - if _, ok := luc.mutation.Avatar(); !ok { - v := linuser.DefaultAvatar - luc.mutation.SetAvatar(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (luc *LinUserCreate) check() error { - if _, ok := luc.mutation.CreateTime(); !ok { - return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} - } - if _, ok := luc.mutation.UpdateTime(); !ok { - return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} - } - if _, ok := luc.mutation.DeleteTime(); !ok { - return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} - } - if _, ok := luc.mutation.Username(); !ok { - return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} - } - if _, ok := luc.mutation.Nickname(); !ok { - return &ValidationError{Name: "nickname", err: errors.New(`model: missing required field "nickname"`)} - } - if _, ok := luc.mutation.Avatar(); !ok { - return &ValidationError{Name: "avatar", err: errors.New(`model: missing required field "avatar"`)} - } - if _, ok := luc.mutation.Email(); !ok { - return &ValidationError{Name: "email", err: errors.New(`model: missing required field "email"`)} - } - return nil -} - -func (luc *LinUserCreate) sqlSave(ctx context.Context) (*LinUser, error) { - _node, _spec := luc.createSpec() - if err := sqlgraph.CreateNode(ctx, luc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (luc *LinUserCreate) createSpec() (*LinUser, *sqlgraph.CreateSpec) { - var ( - _node = &LinUser{config: luc.config} - _spec = &sqlgraph.CreateSpec{ - Table: linuser.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - } - ) - if value, ok := luc.mutation.CreateTime(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldCreateTime, - }) - _node.CreateTime = value - } - if value, ok := luc.mutation.UpdateTime(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldUpdateTime, - }) - _node.UpdateTime = value - } - if value, ok := luc.mutation.DeleteTime(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldDeleteTime, - }) - _node.DeleteTime = value - } - if value, ok := luc.mutation.Username(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldUsername, - }) - _node.Username = value - } - if value, ok := luc.mutation.Nickname(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldNickname, - }) - _node.Nickname = value - } - if value, ok := luc.mutation.Avatar(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldAvatar, - }) - _node.Avatar = value - } - if value, ok := luc.mutation.Email(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldEmail, - }) - _node.Email = value - } - if nodes := luc.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := luc.mutation.LinGroupIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// LinUserCreateBulk is the builder for creating many LinUser entities in bulk. -type LinUserCreateBulk struct { - config - builders []*LinUserCreate -} - -// Save creates the LinUser entities in the database. -func (lucb *LinUserCreateBulk) Save(ctx context.Context) ([]*LinUser, error) { - specs := make([]*sqlgraph.CreateSpec, len(lucb.builders)) - nodes := make([]*LinUser, len(lucb.builders)) - mutators := make([]Mutator, len(lucb.builders)) - for i := range lucb.builders { - func(i int, root context.Context) { - builder := lucb.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, lucb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, lucb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, lucb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (lucb *LinUserCreateBulk) SaveX(ctx context.Context) []*LinUser { - v, err := lucb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (lucb *LinUserCreateBulk) Exec(ctx context.Context) error { - _, err := lucb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lucb *LinUserCreateBulk) ExecX(ctx context.Context) { - if err := lucb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/linuser_delete.go b/internal/data/model/linuser_delete.go deleted file mode 100644 index 13c22cd..0000000 --- a/internal/data/model/linuser_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserDelete is the builder for deleting a LinUser entity. -type LinUserDelete struct { - config - hooks []Hook - mutation *LinUserMutation -} - -// Where appends a list predicates to the LinUserDelete builder. -func (lud *LinUserDelete) Where(ps ...predicate.LinUser) *LinUserDelete { - lud.mutation.Where(ps...) - return lud -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (lud *LinUserDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(lud.hooks) == 0 { - affected, err = lud.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - lud.mutation = mutation - affected, err = lud.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(lud.hooks) - 1; i >= 0; i-- { - if lud.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = lud.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, lud.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (lud *LinUserDelete) ExecX(ctx context.Context) int { - n, err := lud.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (lud *LinUserDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuser.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - if ps := lud.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, lud.driver, _spec) -} - -// LinUserDeleteOne is the builder for deleting a single LinUser entity. -type LinUserDeleteOne struct { - lud *LinUserDelete -} - -// Exec executes the deletion query. -func (ludo *LinUserDeleteOne) Exec(ctx context.Context) error { - n, err := ludo.lud.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{linuser.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (ludo *LinUserDeleteOne) ExecX(ctx context.Context) { - ludo.lud.ExecX(ctx) -} diff --git a/internal/data/model/linuser_query.go b/internal/data/model/linuser_query.go deleted file mode 100644 index fb1ddf2..0000000 --- a/internal/data/model/linuser_query.go +++ /dev/null @@ -1,1134 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "database/sql/driver" - "errors" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/linuseridentiy" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserQuery is the builder for querying LinUser entities. -type LinUserQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinUser - // eager-loading edges. - withLinUserIdentiy *LinUserIdentiyQuery - withLinGroup *LinGroupQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinUserQuery builder. -func (luq *LinUserQuery) Where(ps ...predicate.LinUser) *LinUserQuery { - luq.predicates = append(luq.predicates, ps...) - return luq -} - -// Limit adds a limit step to the query. -func (luq *LinUserQuery) Limit(limit int) *LinUserQuery { - luq.limit = &limit - return luq -} - -// Offset adds an offset step to the query. -func (luq *LinUserQuery) Offset(offset int) *LinUserQuery { - luq.offset = &offset - return luq -} - -// 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 (luq *LinUserQuery) Unique(unique bool) *LinUserQuery { - luq.unique = &unique - return luq -} - -// Order adds an order step to the query. -func (luq *LinUserQuery) Order(o ...OrderFunc) *LinUserQuery { - luq.order = append(luq.order, o...) - return luq -} - -// QueryLinUserIdentiy chains the current query on the "lin_user_identiy" edge. -func (luq *LinUserQuery) QueryLinUserIdentiy() *LinUserIdentiyQuery { - query := &LinUserIdentiyQuery{config: luq.config} - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := luq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := luq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(linuser.Table, linuser.FieldID, selector), - sqlgraph.To(linuseridentiy.Table, linuseridentiy.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, linuser.LinUserIdentiyTable, linuser.LinUserIdentiyColumn), - ) - fromU = sqlgraph.SetNeighbors(luq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryLinGroup chains the current query on the "lin_group" edge. -func (luq *LinUserQuery) QueryLinGroup() *LinGroupQuery { - query := &LinGroupQuery{config: luq.config} - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := luq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := luq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(linuser.Table, linuser.FieldID, selector), - sqlgraph.To(lingroup.Table, lingroup.FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, linuser.LinGroupTable, linuser.LinGroupPrimaryKey...), - ) - fromU = sqlgraph.SetNeighbors(luq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first LinUser entity from the query. -// Returns a *NotFoundError when no LinUser was found. -func (luq *LinUserQuery) First(ctx context.Context) (*LinUser, error) { - nodes, err := luq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linuser.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (luq *LinUserQuery) FirstX(ctx context.Context) *LinUser { - node, err := luq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinUser ID from the query. -// Returns a *NotFoundError when no LinUser ID was found. -func (luq *LinUserQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = luq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linuser.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (luq *LinUserQuery) FirstIDX(ctx context.Context) int { - id, err := luq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinUser entity from the query. -// Returns a *NotFoundError when no LinUser was found. -func (luq *LinUserQuery) Last(ctx context.Context) (*LinUser, error) { - nodes, err := luq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linuser.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (luq *LinUserQuery) LastX(ctx context.Context) *LinUser { - node, err := luq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinUser ID from the query. -// Returns a *NotFoundError when no LinUser ID was found. -func (luq *LinUserQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = luq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linuser.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (luq *LinUserQuery) LastIDX(ctx context.Context) int { - id, err := luq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinUser entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinUser entity is not found. -// Returns a *NotFoundError when no LinUser entities are found. -func (luq *LinUserQuery) Only(ctx context.Context) (*LinUser, error) { - nodes, err := luq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{linuser.Label} - default: - return nil, &NotSingularError{linuser.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (luq *LinUserQuery) OnlyX(ctx context.Context) *LinUser { - node, err := luq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinUser ID in the query. -// Returns a *NotSingularError when exactly one LinUser ID is not found. -// Returns a *NotFoundError when no entities are found. -func (luq *LinUserQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = luq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{linuser.Label} - default: - err = &NotSingularError{linuser.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (luq *LinUserQuery) OnlyIDX(ctx context.Context) int { - id, err := luq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinUsers. -func (luq *LinUserQuery) All(ctx context.Context) ([]*LinUser, error) { - if err := luq.prepareQuery(ctx); err != nil { - return nil, err - } - return luq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (luq *LinUserQuery) AllX(ctx context.Context) []*LinUser { - nodes, err := luq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinUser IDs. -func (luq *LinUserQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := luq.Select(linuser.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (luq *LinUserQuery) IDsX(ctx context.Context) []int { - ids, err := luq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (luq *LinUserQuery) Count(ctx context.Context) (int, error) { - if err := luq.prepareQuery(ctx); err != nil { - return 0, err - } - return luq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (luq *LinUserQuery) CountX(ctx context.Context) int { - count, err := luq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (luq *LinUserQuery) Exist(ctx context.Context) (bool, error) { - if err := luq.prepareQuery(ctx); err != nil { - return false, err - } - return luq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (luq *LinUserQuery) ExistX(ctx context.Context) bool { - exist, err := luq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinUserQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (luq *LinUserQuery) Clone() *LinUserQuery { - if luq == nil { - return nil - } - return &LinUserQuery{ - config: luq.config, - limit: luq.limit, - offset: luq.offset, - order: append([]OrderFunc{}, luq.order...), - predicates: append([]predicate.LinUser{}, luq.predicates...), - withLinUserIdentiy: luq.withLinUserIdentiy.Clone(), - withLinGroup: luq.withLinGroup.Clone(), - // clone intermediate query. - sql: luq.sql.Clone(), - path: luq.path, - } -} - -// WithLinUserIdentiy tells the query-builder to eager-load the nodes that are connected to -// the "lin_user_identiy" edge. The optional arguments are used to configure the query builder of the edge. -func (luq *LinUserQuery) WithLinUserIdentiy(opts ...func(*LinUserIdentiyQuery)) *LinUserQuery { - query := &LinUserIdentiyQuery{config: luq.config} - for _, opt := range opts { - opt(query) - } - luq.withLinUserIdentiy = query - return luq -} - -// WithLinGroup tells the query-builder to eager-load the nodes that are connected to -// the "lin_group" edge. The optional arguments are used to configure the query builder of the edge. -func (luq *LinUserQuery) WithLinGroup(opts ...func(*LinGroupQuery)) *LinUserQuery { - query := &LinGroupQuery{config: luq.config} - for _, opt := range opts { - opt(query) - } - luq.withLinGroup = query - return luq -} - -// 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 { -// CreateTime time.Time `json:"create_time,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinUser.Query(). -// GroupBy(linuser.FieldCreateTime). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (luq *LinUserQuery) GroupBy(field string, fields ...string) *LinUserGroupBy { - group := &LinUserGroupBy{config: luq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := luq.prepareQuery(ctx); err != nil { - return nil, err - } - return luq.sqlQuery(ctx), nil - } - return group -} - -// 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 { -// CreateTime time.Time `json:"create_time,omitempty"` -// } -// -// client.LinUser.Query(). -// Select(linuser.FieldCreateTime). -// Scan(ctx, &v) -// -func (luq *LinUserQuery) Select(fields ...string) *LinUserSelect { - luq.fields = append(luq.fields, fields...) - return &LinUserSelect{LinUserQuery: luq} -} - -func (luq *LinUserQuery) prepareQuery(ctx context.Context) error { - for _, f := range luq.fields { - if !linuser.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if luq.path != nil { - prev, err := luq.path(ctx) - if err != nil { - return err - } - luq.sql = prev - } - return nil -} - -func (luq *LinUserQuery) sqlAll(ctx context.Context) ([]*LinUser, error) { - var ( - nodes = []*LinUser{} - _spec = luq.querySpec() - loadedTypes = [2]bool{ - luq.withLinUserIdentiy != nil, - luq.withLinGroup != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinUser{config: luq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, luq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - - if query := luq.withLinUserIdentiy; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*LinUser) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - nodes[i].Edges.LinUserIdentiy = []*LinUserIdentiy{} - } - query.withFKs = true - query.Where(predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.InValues(linuser.LinUserIdentiyColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err - } - for _, n := range neighbors { - fk := n.lin_user_lin_user_identiy - if fk == nil { - return nil, fmt.Errorf(`foreign-key "lin_user_lin_user_identiy" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "lin_user_lin_user_identiy" returned %v for node %v`, *fk, n.ID) - } - node.Edges.LinUserIdentiy = append(node.Edges.LinUserIdentiy, n) - } - } - - if query := luq.withLinGroup; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - ids := make(map[int]*LinUser, len(nodes)) - for _, node := range nodes { - ids[node.ID] = node - fks = append(fks, node.ID) - node.Edges.LinGroup = []*LinGroup{} - } - var ( - edgeids []int - edges = make(map[int][]*LinUser) - ) - _spec := &sqlgraph.EdgeQuerySpec{ - Edge: &sqlgraph.EdgeSpec{ - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - }, - Predicate: func(s *sql.Selector) { - s.Where(sql.InValues(linuser.LinGroupPrimaryKey[1], fks...)) - }, - ScanValues: func() [2]interface{} { - return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} - }, - Assign: func(out, in interface{}) error { - eout, ok := out.(*sql.NullInt64) - if !ok || eout == nil { - return fmt.Errorf("unexpected id value for edge-out") - } - ein, ok := in.(*sql.NullInt64) - if !ok || ein == nil { - return fmt.Errorf("unexpected id value for edge-in") - } - outValue := int(eout.Int64) - inValue := int(ein.Int64) - node, ok := ids[outValue] - if !ok { - return fmt.Errorf("unexpected node id in edges: %v", outValue) - } - if _, ok := edges[inValue]; !ok { - edgeids = append(edgeids, inValue) - } - edges[inValue] = append(edges[inValue], node) - return nil - }, - } - if err := sqlgraph.QueryEdges(ctx, luq.driver, _spec); err != nil { - return nil, fmt.Errorf(`query edges "lin_group": %w`, err) - } - query.Where(lingroup.IDIn(edgeids...)) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err - } - for _, n := range neighbors { - nodes, ok := edges[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected "lin_group" node returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.LinGroup = append(nodes[i].Edges.LinGroup, n) - } - } - } - - return nodes, nil -} - -func (luq *LinUserQuery) sqlCount(ctx context.Context) (int, error) { - _spec := luq.querySpec() - return sqlgraph.CountNodes(ctx, luq.driver, _spec) -} - -func (luq *LinUserQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := luq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (luq *LinUserQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuser.Table, - Columns: linuser.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - From: luq.sql, - Unique: true, - } - if unique := luq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := luq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linuser.FieldID) - for i := range fields { - if fields[i] != linuser.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := luq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := luq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := luq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := luq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (luq *LinUserQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(luq.driver.Dialect()) - t1 := builder.Table(linuser.Table) - columns := luq.fields - if len(columns) == 0 { - columns = linuser.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if luq.sql != nil { - selector = luq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range luq.predicates { - p(selector) - } - for _, p := range luq.order { - p(selector) - } - if offset := luq.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 := luq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinUserGroupBy is the group-by builder for LinUser entities. -type LinUserGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (lugb *LinUserGroupBy) Aggregate(fns ...AggregateFunc) *LinUserGroupBy { - lugb.fns = append(lugb.fns, fns...) - return lugb -} - -// Scan applies the group-by query and scans the result into the given value. -func (lugb *LinUserGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := lugb.path(ctx) - if err != nil { - return err - } - lugb.sql = query - return lugb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lugb *LinUserGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := lugb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(lugb.fields) > 1 { - return nil, errors.New("model: LinUserGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := lugb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lugb *LinUserGroupBy) StringsX(ctx context.Context) []string { - v, err := lugb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lugb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lugb *LinUserGroupBy) StringX(ctx context.Context) string { - v, err := lugb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(lugb.fields) > 1 { - return nil, errors.New("model: LinUserGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := lugb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lugb *LinUserGroupBy) IntsX(ctx context.Context) []int { - v, err := lugb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lugb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lugb *LinUserGroupBy) IntX(ctx context.Context) int { - v, err := lugb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(lugb.fields) > 1 { - return nil, errors.New("model: LinUserGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := lugb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lugb *LinUserGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := lugb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lugb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lugb *LinUserGroupBy) Float64X(ctx context.Context) float64 { - v, err := lugb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(lugb.fields) > 1 { - return nil, errors.New("model: LinUserGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := lugb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lugb *LinUserGroupBy) BoolsX(ctx context.Context) []bool { - v, err := lugb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (lugb *LinUserGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lugb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lugb *LinUserGroupBy) BoolX(ctx context.Context) bool { - v, err := lugb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lugb *LinUserGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range lugb.fields { - if !linuser.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := lugb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := lugb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (lugb *LinUserGroupBy) sqlQuery() *sql.Selector { - selector := lugb.sql.Select() - aggregation := make([]string, 0, len(lugb.fns)) - for _, fn := range lugb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(lugb.fields)+len(lugb.fns)) - for _, f := range lugb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(lugb.fields...)...) -} - -// LinUserSelect is the builder for selecting fields of LinUser entities. -type LinUserSelect struct { - *LinUserQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (lus *LinUserSelect) Scan(ctx context.Context, v interface{}) error { - if err := lus.prepareQuery(ctx); err != nil { - return err - } - lus.sql = lus.LinUserQuery.sqlQuery(ctx) - return lus.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (lus *LinUserSelect) ScanX(ctx context.Context, v interface{}) { - if err := lus.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Strings(ctx context.Context) ([]string, error) { - if len(lus.fields) > 1 { - return nil, errors.New("model: LinUserSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := lus.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (lus *LinUserSelect) StringsX(ctx context.Context) []string { - v, err := lus.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = lus.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (lus *LinUserSelect) StringX(ctx context.Context) string { - v, err := lus.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Ints(ctx context.Context) ([]int, error) { - if len(lus.fields) > 1 { - return nil, errors.New("model: LinUserSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := lus.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (lus *LinUserSelect) IntsX(ctx context.Context) []int { - v, err := lus.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = lus.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (lus *LinUserSelect) IntX(ctx context.Context) int { - v, err := lus.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(lus.fields) > 1 { - return nil, errors.New("model: LinUserSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := lus.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (lus *LinUserSelect) Float64sX(ctx context.Context) []float64 { - v, err := lus.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = lus.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (lus *LinUserSelect) Float64X(ctx context.Context) float64 { - v, err := lus.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Bools(ctx context.Context) ([]bool, error) { - if len(lus.fields) > 1 { - return nil, errors.New("model: LinUserSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := lus.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (lus *LinUserSelect) BoolsX(ctx context.Context) []bool { - v, err := lus.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (lus *LinUserSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = lus.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuser.Label} - default: - err = fmt.Errorf("model: LinUserSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (lus *LinUserSelect) BoolX(ctx context.Context) bool { - v, err := lus.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (lus *LinUserSelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := lus.sql.Query() - if err := lus.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/linuser_update.go b/internal/data/model/linuser_update.go deleted file mode 100644 index be3c6fb..0000000 --- a/internal/data/model/linuser_update.go +++ /dev/null @@ -1,807 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/linuseridentiy" - "lin-cms-go/internal/data/model/predicate" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserUpdate is the builder for updating LinUser entities. -type LinUserUpdate struct { - config - hooks []Hook - mutation *LinUserMutation -} - -// Where appends a list predicates to the LinUserUpdate builder. -func (luu *LinUserUpdate) Where(ps ...predicate.LinUser) *LinUserUpdate { - luu.mutation.Where(ps...) - return luu -} - -// SetUpdateTime sets the "update_time" field. -func (luu *LinUserUpdate) SetUpdateTime(t time.Time) *LinUserUpdate { - luu.mutation.SetUpdateTime(t) - return luu -} - -// SetDeleteTime sets the "delete_time" field. -func (luu *LinUserUpdate) SetDeleteTime(t time.Time) *LinUserUpdate { - luu.mutation.SetDeleteTime(t) - return luu -} - -// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. -func (luu *LinUserUpdate) SetNillableDeleteTime(t *time.Time) *LinUserUpdate { - if t != nil { - luu.SetDeleteTime(*t) - } - return luu -} - -// SetUsername sets the "username" field. -func (luu *LinUserUpdate) SetUsername(s string) *LinUserUpdate { - luu.mutation.SetUsername(s) - return luu -} - -// SetNickname sets the "nickname" field. -func (luu *LinUserUpdate) SetNickname(s string) *LinUserUpdate { - luu.mutation.SetNickname(s) - return luu -} - -// SetAvatar sets the "avatar" field. -func (luu *LinUserUpdate) SetAvatar(s string) *LinUserUpdate { - luu.mutation.SetAvatar(s) - return luu -} - -// SetNillableAvatar sets the "avatar" field if the given value is not nil. -func (luu *LinUserUpdate) SetNillableAvatar(s *string) *LinUserUpdate { - if s != nil { - luu.SetAvatar(*s) - } - return luu -} - -// SetEmail sets the "email" field. -func (luu *LinUserUpdate) SetEmail(s string) *LinUserUpdate { - luu.mutation.SetEmail(s) - return luu -} - -// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. -func (luu *LinUserUpdate) AddLinUserIdentiyIDs(ids ...int) *LinUserUpdate { - luu.mutation.AddLinUserIdentiyIDs(ids...) - return luu -} - -// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. -func (luu *LinUserUpdate) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luu.AddLinUserIdentiyIDs(ids...) -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. -func (luu *LinUserUpdate) AddLinGroupIDs(ids ...int) *LinUserUpdate { - luu.mutation.AddLinGroupIDs(ids...) - return luu -} - -// AddLinGroup adds the "lin_group" edges to the LinGroup entity. -func (luu *LinUserUpdate) AddLinGroup(l ...*LinGroup) *LinUserUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luu.AddLinGroupIDs(ids...) -} - -// Mutation returns the LinUserMutation object of the builder. -func (luu *LinUserUpdate) Mutation() *LinUserMutation { - return luu.mutation -} - -// ClearLinUserIdentiy clears all "lin_user_identiy" edges to the LinUserIdentiy entity. -func (luu *LinUserUpdate) ClearLinUserIdentiy() *LinUserUpdate { - luu.mutation.ClearLinUserIdentiy() - return luu -} - -// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to LinUserIdentiy entities by IDs. -func (luu *LinUserUpdate) RemoveLinUserIdentiyIDs(ids ...int) *LinUserUpdate { - luu.mutation.RemoveLinUserIdentiyIDs(ids...) - return luu -} - -// RemoveLinUserIdentiy removes "lin_user_identiy" edges to LinUserIdentiy entities. -func (luu *LinUserUpdate) RemoveLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luu.RemoveLinUserIdentiyIDs(ids...) -} - -// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. -func (luu *LinUserUpdate) ClearLinGroup() *LinUserUpdate { - luu.mutation.ClearLinGroup() - return luu -} - -// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. -func (luu *LinUserUpdate) RemoveLinGroupIDs(ids ...int) *LinUserUpdate { - luu.mutation.RemoveLinGroupIDs(ids...) - return luu -} - -// RemoveLinGroup removes "lin_group" edges to LinGroup entities. -func (luu *LinUserUpdate) RemoveLinGroup(l ...*LinGroup) *LinUserUpdate { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luu.RemoveLinGroupIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (luu *LinUserUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - luu.defaults() - if len(luu.hooks) == 0 { - affected, err = luu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - luu.mutation = mutation - affected, err = luu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(luu.hooks) - 1; i >= 0; i-- { - if luu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (luu *LinUserUpdate) SaveX(ctx context.Context) int { - affected, err := luu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (luu *LinUserUpdate) Exec(ctx context.Context) error { - _, err := luu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luu *LinUserUpdate) ExecX(ctx context.Context) { - if err := luu.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (luu *LinUserUpdate) defaults() { - if _, ok := luu.mutation.UpdateTime(); !ok { - v := linuser.UpdateDefaultUpdateTime() - luu.mutation.SetUpdateTime(v) - } -} - -func (luu *LinUserUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuser.Table, - Columns: linuser.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - if ps := luu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := luu.mutation.UpdateTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldUpdateTime, - }) - } - if value, ok := luu.mutation.DeleteTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldDeleteTime, - }) - } - if value, ok := luu.mutation.Username(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldUsername, - }) - } - if value, ok := luu.mutation.Nickname(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldNickname, - }) - } - if value, ok := luu.mutation.Avatar(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldAvatar, - }) - } - if value, ok := luu.mutation.Email(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldEmail, - }) - } - if luu.mutation.LinUserIdentiyCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luu.mutation.RemovedLinUserIdentiyIDs(); len(nodes) > 0 && !luu.mutation.LinUserIdentiyCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luu.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if luu.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luu.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !luu.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luu.mutation.LinGroupIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if n, err = sqlgraph.UpdateNodes(ctx, luu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linuser.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinUserUpdateOne is the builder for updating a single LinUser entity. -type LinUserUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinUserMutation -} - -// SetUpdateTime sets the "update_time" field. -func (luuo *LinUserUpdateOne) SetUpdateTime(t time.Time) *LinUserUpdateOne { - luuo.mutation.SetUpdateTime(t) - return luuo -} - -// SetDeleteTime sets the "delete_time" field. -func (luuo *LinUserUpdateOne) SetDeleteTime(t time.Time) *LinUserUpdateOne { - luuo.mutation.SetDeleteTime(t) - return luuo -} - -// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. -func (luuo *LinUserUpdateOne) SetNillableDeleteTime(t *time.Time) *LinUserUpdateOne { - if t != nil { - luuo.SetDeleteTime(*t) - } - return luuo -} - -// SetUsername sets the "username" field. -func (luuo *LinUserUpdateOne) SetUsername(s string) *LinUserUpdateOne { - luuo.mutation.SetUsername(s) - return luuo -} - -// SetNickname sets the "nickname" field. -func (luuo *LinUserUpdateOne) SetNickname(s string) *LinUserUpdateOne { - luuo.mutation.SetNickname(s) - return luuo -} - -// SetAvatar sets the "avatar" field. -func (luuo *LinUserUpdateOne) SetAvatar(s string) *LinUserUpdateOne { - luuo.mutation.SetAvatar(s) - return luuo -} - -// SetNillableAvatar sets the "avatar" field if the given value is not nil. -func (luuo *LinUserUpdateOne) SetNillableAvatar(s *string) *LinUserUpdateOne { - if s != nil { - luuo.SetAvatar(*s) - } - return luuo -} - -// SetEmail sets the "email" field. -func (luuo *LinUserUpdateOne) SetEmail(s string) *LinUserUpdateOne { - luuo.mutation.SetEmail(s) - return luuo -} - -// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. -func (luuo *LinUserUpdateOne) AddLinUserIdentiyIDs(ids ...int) *LinUserUpdateOne { - luuo.mutation.AddLinUserIdentiyIDs(ids...) - return luuo -} - -// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. -func (luuo *LinUserUpdateOne) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luuo.AddLinUserIdentiyIDs(ids...) -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. -func (luuo *LinUserUpdateOne) AddLinGroupIDs(ids ...int) *LinUserUpdateOne { - luuo.mutation.AddLinGroupIDs(ids...) - return luuo -} - -// AddLinGroup adds the "lin_group" edges to the LinGroup entity. -func (luuo *LinUserUpdateOne) AddLinGroup(l ...*LinGroup) *LinUserUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luuo.AddLinGroupIDs(ids...) -} - -// Mutation returns the LinUserMutation object of the builder. -func (luuo *LinUserUpdateOne) Mutation() *LinUserMutation { - return luuo.mutation -} - -// ClearLinUserIdentiy clears all "lin_user_identiy" edges to the LinUserIdentiy entity. -func (luuo *LinUserUpdateOne) ClearLinUserIdentiy() *LinUserUpdateOne { - luuo.mutation.ClearLinUserIdentiy() - return luuo -} - -// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to LinUserIdentiy entities by IDs. -func (luuo *LinUserUpdateOne) RemoveLinUserIdentiyIDs(ids ...int) *LinUserUpdateOne { - luuo.mutation.RemoveLinUserIdentiyIDs(ids...) - return luuo -} - -// RemoveLinUserIdentiy removes "lin_user_identiy" edges to LinUserIdentiy entities. -func (luuo *LinUserUpdateOne) RemoveLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luuo.RemoveLinUserIdentiyIDs(ids...) -} - -// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. -func (luuo *LinUserUpdateOne) ClearLinGroup() *LinUserUpdateOne { - luuo.mutation.ClearLinGroup() - return luuo -} - -// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. -func (luuo *LinUserUpdateOne) RemoveLinGroupIDs(ids ...int) *LinUserUpdateOne { - luuo.mutation.RemoveLinGroupIDs(ids...) - return luuo -} - -// RemoveLinGroup removes "lin_group" edges to LinGroup entities. -func (luuo *LinUserUpdateOne) RemoveLinGroup(l ...*LinGroup) *LinUserUpdateOne { - ids := make([]int, len(l)) - for i := range l { - ids[i] = l[i].ID - } - return luuo.RemoveLinGroupIDs(ids...) -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (luuo *LinUserUpdateOne) Select(field string, fields ...string) *LinUserUpdateOne { - luuo.fields = append([]string{field}, fields...) - return luuo -} - -// Save executes the query and returns the updated LinUser entity. -func (luuo *LinUserUpdateOne) Save(ctx context.Context) (*LinUser, error) { - var ( - err error - node *LinUser - ) - luuo.defaults() - if len(luuo.hooks) == 0 { - node, err = luuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - luuo.mutation = mutation - node, err = luuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(luuo.hooks) - 1; i >= 0; i-- { - if luuo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luuo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (luuo *LinUserUpdateOne) SaveX(ctx context.Context) *LinUser { - node, err := luuo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (luuo *LinUserUpdateOne) Exec(ctx context.Context) error { - _, err := luuo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luuo *LinUserUpdateOne) ExecX(ctx context.Context) { - if err := luuo.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (luuo *LinUserUpdateOne) defaults() { - if _, ok := luuo.mutation.UpdateTime(); !ok { - v := linuser.UpdateDefaultUpdateTime() - luuo.mutation.SetUpdateTime(v) - } -} - -func (luuo *LinUserUpdateOne) sqlSave(ctx context.Context) (_node *LinUser, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuser.Table, - Columns: linuser.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuser.FieldID, - }, - }, - } - id, ok := luuo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinUser.ID for update")} - } - _spec.Node.ID.Value = id - if fields := luuo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linuser.FieldID) - for _, f := range fields { - if !linuser.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != linuser.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := luuo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := luuo.mutation.UpdateTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldUpdateTime, - }) - } - if value, ok := luuo.mutation.DeleteTime(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: linuser.FieldDeleteTime, - }) - } - if value, ok := luuo.mutation.Username(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldUsername, - }) - } - if value, ok := luuo.mutation.Nickname(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldNickname, - }) - } - if value, ok := luuo.mutation.Avatar(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldAvatar, - }) - } - if value, ok := luuo.mutation.Email(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuser.FieldEmail, - }) - } - if luuo.mutation.LinUserIdentiyCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luuo.mutation.RemovedLinUserIdentiyIDs(); len(nodes) > 0 && !luuo.mutation.LinUserIdentiyCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luuo.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: linuser.LinUserIdentiyTable, - Columns: []string{linuser.LinUserIdentiyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if luuo.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luuo.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !luuo.mutation.LinGroupCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := luuo.mutation.LinGroupIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: linuser.LinGroupTable, - Columns: linuser.LinGroupPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: lingroup.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &LinUser{config: luuo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, luuo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linuser.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/linuseridentiy.go b/internal/data/model/linuseridentiy.go deleted file mode 100644 index 5834615..0000000 --- a/internal/data/model/linuseridentiy.go +++ /dev/null @@ -1,140 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "fmt" - "lin-cms-go/internal/data/model/linuseridentiy" - "strings" - - "entgo.io/ent/dialect/sql" -) - -// LinUserIdentiy is the model entity for the LinUserIdentiy schema. -type LinUserIdentiy struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // UserID holds the value of the "user_id" field. - // 用户id - UserID int `json:"user_id,omitempty"` - // IdentityType holds the value of the "identity_type" field. - IdentityType string `json:"identity_type,omitempty"` - // Identifier holds the value of the "identifier" field. - Identifier string `json:"identifier,omitempty"` - // Credential holds the value of the "credential" field. - Credential string `json:"credential,omitempty"` - lin_user_lin_user_identiy *int -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*LinUserIdentiy) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) - for i := range columns { - switch columns[i] { - case linuseridentiy.FieldID, linuseridentiy.FieldUserID: - values[i] = new(sql.NullInt64) - case linuseridentiy.FieldIdentityType, linuseridentiy.FieldIdentifier, linuseridentiy.FieldCredential: - values[i] = new(sql.NullString) - case linuseridentiy.ForeignKeys[0]: // lin_user_lin_user_identiy - values[i] = new(sql.NullInt64) - default: - return nil, fmt.Errorf("unexpected column %q for type LinUserIdentiy", columns[i]) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the LinUserIdentiy fields. -func (lui *LinUserIdentiy) assignValues(columns []string, values []interface{}) 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 linuseridentiy.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - lui.ID = int(value.Int64) - case linuseridentiy.FieldUserID: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field user_id", values[i]) - } else if value.Valid { - lui.UserID = int(value.Int64) - } - case linuseridentiy.FieldIdentityType: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field identity_type", values[i]) - } else if value.Valid { - lui.IdentityType = value.String - } - case linuseridentiy.FieldIdentifier: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field identifier", values[i]) - } else if value.Valid { - lui.Identifier = value.String - } - case linuseridentiy.FieldCredential: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field credential", values[i]) - } else if value.Valid { - lui.Credential = value.String - } - case linuseridentiy.ForeignKeys[0]: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field lin_user_lin_user_identiy", value) - } else if value.Valid { - lui.lin_user_lin_user_identiy = new(int) - *lui.lin_user_lin_user_identiy = int(value.Int64) - } - } - } - return nil -} - -// Update returns a builder for updating this LinUserIdentiy. -// Note that you need to call LinUserIdentiy.Unwrap() before calling this method if this LinUserIdentiy -// was returned from a transaction, and the transaction was committed or rolled back. -func (lui *LinUserIdentiy) Update() *LinUserIdentiyUpdateOne { - return (&LinUserIdentiyClient{config: lui.config}).UpdateOne(lui) -} - -// Unwrap unwraps the LinUserIdentiy 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 (lui *LinUserIdentiy) Unwrap() *LinUserIdentiy { - tx, ok := lui.config.driver.(*txDriver) - if !ok { - panic("model: LinUserIdentiy is not a transactional entity") - } - lui.config.driver = tx.drv - return lui -} - -// String implements the fmt.Stringer. -func (lui *LinUserIdentiy) String() string { - var builder strings.Builder - builder.WriteString("LinUserIdentiy(") - builder.WriteString(fmt.Sprintf("id=%v", lui.ID)) - builder.WriteString(", user_id=") - builder.WriteString(fmt.Sprintf("%v", lui.UserID)) - builder.WriteString(", identity_type=") - builder.WriteString(lui.IdentityType) - builder.WriteString(", identifier=") - builder.WriteString(lui.Identifier) - builder.WriteString(", credential=") - builder.WriteString(lui.Credential) - builder.WriteByte(')') - return builder.String() -} - -// LinUserIdentiys is a parsable slice of LinUserIdentiy. -type LinUserIdentiys []*LinUserIdentiy - -func (lui LinUserIdentiys) config(cfg config) { - for _i := range lui { - lui[_i].config = cfg - } -} diff --git a/internal/data/model/linuseridentiy/linuseridentiy.go b/internal/data/model/linuseridentiy/linuseridentiy.go deleted file mode 100644 index 7339818..0000000 --- a/internal/data/model/linuseridentiy/linuseridentiy.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linuseridentiy - -const ( - // Label holds the string label denoting the linuseridentiy type in the database. - Label = "lin_user_identiy" - // 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" - // FieldIdentityType holds the string denoting the identity_type field in the database. - FieldIdentityType = "identity_type" - // FieldIdentifier holds the string denoting the identifier field in the database. - FieldIdentifier = "identifier" - // FieldCredential holds the string denoting the credential field in the database. - FieldCredential = "credential" - // Table holds the table name of the linuseridentiy in the database. - Table = "lin_user_identiy" -) - -// Columns holds all SQL columns for linuseridentiy fields. -var Columns = []string{ - FieldID, - FieldUserID, - FieldIdentityType, - FieldIdentifier, - FieldCredential, -} - -// ForeignKeys holds the SQL foreign-keys that are owned by the "lin_user_identiy" -// table and are not defined as standalone fields in the schema. -var ForeignKeys = []string{ - "lin_user_lin_user_identiy", -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - for i := range ForeignKeys { - if column == ForeignKeys[i] { - return true - } - } - return false -} diff --git a/internal/data/model/linuseridentiy/where.go b/internal/data/model/linuseridentiy/where.go deleted file mode 100644 index 69704f1..0000000 --- a/internal/data/model/linuseridentiy/where.go +++ /dev/null @@ -1,561 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package linuseridentiy - -import ( - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) -} - -// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. -func UserID(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUserID), v)) - }) -} - -// IdentityType applies equality check predicate on the "identity_type" field. It's identical to IdentityTypeEQ. -func IdentityType(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldIdentityType), v)) - }) -} - -// Identifier applies equality check predicate on the "identifier" field. It's identical to IdentifierEQ. -func Identifier(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldIdentifier), v)) - }) -} - -// Credential applies equality check predicate on the "credential" field. It's identical to CredentialEQ. -func Credential(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCredential), v)) - }) -} - -// UserIDEQ applies the EQ predicate on the "user_id" field. -func UserIDEQ(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUserID), v)) - }) -} - -// UserIDNEQ applies the NEQ predicate on the "user_id" field. -func UserIDNEQ(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUserID), v)) - }) -} - -// UserIDIn applies the In predicate on the "user_id" field. -func UserIDIn(vs ...int) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUserID), v...)) - }) -} - -// UserIDNotIn applies the NotIn predicate on the "user_id" field. -func UserIDNotIn(vs ...int) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUserID), v...)) - }) -} - -// UserIDGT applies the GT predicate on the "user_id" field. -func UserIDGT(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUserID), v)) - }) -} - -// UserIDGTE applies the GTE predicate on the "user_id" field. -func UserIDGTE(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUserID), v)) - }) -} - -// UserIDLT applies the LT predicate on the "user_id" field. -func UserIDLT(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUserID), v)) - }) -} - -// UserIDLTE applies the LTE predicate on the "user_id" field. -func UserIDLTE(v int) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUserID), v)) - }) -} - -// IdentityTypeEQ applies the EQ predicate on the "identity_type" field. -func IdentityTypeEQ(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeNEQ applies the NEQ predicate on the "identity_type" field. -func IdentityTypeNEQ(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeIn applies the In predicate on the "identity_type" field. -func IdentityTypeIn(vs ...string) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldIdentityType), v...)) - }) -} - -// IdentityTypeNotIn applies the NotIn predicate on the "identity_type" field. -func IdentityTypeNotIn(vs ...string) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldIdentityType), v...)) - }) -} - -// IdentityTypeGT applies the GT predicate on the "identity_type" field. -func IdentityTypeGT(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeGTE applies the GTE predicate on the "identity_type" field. -func IdentityTypeGTE(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeLT applies the LT predicate on the "identity_type" field. -func IdentityTypeLT(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeLTE applies the LTE predicate on the "identity_type" field. -func IdentityTypeLTE(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeContains applies the Contains predicate on the "identity_type" field. -func IdentityTypeContains(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeHasPrefix applies the HasPrefix predicate on the "identity_type" field. -func IdentityTypeHasPrefix(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeHasSuffix applies the HasSuffix predicate on the "identity_type" field. -func IdentityTypeHasSuffix(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeEqualFold applies the EqualFold predicate on the "identity_type" field. -func IdentityTypeEqualFold(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldIdentityType), v)) - }) -} - -// IdentityTypeContainsFold applies the ContainsFold predicate on the "identity_type" field. -func IdentityTypeContainsFold(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldIdentityType), v)) - }) -} - -// IdentifierEQ applies the EQ predicate on the "identifier" field. -func IdentifierEQ(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierNEQ applies the NEQ predicate on the "identifier" field. -func IdentifierNEQ(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierIn applies the In predicate on the "identifier" field. -func IdentifierIn(vs ...string) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldIdentifier), v...)) - }) -} - -// IdentifierNotIn applies the NotIn predicate on the "identifier" field. -func IdentifierNotIn(vs ...string) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldIdentifier), v...)) - }) -} - -// IdentifierGT applies the GT predicate on the "identifier" field. -func IdentifierGT(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierGTE applies the GTE predicate on the "identifier" field. -func IdentifierGTE(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierLT applies the LT predicate on the "identifier" field. -func IdentifierLT(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierLTE applies the LTE predicate on the "identifier" field. -func IdentifierLTE(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierContains applies the Contains predicate on the "identifier" field. -func IdentifierContains(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierHasPrefix applies the HasPrefix predicate on the "identifier" field. -func IdentifierHasPrefix(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierHasSuffix applies the HasSuffix predicate on the "identifier" field. -func IdentifierHasSuffix(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierEqualFold applies the EqualFold predicate on the "identifier" field. -func IdentifierEqualFold(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldIdentifier), v)) - }) -} - -// IdentifierContainsFold applies the ContainsFold predicate on the "identifier" field. -func IdentifierContainsFold(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldIdentifier), v)) - }) -} - -// CredentialEQ applies the EQ predicate on the "credential" field. -func CredentialEQ(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCredential), v)) - }) -} - -// CredentialNEQ applies the NEQ predicate on the "credential" field. -func CredentialNEQ(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldCredential), v)) - }) -} - -// CredentialIn applies the In predicate on the "credential" field. -func CredentialIn(vs ...string) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldCredential), v...)) - }) -} - -// CredentialNotIn applies the NotIn predicate on the "credential" field. -func CredentialNotIn(vs ...string) predicate.LinUserIdentiy { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.LinUserIdentiy(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldCredential), v...)) - }) -} - -// CredentialGT applies the GT predicate on the "credential" field. -func CredentialGT(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldCredential), v)) - }) -} - -// CredentialGTE applies the GTE predicate on the "credential" field. -func CredentialGTE(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldCredential), v)) - }) -} - -// CredentialLT applies the LT predicate on the "credential" field. -func CredentialLT(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldCredential), v)) - }) -} - -// CredentialLTE applies the LTE predicate on the "credential" field. -func CredentialLTE(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldCredential), v)) - }) -} - -// CredentialContains applies the Contains predicate on the "credential" field. -func CredentialContains(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldCredential), v)) - }) -} - -// CredentialHasPrefix applies the HasPrefix predicate on the "credential" field. -func CredentialHasPrefix(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldCredential), v)) - }) -} - -// CredentialHasSuffix applies the HasSuffix predicate on the "credential" field. -func CredentialHasSuffix(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldCredential), v)) - }) -} - -// CredentialEqualFold applies the EqualFold predicate on the "credential" field. -func CredentialEqualFold(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldCredential), v)) - }) -} - -// CredentialContainsFold applies the ContainsFold predicate on the "credential" field. -func CredentialContainsFold(v string) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldCredential), v)) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.LinUserIdentiy) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.LinUserIdentiy) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.LinUserIdentiy) predicate.LinUserIdentiy { - return predicate.LinUserIdentiy(func(s *sql.Selector) { - p(s.Not()) - }) -} diff --git a/internal/data/model/linuseridentiy_create.go b/internal/data/model/linuseridentiy_create.go deleted file mode 100644 index 5c5c685..0000000 --- a/internal/data/model/linuseridentiy_create.go +++ /dev/null @@ -1,271 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/linuseridentiy" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserIdentiyCreate is the builder for creating a LinUserIdentiy entity. -type LinUserIdentiyCreate struct { - config - mutation *LinUserIdentiyMutation - hooks []Hook -} - -// SetUserID sets the "user_id" field. -func (luic *LinUserIdentiyCreate) SetUserID(i int) *LinUserIdentiyCreate { - luic.mutation.SetUserID(i) - return luic -} - -// SetIdentityType sets the "identity_type" field. -func (luic *LinUserIdentiyCreate) SetIdentityType(s string) *LinUserIdentiyCreate { - luic.mutation.SetIdentityType(s) - return luic -} - -// SetIdentifier sets the "identifier" field. -func (luic *LinUserIdentiyCreate) SetIdentifier(s string) *LinUserIdentiyCreate { - luic.mutation.SetIdentifier(s) - return luic -} - -// SetCredential sets the "credential" field. -func (luic *LinUserIdentiyCreate) SetCredential(s string) *LinUserIdentiyCreate { - luic.mutation.SetCredential(s) - return luic -} - -// Mutation returns the LinUserIdentiyMutation object of the builder. -func (luic *LinUserIdentiyCreate) Mutation() *LinUserIdentiyMutation { - return luic.mutation -} - -// Save creates the LinUserIdentiy in the database. -func (luic *LinUserIdentiyCreate) Save(ctx context.Context) (*LinUserIdentiy, error) { - var ( - err error - node *LinUserIdentiy - ) - if len(luic.hooks) == 0 { - if err = luic.check(); err != nil { - return nil, err - } - node, err = luic.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserIdentiyMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = luic.check(); err != nil { - return nil, err - } - luic.mutation = mutation - if node, err = luic.sqlSave(ctx); err != nil { - return nil, err - } - mutation.id = &node.ID - mutation.done = true - return node, err - }) - for i := len(luic.hooks) - 1; i >= 0; i-- { - if luic.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luic.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luic.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX calls Save and panics if Save returns an error. -func (luic *LinUserIdentiyCreate) SaveX(ctx context.Context) *LinUserIdentiy { - v, err := luic.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (luic *LinUserIdentiyCreate) Exec(ctx context.Context) error { - _, err := luic.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luic *LinUserIdentiyCreate) ExecX(ctx context.Context) { - if err := luic.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (luic *LinUserIdentiyCreate) check() error { - if _, ok := luic.mutation.UserID(); !ok { - return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} - } - if _, ok := luic.mutation.IdentityType(); !ok { - return &ValidationError{Name: "identity_type", err: errors.New(`model: missing required field "identity_type"`)} - } - if _, ok := luic.mutation.Identifier(); !ok { - return &ValidationError{Name: "identifier", err: errors.New(`model: missing required field "identifier"`)} - } - if _, ok := luic.mutation.Credential(); !ok { - return &ValidationError{Name: "credential", err: errors.New(`model: missing required field "credential"`)} - } - return nil -} - -func (luic *LinUserIdentiyCreate) sqlSave(ctx context.Context) (*LinUserIdentiy, error) { - _node, _spec := luic.createSpec() - if err := sqlgraph.CreateNode(ctx, luic.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - return _node, nil -} - -func (luic *LinUserIdentiyCreate) createSpec() (*LinUserIdentiy, *sqlgraph.CreateSpec) { - var ( - _node = &LinUserIdentiy{config: luic.config} - _spec = &sqlgraph.CreateSpec{ - Table: linuseridentiy.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - } - ) - if value, ok := luic.mutation.UserID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linuseridentiy.FieldUserID, - }) - _node.UserID = value - } - if value, ok := luic.mutation.IdentityType(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldIdentityType, - }) - _node.IdentityType = value - } - if value, ok := luic.mutation.Identifier(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldIdentifier, - }) - _node.Identifier = value - } - if value, ok := luic.mutation.Credential(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldCredential, - }) - _node.Credential = value - } - return _node, _spec -} - -// LinUserIdentiyCreateBulk is the builder for creating many LinUserIdentiy entities in bulk. -type LinUserIdentiyCreateBulk struct { - config - builders []*LinUserIdentiyCreate -} - -// Save creates the LinUserIdentiy entities in the database. -func (luicb *LinUserIdentiyCreateBulk) Save(ctx context.Context) ([]*LinUserIdentiy, error) { - specs := make([]*sqlgraph.CreateSpec, len(luicb.builders)) - nodes := make([]*LinUserIdentiy, len(luicb.builders)) - mutators := make([]Mutator, len(luicb.builders)) - for i := range luicb.builders { - func(i int, root context.Context) { - builder := luicb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserIdentiyMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() - var err error - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, luicb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, luicb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - 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, luicb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (luicb *LinUserIdentiyCreateBulk) SaveX(ctx context.Context) []*LinUserIdentiy { - v, err := luicb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (luicb *LinUserIdentiyCreateBulk) Exec(ctx context.Context) error { - _, err := luicb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luicb *LinUserIdentiyCreateBulk) ExecX(ctx context.Context) { - if err := luicb.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/data/model/linuseridentiy_delete.go b/internal/data/model/linuseridentiy_delete.go deleted file mode 100644 index 74d2ac9..0000000 --- a/internal/data/model/linuseridentiy_delete.go +++ /dev/null @@ -1,111 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linuseridentiy" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserIdentiyDelete is the builder for deleting a LinUserIdentiy entity. -type LinUserIdentiyDelete struct { - config - hooks []Hook - mutation *LinUserIdentiyMutation -} - -// Where appends a list predicates to the LinUserIdentiyDelete builder. -func (luid *LinUserIdentiyDelete) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyDelete { - luid.mutation.Where(ps...) - return luid -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (luid *LinUserIdentiyDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(luid.hooks) == 0 { - affected, err = luid.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserIdentiyMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - luid.mutation = mutation - affected, err = luid.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(luid.hooks) - 1; i >= 0; i-- { - if luid.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luid.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luid.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luid *LinUserIdentiyDelete) ExecX(ctx context.Context) int { - n, err := luid.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (luid *LinUserIdentiyDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuseridentiy.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - if ps := luid.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return sqlgraph.DeleteNodes(ctx, luid.driver, _spec) -} - -// LinUserIdentiyDeleteOne is the builder for deleting a single LinUserIdentiy entity. -type LinUserIdentiyDeleteOne struct { - luid *LinUserIdentiyDelete -} - -// Exec executes the deletion query. -func (luido *LinUserIdentiyDeleteOne) Exec(ctx context.Context) error { - n, err := luido.luid.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{linuseridentiy.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (luido *LinUserIdentiyDeleteOne) ExecX(ctx context.Context) { - luido.luid.ExecX(ctx) -} diff --git a/internal/data/model/linuseridentiy_query.go b/internal/data/model/linuseridentiy_query.go deleted file mode 100644 index 2a91964..0000000 --- a/internal/data/model/linuseridentiy_query.go +++ /dev/null @@ -1,965 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "errors" - "fmt" - "lin-cms-go/internal/data/model/linuseridentiy" - "lin-cms-go/internal/data/model/predicate" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserIdentiyQuery is the builder for querying LinUserIdentiy entities. -type LinUserIdentiyQuery struct { - config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.LinUserIdentiy - withFKs bool - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the LinUserIdentiyQuery builder. -func (luiq *LinUserIdentiyQuery) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyQuery { - luiq.predicates = append(luiq.predicates, ps...) - return luiq -} - -// Limit adds a limit step to the query. -func (luiq *LinUserIdentiyQuery) Limit(limit int) *LinUserIdentiyQuery { - luiq.limit = &limit - return luiq -} - -// Offset adds an offset step to the query. -func (luiq *LinUserIdentiyQuery) Offset(offset int) *LinUserIdentiyQuery { - luiq.offset = &offset - return luiq -} - -// 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 (luiq *LinUserIdentiyQuery) Unique(unique bool) *LinUserIdentiyQuery { - luiq.unique = &unique - return luiq -} - -// Order adds an order step to the query. -func (luiq *LinUserIdentiyQuery) Order(o ...OrderFunc) *LinUserIdentiyQuery { - luiq.order = append(luiq.order, o...) - return luiq -} - -// First returns the first LinUserIdentiy entity from the query. -// Returns a *NotFoundError when no LinUserIdentiy was found. -func (luiq *LinUserIdentiyQuery) First(ctx context.Context) (*LinUserIdentiy, error) { - nodes, err := luiq.Limit(1).All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linuseridentiy.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) FirstX(ctx context.Context) *LinUserIdentiy { - node, err := luiq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first LinUserIdentiy ID from the query. -// Returns a *NotFoundError when no LinUserIdentiy ID was found. -func (luiq *LinUserIdentiyQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = luiq.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linuseridentiy.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) FirstIDX(ctx context.Context) int { - id, err := luiq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Last returns the last LinUserIdentiy entity from the query. -// Returns a *NotFoundError when no LinUserIdentiy was found. -func (luiq *LinUserIdentiyQuery) Last(ctx context.Context) (*LinUserIdentiy, error) { - nodes, err := luiq.All(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{linuseridentiy.Label} - } - return nodes[len(nodes)-1], nil -} - -// LastX is like Last, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) LastX(ctx context.Context) *LinUserIdentiy { - node, err := luiq.Last(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// LastID returns the last LinUserIdentiy ID from the query. -// Returns a *NotFoundError when no LinUserIdentiy ID was found. -func (luiq *LinUserIdentiyQuery) LastID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = luiq.IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{linuseridentiy.Label} - return - } - return ids[len(ids)-1], nil -} - -// LastIDX is like LastID, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) LastIDX(ctx context.Context) int { - id, err := luiq.LastID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single LinUserIdentiy entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one LinUserIdentiy entity is not found. -// Returns a *NotFoundError when no LinUserIdentiy entities are found. -func (luiq *LinUserIdentiyQuery) Only(ctx context.Context) (*LinUserIdentiy, error) { - nodes, err := luiq.Limit(2).All(ctx) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{linuseridentiy.Label} - default: - return nil, &NotSingularError{linuseridentiy.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) OnlyX(ctx context.Context) *LinUserIdentiy { - node, err := luiq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only LinUserIdentiy ID in the query. -// Returns a *NotSingularError when exactly one LinUserIdentiy ID is not found. -// Returns a *NotFoundError when no entities are found. -func (luiq *LinUserIdentiyQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = luiq.Limit(2).IDs(ctx); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = &NotSingularError{linuseridentiy.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) OnlyIDX(ctx context.Context) int { - id, err := luiq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of LinUserIdentiys. -func (luiq *LinUserIdentiyQuery) All(ctx context.Context) ([]*LinUserIdentiy, error) { - if err := luiq.prepareQuery(ctx); err != nil { - return nil, err - } - return luiq.sqlAll(ctx) -} - -// AllX is like All, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) AllX(ctx context.Context) []*LinUserIdentiy { - nodes, err := luiq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of LinUserIdentiy IDs. -func (luiq *LinUserIdentiyQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := luiq.Select(linuseridentiy.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) IDsX(ctx context.Context) []int { - ids, err := luiq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (luiq *LinUserIdentiyQuery) Count(ctx context.Context) (int, error) { - if err := luiq.prepareQuery(ctx); err != nil { - return 0, err - } - return luiq.sqlCount(ctx) -} - -// CountX is like Count, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) CountX(ctx context.Context) int { - count, err := luiq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (luiq *LinUserIdentiyQuery) Exist(ctx context.Context) (bool, error) { - if err := luiq.prepareQuery(ctx); err != nil { - return false, err - } - return luiq.sqlExist(ctx) -} - -// ExistX is like Exist, but panics if an error occurs. -func (luiq *LinUserIdentiyQuery) ExistX(ctx context.Context) bool { - exist, err := luiq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the LinUserIdentiyQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (luiq *LinUserIdentiyQuery) Clone() *LinUserIdentiyQuery { - if luiq == nil { - return nil - } - return &LinUserIdentiyQuery{ - config: luiq.config, - limit: luiq.limit, - offset: luiq.offset, - order: append([]OrderFunc{}, luiq.order...), - predicates: append([]predicate.LinUserIdentiy{}, luiq.predicates...), - // clone intermediate query. - sql: luiq.sql.Clone(), - path: luiq.path, - } -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// UserID int `json:"user_id,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.LinUserIdentiy.Query(). -// GroupBy(linuseridentiy.FieldUserID). -// Aggregate(model.Count()). -// Scan(ctx, &v) -// -func (luiq *LinUserIdentiyQuery) GroupBy(field string, fields ...string) *LinUserIdentiyGroupBy { - group := &LinUserIdentiyGroupBy{config: luiq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := luiq.prepareQuery(ctx); err != nil { - return nil, err - } - return luiq.sqlQuery(ctx), nil - } - return group -} - -// 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 int `json:"user_id,omitempty"` -// } -// -// client.LinUserIdentiy.Query(). -// Select(linuseridentiy.FieldUserID). -// Scan(ctx, &v) -// -func (luiq *LinUserIdentiyQuery) Select(fields ...string) *LinUserIdentiySelect { - luiq.fields = append(luiq.fields, fields...) - return &LinUserIdentiySelect{LinUserIdentiyQuery: luiq} -} - -func (luiq *LinUserIdentiyQuery) prepareQuery(ctx context.Context) error { - for _, f := range luiq.fields { - if !linuseridentiy.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - } - if luiq.path != nil { - prev, err := luiq.path(ctx) - if err != nil { - return err - } - luiq.sql = prev - } - return nil -} - -func (luiq *LinUserIdentiyQuery) sqlAll(ctx context.Context) ([]*LinUserIdentiy, error) { - var ( - nodes = []*LinUserIdentiy{} - withFKs = luiq.withFKs - _spec = luiq.querySpec() - ) - if withFKs { - _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.ForeignKeys...) - } - _spec.ScanValues = func(columns []string) ([]interface{}, error) { - node := &LinUserIdentiy{config: luiq.config} - nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("model: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] - return node.assignValues(columns, values) - } - if err := sqlgraph.QueryNodes(ctx, luiq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (luiq *LinUserIdentiyQuery) sqlCount(ctx context.Context) (int, error) { - _spec := luiq.querySpec() - return sqlgraph.CountNodes(ctx, luiq.driver, _spec) -} - -func (luiq *LinUserIdentiyQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := luiq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("model: check existence: %w", err) - } - return n > 0, nil -} - -func (luiq *LinUserIdentiyQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuseridentiy.Table, - Columns: linuseridentiy.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - From: luiq.sql, - Unique: true, - } - if unique := luiq.unique; unique != nil { - _spec.Unique = *unique - } - if fields := luiq.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.FieldID) - for i := range fields { - if fields[i] != linuseridentiy.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := luiq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := luiq.limit; limit != nil { - _spec.Limit = *limit - } - if offset := luiq.offset; offset != nil { - _spec.Offset = *offset - } - if ps := luiq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (luiq *LinUserIdentiyQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(luiq.driver.Dialect()) - t1 := builder.Table(linuseridentiy.Table) - columns := luiq.fields - if len(columns) == 0 { - columns = linuseridentiy.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if luiq.sql != nil { - selector = luiq.sql - selector.Select(selector.Columns(columns...)...) - } - for _, p := range luiq.predicates { - p(selector) - } - for _, p := range luiq.order { - p(selector) - } - if offset := luiq.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 := luiq.limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// LinUserIdentiyGroupBy is the group-by builder for LinUserIdentiy entities. -type LinUserIdentiyGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (luigb *LinUserIdentiyGroupBy) Aggregate(fns ...AggregateFunc) *LinUserIdentiyGroupBy { - luigb.fns = append(luigb.fns, fns...) - return luigb -} - -// Scan applies the group-by query and scans the result into the given value. -func (luigb *LinUserIdentiyGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := luigb.path(ctx) - if err != nil { - return err - } - luigb.sql = query - return luigb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := luigb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(luigb.fields) > 1 { - return nil, errors.New("model: LinUserIdentiyGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := luigb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) StringsX(ctx context.Context) []string { - v, err := luigb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = luigb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiyGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) StringX(ctx context.Context) string { - v, err := luigb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(luigb.fields) > 1 { - return nil, errors.New("model: LinUserIdentiyGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := luigb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) IntsX(ctx context.Context) []int { - v, err := luigb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = luigb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiyGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) IntX(ctx context.Context) int { - v, err := luigb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(luigb.fields) > 1 { - return nil, errors.New("model: LinUserIdentiyGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := luigb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := luigb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = luigb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiyGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) Float64X(ctx context.Context) float64 { - v, err := luigb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(luigb.fields) > 1 { - return nil, errors.New("model: LinUserIdentiyGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := luigb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) BoolsX(ctx context.Context) []bool { - v, err := luigb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (luigb *LinUserIdentiyGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = luigb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiyGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (luigb *LinUserIdentiyGroupBy) BoolX(ctx context.Context) bool { - v, err := luigb.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (luigb *LinUserIdentiyGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range luigb.fields { - if !linuseridentiy.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} - } - } - selector := luigb.sqlQuery() - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := luigb.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -func (luigb *LinUserIdentiyGroupBy) sqlQuery() *sql.Selector { - selector := luigb.sql.Select() - aggregation := make([]string, 0, len(luigb.fns)) - for _, fn := range luigb.fns { - aggregation = append(aggregation, fn(selector)) - } - // If no columns were selected in a custom aggregation function, the default - // selection is the fields used for "group-by", and the aggregation functions. - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(luigb.fields)+len(luigb.fns)) - for _, f := range luigb.fields { - columns = append(columns, selector.C(f)) - } - for _, c := range aggregation { - columns = append(columns, c) - } - selector.Select(columns...) - } - return selector.GroupBy(selector.Columns(luigb.fields...)...) -} - -// LinUserIdentiySelect is the builder for selecting fields of LinUserIdentiy entities. -type LinUserIdentiySelect struct { - *LinUserIdentiyQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector -} - -// Scan applies the selector query and scans the result into the given value. -func (luis *LinUserIdentiySelect) Scan(ctx context.Context, v interface{}) error { - if err := luis.prepareQuery(ctx); err != nil { - return err - } - luis.sql = luis.LinUserIdentiyQuery.sqlQuery(ctx) - return luis.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (luis *LinUserIdentiySelect) ScanX(ctx context.Context, v interface{}) { - if err := luis.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Strings(ctx context.Context) ([]string, error) { - if len(luis.fields) > 1 { - return nil, errors.New("model: LinUserIdentiySelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := luis.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (luis *LinUserIdentiySelect) StringsX(ctx context.Context) []string { - v, err := luis.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = luis.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiySelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (luis *LinUserIdentiySelect) StringX(ctx context.Context) string { - v, err := luis.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Ints(ctx context.Context) ([]int, error) { - if len(luis.fields) > 1 { - return nil, errors.New("model: LinUserIdentiySelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := luis.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (luis *LinUserIdentiySelect) IntsX(ctx context.Context) []int { - v, err := luis.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = luis.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiySelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (luis *LinUserIdentiySelect) IntX(ctx context.Context) int { - v, err := luis.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Float64s(ctx context.Context) ([]float64, error) { - if len(luis.fields) > 1 { - return nil, errors.New("model: LinUserIdentiySelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := luis.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (luis *LinUserIdentiySelect) Float64sX(ctx context.Context) []float64 { - v, err := luis.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = luis.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiySelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (luis *LinUserIdentiySelect) Float64X(ctx context.Context) float64 { - v, err := luis.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Bools(ctx context.Context) ([]bool, error) { - if len(luis.fields) > 1 { - return nil, errors.New("model: LinUserIdentiySelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := luis.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (luis *LinUserIdentiySelect) BoolsX(ctx context.Context) []bool { - v, err := luis.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (luis *LinUserIdentiySelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = luis.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{linuseridentiy.Label} - default: - err = fmt.Errorf("model: LinUserIdentiySelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (luis *LinUserIdentiySelect) BoolX(ctx context.Context) bool { - v, err := luis.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (luis *LinUserIdentiySelect) sqlScan(ctx context.Context, v interface{}) error { - rows := &sql.Rows{} - query, args := luis.sql.Query() - if err := luis.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/data/model/linuseridentiy_update.go b/internal/data/model/linuseridentiy_update.go deleted file mode 100644 index d11f59b..0000000 --- a/internal/data/model/linuseridentiy_update.go +++ /dev/null @@ -1,370 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/linuseridentiy" - "lin-cms-go/internal/data/model/predicate" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// LinUserIdentiyUpdate is the builder for updating LinUserIdentiy entities. -type LinUserIdentiyUpdate struct { - config - hooks []Hook - mutation *LinUserIdentiyMutation -} - -// Where appends a list predicates to the LinUserIdentiyUpdate builder. -func (luiu *LinUserIdentiyUpdate) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyUpdate { - luiu.mutation.Where(ps...) - return luiu -} - -// SetUserID sets the "user_id" field. -func (luiu *LinUserIdentiyUpdate) SetUserID(i int) *LinUserIdentiyUpdate { - luiu.mutation.ResetUserID() - luiu.mutation.SetUserID(i) - return luiu -} - -// AddUserID adds i to the "user_id" field. -func (luiu *LinUserIdentiyUpdate) AddUserID(i int) *LinUserIdentiyUpdate { - luiu.mutation.AddUserID(i) - return luiu -} - -// SetIdentityType sets the "identity_type" field. -func (luiu *LinUserIdentiyUpdate) SetIdentityType(s string) *LinUserIdentiyUpdate { - luiu.mutation.SetIdentityType(s) - return luiu -} - -// SetIdentifier sets the "identifier" field. -func (luiu *LinUserIdentiyUpdate) SetIdentifier(s string) *LinUserIdentiyUpdate { - luiu.mutation.SetIdentifier(s) - return luiu -} - -// SetCredential sets the "credential" field. -func (luiu *LinUserIdentiyUpdate) SetCredential(s string) *LinUserIdentiyUpdate { - luiu.mutation.SetCredential(s) - return luiu -} - -// Mutation returns the LinUserIdentiyMutation object of the builder. -func (luiu *LinUserIdentiyUpdate) Mutation() *LinUserIdentiyMutation { - return luiu.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (luiu *LinUserIdentiyUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(luiu.hooks) == 0 { - affected, err = luiu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserIdentiyMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - luiu.mutation = mutation - affected, err = luiu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(luiu.hooks) - 1; i >= 0; i-- { - if luiu.hooks[i] == nil { - return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luiu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luiu.mutation); err != nil { - return 0, err - } - } - return affected, err -} - -// SaveX is like Save, but panics if an error occurs. -func (luiu *LinUserIdentiyUpdate) SaveX(ctx context.Context) int { - affected, err := luiu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (luiu *LinUserIdentiyUpdate) Exec(ctx context.Context) error { - _, err := luiu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luiu *LinUserIdentiyUpdate) ExecX(ctx context.Context) { - if err := luiu.Exec(ctx); err != nil { - panic(err) - } -} - -func (luiu *LinUserIdentiyUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuseridentiy.Table, - Columns: linuseridentiy.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - if ps := luiu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := luiu.mutation.UserID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linuseridentiy.FieldUserID, - }) - } - if value, ok := luiu.mutation.AddedUserID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linuseridentiy.FieldUserID, - }) - } - if value, ok := luiu.mutation.IdentityType(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldIdentityType, - }) - } - if value, ok := luiu.mutation.Identifier(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldIdentifier, - }) - } - if value, ok := luiu.mutation.Credential(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldCredential, - }) - } - if n, err = sqlgraph.UpdateNodes(ctx, luiu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linuseridentiy.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return 0, err - } - return n, nil -} - -// LinUserIdentiyUpdateOne is the builder for updating a single LinUserIdentiy entity. -type LinUserIdentiyUpdateOne struct { - config - fields []string - hooks []Hook - mutation *LinUserIdentiyMutation -} - -// SetUserID sets the "user_id" field. -func (luiuo *LinUserIdentiyUpdateOne) SetUserID(i int) *LinUserIdentiyUpdateOne { - luiuo.mutation.ResetUserID() - luiuo.mutation.SetUserID(i) - return luiuo -} - -// AddUserID adds i to the "user_id" field. -func (luiuo *LinUserIdentiyUpdateOne) AddUserID(i int) *LinUserIdentiyUpdateOne { - luiuo.mutation.AddUserID(i) - return luiuo -} - -// SetIdentityType sets the "identity_type" field. -func (luiuo *LinUserIdentiyUpdateOne) SetIdentityType(s string) *LinUserIdentiyUpdateOne { - luiuo.mutation.SetIdentityType(s) - return luiuo -} - -// SetIdentifier sets the "identifier" field. -func (luiuo *LinUserIdentiyUpdateOne) SetIdentifier(s string) *LinUserIdentiyUpdateOne { - luiuo.mutation.SetIdentifier(s) - return luiuo -} - -// SetCredential sets the "credential" field. -func (luiuo *LinUserIdentiyUpdateOne) SetCredential(s string) *LinUserIdentiyUpdateOne { - luiuo.mutation.SetCredential(s) - return luiuo -} - -// Mutation returns the LinUserIdentiyMutation object of the builder. -func (luiuo *LinUserIdentiyUpdateOne) Mutation() *LinUserIdentiyMutation { - return luiuo.mutation -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (luiuo *LinUserIdentiyUpdateOne) Select(field string, fields ...string) *LinUserIdentiyUpdateOne { - luiuo.fields = append([]string{field}, fields...) - return luiuo -} - -// Save executes the query and returns the updated LinUserIdentiy entity. -func (luiuo *LinUserIdentiyUpdateOne) Save(ctx context.Context) (*LinUserIdentiy, error) { - var ( - err error - node *LinUserIdentiy - ) - if len(luiuo.hooks) == 0 { - node, err = luiuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*LinUserIdentiyMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - luiuo.mutation = mutation - node, err = luiuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(luiuo.hooks) - 1; i >= 0; i-- { - if luiuo.hooks[i] == nil { - return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") - } - mut = luiuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, luiuo.mutation); err != nil { - return nil, err - } - } - return node, err -} - -// SaveX is like Save, but panics if an error occurs. -func (luiuo *LinUserIdentiyUpdateOne) SaveX(ctx context.Context) *LinUserIdentiy { - node, err := luiuo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (luiuo *LinUserIdentiyUpdateOne) Exec(ctx context.Context) error { - _, err := luiuo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (luiuo *LinUserIdentiyUpdateOne) ExecX(ctx context.Context) { - if err := luiuo.Exec(ctx); err != nil { - panic(err) - } -} - -func (luiuo *LinUserIdentiyUpdateOne) sqlSave(ctx context.Context) (_node *LinUserIdentiy, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: linuseridentiy.Table, - Columns: linuseridentiy.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: linuseridentiy.FieldID, - }, - }, - } - id, ok := luiuo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinUserIdentiy.ID for update")} - } - _spec.Node.ID.Value = id - if fields := luiuo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.FieldID) - for _, f := range fields { - if !linuseridentiy.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} - } - if f != linuseridentiy.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := luiuo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := luiuo.mutation.UserID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linuseridentiy.FieldUserID, - }) - } - if value, ok := luiuo.mutation.AddedUserID(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Value: value, - Column: linuseridentiy.FieldUserID, - }) - } - if value, ok := luiuo.mutation.IdentityType(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldIdentityType, - }) - } - if value, ok := luiuo.mutation.Identifier(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldIdentifier, - }) - } - if value, ok := luiuo.mutation.Credential(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: linuseridentiy.FieldCredential, - }) - } - _node = &LinUserIdentiy{config: luiuo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, luiuo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{linuseridentiy.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{err.Error(), err} - } - return nil, err - } - return _node, nil -} diff --git a/internal/data/model/migrate/migrate.go b/internal/data/model/migrate/migrate.go deleted file mode 100644 index e4a9a22..0000000 --- a/internal/data/model/migrate/migrate.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package migrate - -import ( - "context" - "fmt" - "io" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql/schema" -) - -var ( - // WithGlobalUniqueID sets the universal ids options to the migration. - // If this option is enabled, ent migration will allocate a 1<<32 range - // for the ids of each entity (table). - // Note that this option cannot be applied on tables that already exist. - WithGlobalUniqueID = schema.WithGlobalUniqueID - // WithDropColumn sets the drop column option to the migration. - // If this option is enabled, ent migration will drop old columns - // that were used for both fields and edges. This defaults to false. - WithDropColumn = schema.WithDropColumn - // WithDropIndex sets the drop index option to the migration. - // If this option is enabled, ent migration will drop old indexes - // that were defined in the schema. This defaults to false. - // Note that unique constraints are defined using `UNIQUE INDEX`, - // and therefore, it's recommended to enable this option to get more - // flexibility in the schema changes. - WithDropIndex = schema.WithDropIndex - // WithFixture sets the foreign-key renaming option to the migration when upgrading - // ent from v0.1.0 (issue-#285). Defaults to false. - WithFixture = schema.WithFixture - // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. - WithForeignKeys = schema.WithForeignKeys -) - -// Schema is the API for creating, migrating and dropping a schema. -type Schema struct { - drv dialect.Driver - universalID bool -} - -// NewSchema creates a new schema client. -func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } - -// Create creates all schema resources. -func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { - migrate, err := schema.NewMigrate(s.drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %w", err) - } - return migrate.Create(ctx, Tables...) -} - -// WriteTo writes the schema changes to w instead of running them against the database. -// -// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { -// log.Fatal(err) -// } -// -func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { - drv := &schema.WriteDriver{ - Writer: w, - Driver: s.drv, - } - migrate, err := schema.NewMigrate(drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %w", err) - } - return migrate.Create(ctx, Tables...) -} diff --git a/internal/data/model/migrate/schema.go b/internal/data/model/migrate/schema.go deleted file mode 100644 index 210788f..0000000 --- a/internal/data/model/migrate/schema.go +++ /dev/null @@ -1,235 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package migrate - -import ( - "entgo.io/ent/dialect/entsql" - "entgo.io/ent/dialect/sql/schema" - "entgo.io/ent/schema/field" -) - -var ( - // BookColumns holds the columns for the "book" table. - BookColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "title", Type: field.TypeString}, - {Name: "author", Type: field.TypeString}, - {Name: "summary", Type: field.TypeString}, - {Name: "image", Type: field.TypeString}, - } - // BookTable holds the schema information for the "book" table. - BookTable = &schema.Table{ - Name: "book", - Columns: BookColumns, - PrimaryKey: []*schema.Column{BookColumns[0]}, - } - // LinFileColumns holds the columns for the "lin_file" table. - LinFileColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "path", Type: field.TypeString}, - {Name: "type", Type: field.TypeInt8}, - {Name: "name", Type: field.TypeString}, - {Name: "extension", Type: field.TypeString}, - {Name: "size", Type: field.TypeInt}, - {Name: "md5", Type: field.TypeString, Unique: true}, - } - // LinFileTable holds the schema information for the "lin_file" table. - LinFileTable = &schema.Table{ - Name: "lin_file", - Columns: LinFileColumns, - PrimaryKey: []*schema.Column{LinFileColumns[0]}, - } - // LinGroupColumns holds the columns for the "lin_group" table. - LinGroupColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "name", Type: field.TypeString, Unique: true}, - {Name: "info", Type: field.TypeString}, - {Name: "level", Type: field.TypeInt8}, - } - // LinGroupTable holds the schema information for the "lin_group" table. - LinGroupTable = &schema.Table{ - Name: "lin_group", - Columns: LinGroupColumns, - PrimaryKey: []*schema.Column{LinGroupColumns[0]}, - } - // LinGroupPermissionColumns holds the columns for the "lin_group_permission" table. - LinGroupPermissionColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "group_id", Type: field.TypeInt, Unique: true}, - {Name: "permission_id", Type: field.TypeInt}, - } - // LinGroupPermissionTable holds the schema information for the "lin_group_permission" table. - LinGroupPermissionTable = &schema.Table{ - Name: "lin_group_permission", - Columns: LinGroupPermissionColumns, - PrimaryKey: []*schema.Column{LinGroupPermissionColumns[0]}, - } - // LinLogColumns holds the columns for the "lin_log" table. - LinLogColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "create_time", Type: field.TypeTime}, - {Name: "update_time", Type: field.TypeTime}, - {Name: "delete_time", Type: field.TypeTime}, - {Name: "message", Type: field.TypeString}, - {Name: "user_id", Type: field.TypeInt}, - {Name: "username", Type: field.TypeString}, - {Name: "status_code", Type: field.TypeInt}, - {Name: "method", Type: field.TypeString}, - {Name: "path", Type: field.TypeString}, - {Name: "permission", Type: field.TypeString}, - } - // LinLogTable holds the schema information for the "lin_log" table. - LinLogTable = &schema.Table{ - Name: "lin_log", - Columns: LinLogColumns, - PrimaryKey: []*schema.Column{LinLogColumns[0]}, - } - // LinPermissionColumns holds the columns for the "lin_permission" table. - LinPermissionColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "name", Type: field.TypeString}, - {Name: "module", Type: field.TypeString}, - {Name: "mount", Type: field.TypeInt8}, - } - // LinPermissionTable holds the schema information for the "lin_permission" table. - LinPermissionTable = &schema.Table{ - Name: "lin_permission", - Columns: LinPermissionColumns, - PrimaryKey: []*schema.Column{LinPermissionColumns[0]}, - } - // LinUserColumns holds the columns for the "lin_user" table. - LinUserColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "create_time", Type: field.TypeTime}, - {Name: "update_time", Type: field.TypeTime}, - {Name: "delete_time", Type: field.TypeTime}, - {Name: "username", Type: field.TypeString, Unique: true}, - {Name: "nickname", Type: field.TypeString}, - {Name: "avatar", Type: field.TypeString, Default: ""}, - {Name: "email", Type: field.TypeString, Unique: true}, - } - // LinUserTable holds the schema information for the "lin_user" table. - LinUserTable = &schema.Table{ - Name: "lin_user", - Columns: LinUserColumns, - PrimaryKey: []*schema.Column{LinUserColumns[0]}, - } - // LinUserIdentiyColumns holds the columns for the "lin_user_identiy" table. - LinUserIdentiyColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "user_id", Type: field.TypeInt}, - {Name: "identity_type", Type: field.TypeString}, - {Name: "identifier", Type: field.TypeString}, - {Name: "credential", Type: field.TypeString}, - {Name: "lin_user_lin_user_identiy", Type: field.TypeInt, Nullable: true}, - } - // LinUserIdentiyTable holds the schema information for the "lin_user_identiy" table. - LinUserIdentiyTable = &schema.Table{ - Name: "lin_user_identiy", - Columns: LinUserIdentiyColumns, - PrimaryKey: []*schema.Column{LinUserIdentiyColumns[0]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "lin_user_identiy_lin_user_lin_user_identiy", - Columns: []*schema.Column{LinUserIdentiyColumns[5]}, - RefColumns: []*schema.Column{LinUserColumns[0]}, - OnDelete: schema.SetNull, - }, - }, - } - // LinUserGroupColumns holds the columns for the "lin_user_group" table. - LinUserGroupColumns = []*schema.Column{ - {Name: "user_id", Type: field.TypeInt}, - {Name: "group_id", Type: field.TypeInt}, - } - // LinUserGroupTable holds the schema information for the "lin_user_group" table. - LinUserGroupTable = &schema.Table{ - Name: "lin_user_group", - Columns: LinUserGroupColumns, - PrimaryKey: []*schema.Column{LinUserGroupColumns[0], LinUserGroupColumns[1]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "lin_user_group_user_id", - Columns: []*schema.Column{LinUserGroupColumns[0]}, - RefColumns: []*schema.Column{LinGroupColumns[0]}, - OnDelete: schema.Cascade, - }, - { - Symbol: "lin_user_group_group_id", - Columns: []*schema.Column{LinUserGroupColumns[1]}, - RefColumns: []*schema.Column{LinUserColumns[0]}, - OnDelete: schema.Cascade, - }, - }, - } - // LinPermissionLinGroupColumns holds the columns for the "lin_permission_lin_group" table. - LinPermissionLinGroupColumns = []*schema.Column{ - {Name: "lin_permission_id", Type: field.TypeInt}, - {Name: "lin_group_id", Type: field.TypeInt}, - } - // LinPermissionLinGroupTable holds the schema information for the "lin_permission_lin_group" table. - LinPermissionLinGroupTable = &schema.Table{ - Name: "lin_permission_lin_group", - Columns: LinPermissionLinGroupColumns, - PrimaryKey: []*schema.Column{LinPermissionLinGroupColumns[0], LinPermissionLinGroupColumns[1]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "lin_permission_lin_group_lin_permission_id", - Columns: []*schema.Column{LinPermissionLinGroupColumns[0]}, - RefColumns: []*schema.Column{LinPermissionColumns[0]}, - OnDelete: schema.Cascade, - }, - { - Symbol: "lin_permission_lin_group_lin_group_id", - Columns: []*schema.Column{LinPermissionLinGroupColumns[1]}, - RefColumns: []*schema.Column{LinGroupColumns[0]}, - OnDelete: schema.Cascade, - }, - }, - } - // Tables holds all the tables in the schema. - Tables = []*schema.Table{ - BookTable, - LinFileTable, - LinGroupTable, - LinGroupPermissionTable, - LinLogTable, - LinPermissionTable, - LinUserTable, - LinUserIdentiyTable, - LinUserGroupTable, - LinPermissionLinGroupTable, - } -) - -func init() { - BookTable.Annotation = &entsql.Annotation{ - Table: "book", - } - LinFileTable.Annotation = &entsql.Annotation{ - Table: "lin_file", - } - LinGroupTable.Annotation = &entsql.Annotation{ - Table: "lin_group", - } - LinGroupPermissionTable.Annotation = &entsql.Annotation{ - Table: "lin_group_permission", - } - LinLogTable.Annotation = &entsql.Annotation{ - Table: "lin_log", - } - LinPermissionTable.Annotation = &entsql.Annotation{ - Table: "lin_permission", - } - LinUserTable.Annotation = &entsql.Annotation{ - Table: "lin_user", - } - LinUserIdentiyTable.ForeignKeys[0].RefTable = LinUserTable - LinUserIdentiyTable.Annotation = &entsql.Annotation{ - Table: "lin_user_identiy", - } - LinUserGroupTable.ForeignKeys[0].RefTable = LinGroupTable - LinUserGroupTable.ForeignKeys[1].RefTable = LinUserTable - LinPermissionLinGroupTable.ForeignKeys[0].RefTable = LinPermissionTable - LinPermissionLinGroupTable.ForeignKeys[1].RefTable = LinGroupTable -} diff --git a/internal/data/model/mutation.go b/internal/data/model/mutation.go deleted file mode 100644 index 0d37c80..0000000 --- a/internal/data/model/mutation.go +++ /dev/null @@ -1,4810 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "fmt" - "lin-cms-go/internal/data/model/book" - "lin-cms-go/internal/data/model/linfile" - "lin-cms-go/internal/data/model/lingroup" - "lin-cms-go/internal/data/model/lingrouppermission" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/linpermission" - "lin-cms-go/internal/data/model/linuser" - "lin-cms-go/internal/data/model/linuseridentiy" - "lin-cms-go/internal/data/model/predicate" - "sync" - "time" - - "entgo.io/ent" -) - -const ( - // Operation types. - OpCreate = ent.OpCreate - OpDelete = ent.OpDelete - OpDeleteOne = ent.OpDeleteOne - OpUpdate = ent.OpUpdate - OpUpdateOne = ent.OpUpdateOne - - // Node types. - TypeBook = "Book" - TypeLinFile = "LinFile" - TypeLinGroup = "LinGroup" - TypeLinGroupPermission = "LinGroupPermission" - TypeLinLog = "LinLog" - TypeLinPermission = "LinPermission" - TypeLinUser = "LinUser" - TypeLinUserIdentiy = "LinUserIdentiy" -) - -// BookMutation represents an operation that mutates the Book nodes in the graph. -type BookMutation struct { - config - op Op - typ string - id *int - title *string - author *string - summary *string - image *string - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Book, error) - predicates []predicate.Book -} - -var _ ent.Mutation = (*BookMutation)(nil) - -// bookOption allows management of the mutation configuration using functional options. -type bookOption func(*BookMutation) - -// newBookMutation creates new mutation for the Book entity. -func newBookMutation(c config, op Op, opts ...bookOption) *BookMutation { - m := &BookMutation{ - config: c, - op: op, - typ: TypeBook, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withBookID sets the ID field of the mutation. -func withBookID(id int) bookOption { - return func(m *BookMutation) { - var ( - err error - once sync.Once - value *Book - ) - m.oldValue = func(ctx context.Context) (*Book, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Book.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withBook sets the old Book of the mutation. -func withBook(node *Book) bookOption { - return func(m *BookMutation) { - m.oldValue = func(context.Context) (*Book, 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 BookMutation) 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 BookMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *BookMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetTitle sets the "title" field. -func (m *BookMutation) SetTitle(s string) { - m.title = &s -} - -// Title returns the value of the "title" field in the mutation. -func (m *BookMutation) Title() (r string, exists bool) { - v := m.title - if v == nil { - return - } - return *v, true -} - -// OldTitle returns the old "title" field's value of the Book entity. -// If the Book 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 *BookMutation) OldTitle(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldTitle is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldTitle requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTitle: %w", err) - } - return oldValue.Title, nil -} - -// ResetTitle resets all changes to the "title" field. -func (m *BookMutation) ResetTitle() { - m.title = nil -} - -// SetAuthor sets the "author" field. -func (m *BookMutation) SetAuthor(s string) { - m.author = &s -} - -// Author returns the value of the "author" field in the mutation. -func (m *BookMutation) Author() (r string, exists bool) { - v := m.author - if v == nil { - return - } - return *v, true -} - -// OldAuthor returns the old "author" field's value of the Book entity. -// If the Book 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 *BookMutation) OldAuthor(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldAuthor is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldAuthor requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAuthor: %w", err) - } - return oldValue.Author, nil -} - -// ResetAuthor resets all changes to the "author" field. -func (m *BookMutation) ResetAuthor() { - m.author = nil -} - -// SetSummary sets the "summary" field. -func (m *BookMutation) SetSummary(s string) { - m.summary = &s -} - -// Summary returns the value of the "summary" field in the mutation. -func (m *BookMutation) Summary() (r string, exists bool) { - v := m.summary - if v == nil { - return - } - return *v, true -} - -// OldSummary returns the old "summary" field's value of the Book entity. -// If the Book 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 *BookMutation) OldSummary(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldSummary is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldSummary requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSummary: %w", err) - } - return oldValue.Summary, nil -} - -// ResetSummary resets all changes to the "summary" field. -func (m *BookMutation) ResetSummary() { - m.summary = nil -} - -// SetImage sets the "image" field. -func (m *BookMutation) SetImage(s string) { - m.image = &s -} - -// Image returns the value of the "image" field in the mutation. -func (m *BookMutation) Image() (r string, exists bool) { - v := m.image - if v == nil { - return - } - return *v, true -} - -// OldImage returns the old "image" field's value of the Book entity. -// If the Book 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 *BookMutation) OldImage(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldImage is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldImage requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldImage: %w", err) - } - return oldValue.Image, nil -} - -// ResetImage resets all changes to the "image" field. -func (m *BookMutation) ResetImage() { - m.image = nil -} - -// Where appends a list predicates to the BookMutation builder. -func (m *BookMutation) Where(ps ...predicate.Book) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *BookMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (Book). -func (m *BookMutation) 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 *BookMutation) Fields() []string { - fields := make([]string, 0, 4) - if m.title != nil { - fields = append(fields, book.FieldTitle) - } - if m.author != nil { - fields = append(fields, book.FieldAuthor) - } - if m.summary != nil { - fields = append(fields, book.FieldSummary) - } - if m.image != nil { - fields = append(fields, book.FieldImage) - } - 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 *BookMutation) Field(name string) (ent.Value, bool) { - switch name { - case book.FieldTitle: - return m.Title() - case book.FieldAuthor: - return m.Author() - case book.FieldSummary: - return m.Summary() - case book.FieldImage: - return m.Image() - } - 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 *BookMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case book.FieldTitle: - return m.OldTitle(ctx) - case book.FieldAuthor: - return m.OldAuthor(ctx) - case book.FieldSummary: - return m.OldSummary(ctx) - case book.FieldImage: - return m.OldImage(ctx) - } - return nil, fmt.Errorf("unknown Book 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 *BookMutation) SetField(name string, value ent.Value) error { - switch name { - case book.FieldTitle: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTitle(v) - return nil - case book.FieldAuthor: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAuthor(v) - return nil - case book.FieldSummary: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSummary(v) - return nil - case book.FieldImage: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetImage(v) - return nil - } - return fmt.Errorf("unknown Book field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *BookMutation) 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 *BookMutation) 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 *BookMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown Book numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *BookMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *BookMutation) 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 *BookMutation) ClearField(name string) error { - return fmt.Errorf("unknown Book 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 *BookMutation) ResetField(name string) error { - switch name { - case book.FieldTitle: - m.ResetTitle() - return nil - case book.FieldAuthor: - m.ResetAuthor() - return nil - case book.FieldSummary: - m.ResetSummary() - return nil - case book.FieldImage: - m.ResetImage() - return nil - } - return fmt.Errorf("unknown Book field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *BookMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *BookMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *BookMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *BookMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *BookMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *BookMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *BookMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Book 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 *BookMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Book edge %s", name) -} - -// LinFileMutation represents an operation that mutates the LinFile nodes in the graph. -type LinFileMutation struct { - config - op Op - typ string - id *int - _path *string - _type *int8 - add_type *int8 - name *string - extension *string - size *int - addsize *int - md5 *string - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*LinFile, error) - predicates []predicate.LinFile -} - -var _ ent.Mutation = (*LinFileMutation)(nil) - -// linfileOption allows management of the mutation configuration using functional options. -type linfileOption func(*LinFileMutation) - -// newLinFileMutation creates new mutation for the LinFile entity. -func newLinFileMutation(c config, op Op, opts ...linfileOption) *LinFileMutation { - m := &LinFileMutation{ - config: c, - op: op, - typ: TypeLinFile, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinFileID sets the ID field of the mutation. -func withLinFileID(id int) linfileOption { - return func(m *LinFileMutation) { - var ( - err error - once sync.Once - value *LinFile - ) - m.oldValue = func(ctx context.Context) (*LinFile, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinFile.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinFile sets the old LinFile of the mutation. -func withLinFile(node *LinFile) linfileOption { - return func(m *LinFileMutation) { - m.oldValue = func(context.Context) (*LinFile, 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 LinFileMutation) 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 LinFileMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinFileMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetPath sets the "path" field. -func (m *LinFileMutation) SetPath(s string) { - m._path = &s -} - -// Path returns the value of the "path" field in the mutation. -func (m *LinFileMutation) Path() (r string, exists bool) { - v := m._path - if v == nil { - return - } - return *v, true -} - -// OldPath returns the old "path" field's value of the LinFile entity. -// If the LinFile 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 *LinFileMutation) OldPath(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldPath is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldPath requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPath: %w", err) - } - return oldValue.Path, nil -} - -// ResetPath resets all changes to the "path" field. -func (m *LinFileMutation) ResetPath() { - m._path = nil -} - -// SetType sets the "type" field. -func (m *LinFileMutation) SetType(i int8) { - m._type = &i - m.add_type = nil -} - -// GetType returns the value of the "type" field in the mutation. -func (m *LinFileMutation) GetType() (r int8, exists bool) { - v := m._type - if v == nil { - return - } - return *v, true -} - -// OldType returns the old "type" field's value of the LinFile entity. -// If the LinFile 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 *LinFileMutation) OldType(ctx context.Context) (v int8, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldType is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldType requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldType: %w", err) - } - return oldValue.Type, nil -} - -// AddType adds i to the "type" field. -func (m *LinFileMutation) AddType(i int8) { - if m.add_type != nil { - *m.add_type += i - } else { - m.add_type = &i - } -} - -// AddedType returns the value that was added to the "type" field in this mutation. -func (m *LinFileMutation) AddedType() (r int8, exists bool) { - v := m.add_type - if v == nil { - return - } - return *v, true -} - -// ResetType resets all changes to the "type" field. -func (m *LinFileMutation) ResetType() { - m._type = nil - m.add_type = nil -} - -// SetName sets the "name" field. -func (m *LinFileMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *LinFileMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true -} - -// OldName returns the old "name" field's value of the LinFile entity. -// If the LinFile 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 *LinFileMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) - } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *LinFileMutation) ResetName() { - m.name = nil -} - -// SetExtension sets the "extension" field. -func (m *LinFileMutation) SetExtension(s string) { - m.extension = &s -} - -// Extension returns the value of the "extension" field in the mutation. -func (m *LinFileMutation) Extension() (r string, exists bool) { - v := m.extension - if v == nil { - return - } - return *v, true -} - -// OldExtension returns the old "extension" field's value of the LinFile entity. -// If the LinFile 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 *LinFileMutation) OldExtension(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldExtension is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldExtension requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldExtension: %w", err) - } - return oldValue.Extension, nil -} - -// ResetExtension resets all changes to the "extension" field. -func (m *LinFileMutation) ResetExtension() { - m.extension = nil -} - -// SetSize sets the "size" field. -func (m *LinFileMutation) SetSize(i int) { - m.size = &i - m.addsize = nil -} - -// Size returns the value of the "size" field in the mutation. -func (m *LinFileMutation) Size() (r int, exists bool) { - v := m.size - if v == nil { - return - } - return *v, true -} - -// OldSize returns the old "size" field's value of the LinFile entity. -// If the LinFile 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 *LinFileMutation) OldSize(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldSize is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldSize requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSize: %w", err) - } - return oldValue.Size, nil -} - -// AddSize adds i to the "size" field. -func (m *LinFileMutation) AddSize(i int) { - if m.addsize != nil { - *m.addsize += i - } else { - m.addsize = &i - } -} - -// AddedSize returns the value that was added to the "size" field in this mutation. -func (m *LinFileMutation) AddedSize() (r int, exists bool) { - v := m.addsize - if v == nil { - return - } - return *v, true -} - -// ResetSize resets all changes to the "size" field. -func (m *LinFileMutation) ResetSize() { - m.size = nil - m.addsize = nil -} - -// SetMd5 sets the "md5" field. -func (m *LinFileMutation) SetMd5(s string) { - m.md5 = &s -} - -// Md5 returns the value of the "md5" field in the mutation. -func (m *LinFileMutation) Md5() (r string, exists bool) { - v := m.md5 - if v == nil { - return - } - return *v, true -} - -// OldMd5 returns the old "md5" field's value of the LinFile entity. -// If the LinFile 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 *LinFileMutation) OldMd5(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMd5 is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMd5 requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMd5: %w", err) - } - return oldValue.Md5, nil -} - -// ResetMd5 resets all changes to the "md5" field. -func (m *LinFileMutation) ResetMd5() { - m.md5 = nil -} - -// Where appends a list predicates to the LinFileMutation builder. -func (m *LinFileMutation) Where(ps ...predicate.LinFile) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinFileMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinFile). -func (m *LinFileMutation) 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 *LinFileMutation) Fields() []string { - fields := make([]string, 0, 6) - if m._path != nil { - fields = append(fields, linfile.FieldPath) - } - if m._type != nil { - fields = append(fields, linfile.FieldType) - } - if m.name != nil { - fields = append(fields, linfile.FieldName) - } - if m.extension != nil { - fields = append(fields, linfile.FieldExtension) - } - if m.size != nil { - fields = append(fields, linfile.FieldSize) - } - if m.md5 != nil { - fields = append(fields, linfile.FieldMd5) - } - 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 *LinFileMutation) Field(name string) (ent.Value, bool) { - switch name { - case linfile.FieldPath: - return m.Path() - case linfile.FieldType: - return m.GetType() - case linfile.FieldName: - return m.Name() - case linfile.FieldExtension: - return m.Extension() - case linfile.FieldSize: - return m.Size() - case linfile.FieldMd5: - return m.Md5() - } - 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 *LinFileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case linfile.FieldPath: - return m.OldPath(ctx) - case linfile.FieldType: - return m.OldType(ctx) - case linfile.FieldName: - return m.OldName(ctx) - case linfile.FieldExtension: - return m.OldExtension(ctx) - case linfile.FieldSize: - return m.OldSize(ctx) - case linfile.FieldMd5: - return m.OldMd5(ctx) - } - return nil, fmt.Errorf("unknown LinFile 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 *LinFileMutation) SetField(name string, value ent.Value) error { - switch name { - case linfile.FieldPath: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPath(v) - return nil - case linfile.FieldType: - v, ok := value.(int8) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetType(v) - return nil - case linfile.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case linfile.FieldExtension: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetExtension(v) - return nil - case linfile.FieldSize: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSize(v) - return nil - case linfile.FieldMd5: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMd5(v) - return nil - } - return fmt.Errorf("unknown LinFile field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinFileMutation) AddedFields() []string { - var fields []string - if m.add_type != nil { - fields = append(fields, linfile.FieldType) - } - if m.addsize != nil { - fields = append(fields, linfile.FieldSize) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *LinFileMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case linfile.FieldType: - return m.AddedType() - case linfile.FieldSize: - return m.AddedSize() - } - 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 *LinFileMutation) AddField(name string, value ent.Value) error { - switch name { - case linfile.FieldType: - v, ok := value.(int8) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddType(v) - return nil - case linfile.FieldSize: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddSize(v) - return nil - } - return fmt.Errorf("unknown LinFile numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinFileMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinFileMutation) 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 *LinFileMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinFile 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 *LinFileMutation) ResetField(name string) error { - switch name { - case linfile.FieldPath: - m.ResetPath() - return nil - case linfile.FieldType: - m.ResetType() - return nil - case linfile.FieldName: - m.ResetName() - return nil - case linfile.FieldExtension: - m.ResetExtension() - return nil - case linfile.FieldSize: - m.ResetSize() - return nil - case linfile.FieldMd5: - m.ResetMd5() - return nil - } - return fmt.Errorf("unknown LinFile field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinFileMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinFileMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinFileMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinFileMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinFileMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinFileMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *LinFileMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown LinFile 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 *LinFileMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown LinFile edge %s", name) -} - -// LinGroupMutation represents an operation that mutates the LinGroup nodes in the graph. -type LinGroupMutation struct { - config - op Op - typ string - id *int - name *string - info *string - level *int8 - addlevel *int8 - clearedFields map[string]struct{} - lin_user map[int]struct{} - removedlin_user map[int]struct{} - clearedlin_user bool - lin_permission map[int]struct{} - removedlin_permission map[int]struct{} - clearedlin_permission bool - done bool - oldValue func(context.Context) (*LinGroup, error) - predicates []predicate.LinGroup -} - -var _ ent.Mutation = (*LinGroupMutation)(nil) - -// lingroupOption allows management of the mutation configuration using functional options. -type lingroupOption func(*LinGroupMutation) - -// newLinGroupMutation creates new mutation for the LinGroup entity. -func newLinGroupMutation(c config, op Op, opts ...lingroupOption) *LinGroupMutation { - m := &LinGroupMutation{ - config: c, - op: op, - typ: TypeLinGroup, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinGroupID sets the ID field of the mutation. -func withLinGroupID(id int) lingroupOption { - return func(m *LinGroupMutation) { - var ( - err error - once sync.Once - value *LinGroup - ) - m.oldValue = func(ctx context.Context) (*LinGroup, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinGroup.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinGroup sets the old LinGroup of the mutation. -func withLinGroup(node *LinGroup) lingroupOption { - return func(m *LinGroupMutation) { - m.oldValue = func(context.Context) (*LinGroup, 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 LinGroupMutation) 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 LinGroupMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinGroupMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetName sets the "name" field. -func (m *LinGroupMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *LinGroupMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true -} - -// OldName returns the old "name" field's value of the LinGroup entity. -// If the LinGroup 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 *LinGroupMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) - } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *LinGroupMutation) ResetName() { - m.name = nil -} - -// SetInfo sets the "info" field. -func (m *LinGroupMutation) SetInfo(s string) { - m.info = &s -} - -// Info returns the value of the "info" field in the mutation. -func (m *LinGroupMutation) Info() (r string, exists bool) { - v := m.info - if v == nil { - return - } - return *v, true -} - -// OldInfo returns the old "info" field's value of the LinGroup entity. -// If the LinGroup 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 *LinGroupMutation) OldInfo(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldInfo is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldInfo requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldInfo: %w", err) - } - return oldValue.Info, nil -} - -// ResetInfo resets all changes to the "info" field. -func (m *LinGroupMutation) ResetInfo() { - m.info = nil -} - -// SetLevel sets the "level" field. -func (m *LinGroupMutation) SetLevel(i int8) { - m.level = &i - m.addlevel = nil -} - -// Level returns the value of the "level" field in the mutation. -func (m *LinGroupMutation) Level() (r int8, exists bool) { - v := m.level - if v == nil { - return - } - return *v, true -} - -// OldLevel returns the old "level" field's value of the LinGroup entity. -// If the LinGroup 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 *LinGroupMutation) OldLevel(ctx context.Context) (v int8, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldLevel is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldLevel requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldLevel: %w", err) - } - return oldValue.Level, nil -} - -// AddLevel adds i to the "level" field. -func (m *LinGroupMutation) AddLevel(i int8) { - if m.addlevel != nil { - *m.addlevel += i - } else { - m.addlevel = &i - } -} - -// AddedLevel returns the value that was added to the "level" field in this mutation. -func (m *LinGroupMutation) AddedLevel() (r int8, exists bool) { - v := m.addlevel - if v == nil { - return - } - return *v, true -} - -// ResetLevel resets all changes to the "level" field. -func (m *LinGroupMutation) ResetLevel() { - m.level = nil - m.addlevel = nil -} - -// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by ids. -func (m *LinGroupMutation) AddLinUserIDs(ids ...int) { - if m.lin_user == nil { - m.lin_user = make(map[int]struct{}) - } - for i := range ids { - m.lin_user[ids[i]] = struct{}{} - } -} - -// ClearLinUser clears the "lin_user" edge to the LinUser entity. -func (m *LinGroupMutation) ClearLinUser() { - m.clearedlin_user = true -} - -// LinUserCleared reports if the "lin_user" edge to the LinUser entity was cleared. -func (m *LinGroupMutation) LinUserCleared() bool { - return m.clearedlin_user -} - -// RemoveLinUserIDs removes the "lin_user" edge to the LinUser entity by IDs. -func (m *LinGroupMutation) RemoveLinUserIDs(ids ...int) { - if m.removedlin_user == nil { - m.removedlin_user = make(map[int]struct{}) - } - for i := range ids { - delete(m.lin_user, ids[i]) - m.removedlin_user[ids[i]] = struct{}{} - } -} - -// RemovedLinUser returns the removed IDs of the "lin_user" edge to the LinUser entity. -func (m *LinGroupMutation) RemovedLinUserIDs() (ids []int) { - for id := range m.removedlin_user { - ids = append(ids, id) - } - return -} - -// LinUserIDs returns the "lin_user" edge IDs in the mutation. -func (m *LinGroupMutation) LinUserIDs() (ids []int) { - for id := range m.lin_user { - ids = append(ids, id) - } - return -} - -// ResetLinUser resets all changes to the "lin_user" edge. -func (m *LinGroupMutation) ResetLinUser() { - m.lin_user = nil - m.clearedlin_user = false - m.removedlin_user = nil -} - -// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by ids. -func (m *LinGroupMutation) AddLinPermissionIDs(ids ...int) { - if m.lin_permission == nil { - m.lin_permission = make(map[int]struct{}) - } - for i := range ids { - m.lin_permission[ids[i]] = struct{}{} - } -} - -// ClearLinPermission clears the "lin_permission" edge to the LinPermission entity. -func (m *LinGroupMutation) ClearLinPermission() { - m.clearedlin_permission = true -} - -// LinPermissionCleared reports if the "lin_permission" edge to the LinPermission entity was cleared. -func (m *LinGroupMutation) LinPermissionCleared() bool { - return m.clearedlin_permission -} - -// RemoveLinPermissionIDs removes the "lin_permission" edge to the LinPermission entity by IDs. -func (m *LinGroupMutation) RemoveLinPermissionIDs(ids ...int) { - if m.removedlin_permission == nil { - m.removedlin_permission = make(map[int]struct{}) - } - for i := range ids { - delete(m.lin_permission, ids[i]) - m.removedlin_permission[ids[i]] = struct{}{} - } -} - -// RemovedLinPermission returns the removed IDs of the "lin_permission" edge to the LinPermission entity. -func (m *LinGroupMutation) RemovedLinPermissionIDs() (ids []int) { - for id := range m.removedlin_permission { - ids = append(ids, id) - } - return -} - -// LinPermissionIDs returns the "lin_permission" edge IDs in the mutation. -func (m *LinGroupMutation) LinPermissionIDs() (ids []int) { - for id := range m.lin_permission { - ids = append(ids, id) - } - return -} - -// ResetLinPermission resets all changes to the "lin_permission" edge. -func (m *LinGroupMutation) ResetLinPermission() { - m.lin_permission = nil - m.clearedlin_permission = false - m.removedlin_permission = nil -} - -// Where appends a list predicates to the LinGroupMutation builder. -func (m *LinGroupMutation) Where(ps ...predicate.LinGroup) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinGroupMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinGroup). -func (m *LinGroupMutation) 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 *LinGroupMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.name != nil { - fields = append(fields, lingroup.FieldName) - } - if m.info != nil { - fields = append(fields, lingroup.FieldInfo) - } - if m.level != nil { - fields = append(fields, lingroup.FieldLevel) - } - 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 *LinGroupMutation) Field(name string) (ent.Value, bool) { - switch name { - case lingroup.FieldName: - return m.Name() - case lingroup.FieldInfo: - return m.Info() - case lingroup.FieldLevel: - return m.Level() - } - 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 *LinGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case lingroup.FieldName: - return m.OldName(ctx) - case lingroup.FieldInfo: - return m.OldInfo(ctx) - case lingroup.FieldLevel: - return m.OldLevel(ctx) - } - return nil, fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) SetField(name string, value ent.Value) error { - switch name { - case lingroup.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case lingroup.FieldInfo: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetInfo(v) - return nil - case lingroup.FieldLevel: - v, ok := value.(int8) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLevel(v) - return nil - } - return fmt.Errorf("unknown LinGroup field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinGroupMutation) AddedFields() []string { - var fields []string - if m.addlevel != nil { - fields = append(fields, lingroup.FieldLevel) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *LinGroupMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case lingroup.FieldLevel: - return m.AddedLevel() - } - 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 *LinGroupMutation) AddField(name string, value ent.Value) error { - switch name { - case lingroup.FieldLevel: - v, ok := value.(int8) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddLevel(v) - return nil - } - return fmt.Errorf("unknown LinGroup numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinGroupMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinGroupMutation) 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 *LinGroupMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) ResetField(name string) error { - switch name { - case lingroup.FieldName: - m.ResetName() - return nil - case lingroup.FieldInfo: - m.ResetInfo() - return nil - case lingroup.FieldLevel: - m.ResetLevel() - return nil - } - return fmt.Errorf("unknown LinGroup field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinGroupMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.lin_user != nil { - edges = append(edges, lingroup.EdgeLinUser) - } - if m.lin_permission != nil { - edges = append(edges, lingroup.EdgeLinPermission) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinGroupMutation) AddedIDs(name string) []ent.Value { - switch name { - case lingroup.EdgeLinUser: - ids := make([]ent.Value, 0, len(m.lin_user)) - for id := range m.lin_user { - ids = append(ids, id) - } - return ids - case lingroup.EdgeLinPermission: - ids := make([]ent.Value, 0, len(m.lin_permission)) - for id := range m.lin_permission { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinGroupMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - if m.removedlin_user != nil { - edges = append(edges, lingroup.EdgeLinUser) - } - if m.removedlin_permission != nil { - edges = append(edges, lingroup.EdgeLinPermission) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinGroupMutation) RemovedIDs(name string) []ent.Value { - switch name { - case lingroup.EdgeLinUser: - ids := make([]ent.Value, 0, len(m.removedlin_user)) - for id := range m.removedlin_user { - ids = append(ids, id) - } - return ids - case lingroup.EdgeLinPermission: - ids := make([]ent.Value, 0, len(m.removedlin_permission)) - for id := range m.removedlin_permission { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinGroupMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedlin_user { - edges = append(edges, lingroup.EdgeLinUser) - } - if m.clearedlin_permission { - edges = append(edges, lingroup.EdgeLinPermission) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinGroupMutation) EdgeCleared(name string) bool { - switch name { - case lingroup.EdgeLinUser: - return m.clearedlin_user - case lingroup.EdgeLinPermission: - return m.clearedlin_permission - } - 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 *LinGroupMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) ResetEdge(name string) error { - switch name { - case lingroup.EdgeLinUser: - m.ResetLinUser() - return nil - case lingroup.EdgeLinPermission: - m.ResetLinPermission() - return nil - } - return fmt.Errorf("unknown LinGroup edge %s", name) -} - -// LinGroupPermissionMutation represents an operation that mutates the LinGroupPermission nodes in the graph. -type LinGroupPermissionMutation struct { - config - op Op - typ string - id *int - group_id *int - addgroup_id *int - permission_id *int - addpermission_id *int - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*LinGroupPermission, error) - predicates []predicate.LinGroupPermission -} - -var _ ent.Mutation = (*LinGroupPermissionMutation)(nil) - -// lingrouppermissionOption allows management of the mutation configuration using functional options. -type lingrouppermissionOption func(*LinGroupPermissionMutation) - -// newLinGroupPermissionMutation creates new mutation for the LinGroupPermission entity. -func newLinGroupPermissionMutation(c config, op Op, opts ...lingrouppermissionOption) *LinGroupPermissionMutation { - m := &LinGroupPermissionMutation{ - config: c, - op: op, - typ: TypeLinGroupPermission, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinGroupPermissionID sets the ID field of the mutation. -func withLinGroupPermissionID(id int) lingrouppermissionOption { - return func(m *LinGroupPermissionMutation) { - var ( - err error - once sync.Once - value *LinGroupPermission - ) - m.oldValue = func(ctx context.Context) (*LinGroupPermission, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinGroupPermission.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinGroupPermission sets the old LinGroupPermission of the mutation. -func withLinGroupPermission(node *LinGroupPermission) lingrouppermissionOption { - return func(m *LinGroupPermissionMutation) { - m.oldValue = func(context.Context) (*LinGroupPermission, 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 LinGroupPermissionMutation) 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 LinGroupPermissionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinGroupPermissionMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetGroupID sets the "group_id" field. -func (m *LinGroupPermissionMutation) SetGroupID(i int) { - m.group_id = &i - m.addgroup_id = nil -} - -// GroupID returns the value of the "group_id" field in the mutation. -func (m *LinGroupPermissionMutation) GroupID() (r int, exists bool) { - v := m.group_id - if v == nil { - return - } - return *v, true -} - -// OldGroupID returns the old "group_id" field's value of the LinGroupPermission entity. -// If the LinGroupPermission 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 *LinGroupPermissionMutation) OldGroupID(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldGroupID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldGroupID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldGroupID: %w", err) - } - return oldValue.GroupID, nil -} - -// AddGroupID adds i to the "group_id" field. -func (m *LinGroupPermissionMutation) AddGroupID(i int) { - if m.addgroup_id != nil { - *m.addgroup_id += i - } else { - m.addgroup_id = &i - } -} - -// AddedGroupID returns the value that was added to the "group_id" field in this mutation. -func (m *LinGroupPermissionMutation) AddedGroupID() (r int, exists bool) { - v := m.addgroup_id - if v == nil { - return - } - return *v, true -} - -// ResetGroupID resets all changes to the "group_id" field. -func (m *LinGroupPermissionMutation) ResetGroupID() { - m.group_id = nil - m.addgroup_id = nil -} - -// SetPermissionID sets the "permission_id" field. -func (m *LinGroupPermissionMutation) SetPermissionID(i int) { - m.permission_id = &i - m.addpermission_id = nil -} - -// PermissionID returns the value of the "permission_id" field in the mutation. -func (m *LinGroupPermissionMutation) PermissionID() (r int, exists bool) { - v := m.permission_id - if v == nil { - return - } - return *v, true -} - -// OldPermissionID returns the old "permission_id" field's value of the LinGroupPermission entity. -// If the LinGroupPermission 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 *LinGroupPermissionMutation) OldPermissionID(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldPermissionID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldPermissionID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPermissionID: %w", err) - } - return oldValue.PermissionID, nil -} - -// AddPermissionID adds i to the "permission_id" field. -func (m *LinGroupPermissionMutation) AddPermissionID(i int) { - if m.addpermission_id != nil { - *m.addpermission_id += i - } else { - m.addpermission_id = &i - } -} - -// AddedPermissionID returns the value that was added to the "permission_id" field in this mutation. -func (m *LinGroupPermissionMutation) AddedPermissionID() (r int, exists bool) { - v := m.addpermission_id - if v == nil { - return - } - return *v, true -} - -// ResetPermissionID resets all changes to the "permission_id" field. -func (m *LinGroupPermissionMutation) ResetPermissionID() { - m.permission_id = nil - m.addpermission_id = nil -} - -// Where appends a list predicates to the LinGroupPermissionMutation builder. -func (m *LinGroupPermissionMutation) Where(ps ...predicate.LinGroupPermission) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinGroupPermissionMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinGroupPermission). -func (m *LinGroupPermissionMutation) 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 *LinGroupPermissionMutation) Fields() []string { - fields := make([]string, 0, 2) - if m.group_id != nil { - fields = append(fields, lingrouppermission.FieldGroupID) - } - if m.permission_id != nil { - fields = append(fields, lingrouppermission.FieldPermissionID) - } - 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 *LinGroupPermissionMutation) Field(name string) (ent.Value, bool) { - switch name { - case lingrouppermission.FieldGroupID: - return m.GroupID() - case lingrouppermission.FieldPermissionID: - return m.PermissionID() - } - 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 *LinGroupPermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case lingrouppermission.FieldGroupID: - return m.OldGroupID(ctx) - case lingrouppermission.FieldPermissionID: - return m.OldPermissionID(ctx) - } - return nil, fmt.Errorf("unknown LinGroupPermission 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 *LinGroupPermissionMutation) SetField(name string, value ent.Value) error { - switch name { - case lingrouppermission.FieldGroupID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetGroupID(v) - return nil - case lingrouppermission.FieldPermissionID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPermissionID(v) - return nil - } - return fmt.Errorf("unknown LinGroupPermission field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinGroupPermissionMutation) AddedFields() []string { - var fields []string - if m.addgroup_id != nil { - fields = append(fields, lingrouppermission.FieldGroupID) - } - if m.addpermission_id != nil { - fields = append(fields, lingrouppermission.FieldPermissionID) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *LinGroupPermissionMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case lingrouppermission.FieldGroupID: - return m.AddedGroupID() - case lingrouppermission.FieldPermissionID: - return m.AddedPermissionID() - } - 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 *LinGroupPermissionMutation) AddField(name string, value ent.Value) error { - switch name { - case lingrouppermission.FieldGroupID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddGroupID(v) - return nil - case lingrouppermission.FieldPermissionID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddPermissionID(v) - return nil - } - return fmt.Errorf("unknown LinGroupPermission numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinGroupPermissionMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinGroupPermissionMutation) 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 *LinGroupPermissionMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinGroupPermission 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 *LinGroupPermissionMutation) ResetField(name string) error { - switch name { - case lingrouppermission.FieldGroupID: - m.ResetGroupID() - return nil - case lingrouppermission.FieldPermissionID: - m.ResetPermissionID() - return nil - } - return fmt.Errorf("unknown LinGroupPermission field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinGroupPermissionMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinGroupPermissionMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinGroupPermissionMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinGroupPermissionMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinGroupPermissionMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinGroupPermissionMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *LinGroupPermissionMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown LinGroupPermission 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 *LinGroupPermissionMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown LinGroupPermission edge %s", name) -} - -// LinLogMutation represents an operation that mutates the LinLog nodes in the graph. -type LinLogMutation struct { - config - op Op - typ string - id *int - create_time *time.Time - update_time *time.Time - delete_time *time.Time - message *string - user_id *int - adduser_id *int - username *string - status_code *int - addstatus_code *int - method *string - _path *string - permission *string - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*LinLog, error) - predicates []predicate.LinLog -} - -var _ ent.Mutation = (*LinLogMutation)(nil) - -// linlogOption allows management of the mutation configuration using functional options. -type linlogOption func(*LinLogMutation) - -// newLinLogMutation creates new mutation for the LinLog entity. -func newLinLogMutation(c config, op Op, opts ...linlogOption) *LinLogMutation { - m := &LinLogMutation{ - config: c, - op: op, - typ: TypeLinLog, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinLogID sets the ID field of the mutation. -func withLinLogID(id int) linlogOption { - return func(m *LinLogMutation) { - var ( - err error - once sync.Once - value *LinLog - ) - m.oldValue = func(ctx context.Context) (*LinLog, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinLog.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinLog sets the old LinLog of the mutation. -func withLinLog(node *LinLog) linlogOption { - return func(m *LinLogMutation) { - m.oldValue = func(context.Context) (*LinLog, 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 LinLogMutation) 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 LinLogMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinLogMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetCreateTime sets the "create_time" field. -func (m *LinLogMutation) SetCreateTime(t time.Time) { - m.create_time = &t -} - -// CreateTime returns the value of the "create_time" field in the mutation. -func (m *LinLogMutation) CreateTime() (r time.Time, exists bool) { - v := m.create_time - if v == nil { - return - } - return *v, true -} - -// OldCreateTime returns the old "create_time" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) - } - return oldValue.CreateTime, nil -} - -// ResetCreateTime resets all changes to the "create_time" field. -func (m *LinLogMutation) ResetCreateTime() { - m.create_time = nil -} - -// SetUpdateTime sets the "update_time" field. -func (m *LinLogMutation) SetUpdateTime(t time.Time) { - m.update_time = &t -} - -// UpdateTime returns the value of the "update_time" field in the mutation. -func (m *LinLogMutation) UpdateTime() (r time.Time, exists bool) { - v := m.update_time - if v == nil { - return - } - return *v, true -} - -// OldUpdateTime returns the old "update_time" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) - } - return oldValue.UpdateTime, nil -} - -// ResetUpdateTime resets all changes to the "update_time" field. -func (m *LinLogMutation) ResetUpdateTime() { - m.update_time = nil -} - -// SetDeleteTime sets the "delete_time" field. -func (m *LinLogMutation) SetDeleteTime(t time.Time) { - m.delete_time = &t -} - -// DeleteTime returns the value of the "delete_time" field in the mutation. -func (m *LinLogMutation) DeleteTime() (r time.Time, exists bool) { - v := m.delete_time - if v == nil { - return - } - return *v, true -} - -// OldDeleteTime returns the old "delete_time" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) - } - return oldValue.DeleteTime, nil -} - -// ResetDeleteTime resets all changes to the "delete_time" field. -func (m *LinLogMutation) ResetDeleteTime() { - m.delete_time = nil -} - -// SetMessage sets the "message" field. -func (m *LinLogMutation) SetMessage(s string) { - m.message = &s -} - -// Message returns the value of the "message" field in the mutation. -func (m *LinLogMutation) Message() (r string, exists bool) { - v := m.message - if v == nil { - return - } - return *v, true -} - -// OldMessage returns the old "message" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldMessage(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMessage is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMessage requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMessage: %w", err) - } - return oldValue.Message, nil -} - -// ResetMessage resets all changes to the "message" field. -func (m *LinLogMutation) ResetMessage() { - m.message = nil -} - -// SetUserID sets the "user_id" field. -func (m *LinLogMutation) SetUserID(i int) { - m.user_id = &i - m.adduser_id = nil -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *LinLogMutation) UserID() (r int, exists bool) { - v := m.user_id - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldUserID(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("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 -} - -// AddUserID adds i to the "user_id" field. -func (m *LinLogMutation) AddUserID(i int) { - if m.adduser_id != nil { - *m.adduser_id += i - } else { - m.adduser_id = &i - } -} - -// AddedUserID returns the value that was added to the "user_id" field in this mutation. -func (m *LinLogMutation) AddedUserID() (r int, exists bool) { - v := m.adduser_id - if v == nil { - return - } - return *v, true -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *LinLogMutation) ResetUserID() { - m.user_id = nil - m.adduser_id = nil -} - -// SetUsername sets the "username" field. -func (m *LinLogMutation) SetUsername(s string) { - m.username = &s -} - -// Username returns the value of the "username" field in the mutation. -func (m *LinLogMutation) Username() (r string, exists bool) { - v := m.username - if v == nil { - return - } - return *v, true -} - -// OldUsername returns the old "username" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldUsername(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUsername is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldUsername requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUsername: %w", err) - } - return oldValue.Username, nil -} - -// ResetUsername resets all changes to the "username" field. -func (m *LinLogMutation) ResetUsername() { - m.username = nil -} - -// SetStatusCode sets the "status_code" field. -func (m *LinLogMutation) SetStatusCode(i int) { - m.status_code = &i - m.addstatus_code = nil -} - -// StatusCode returns the value of the "status_code" field in the mutation. -func (m *LinLogMutation) StatusCode() (r int, exists bool) { - v := m.status_code - if v == nil { - return - } - return *v, true -} - -// OldStatusCode returns the old "status_code" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldStatusCode(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldStatusCode is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldStatusCode requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStatusCode: %w", err) - } - return oldValue.StatusCode, nil -} - -// AddStatusCode adds i to the "status_code" field. -func (m *LinLogMutation) AddStatusCode(i int) { - if m.addstatus_code != nil { - *m.addstatus_code += i - } else { - m.addstatus_code = &i - } -} - -// AddedStatusCode returns the value that was added to the "status_code" field in this mutation. -func (m *LinLogMutation) AddedStatusCode() (r int, exists bool) { - v := m.addstatus_code - if v == nil { - return - } - return *v, true -} - -// ResetStatusCode resets all changes to the "status_code" field. -func (m *LinLogMutation) ResetStatusCode() { - m.status_code = nil - m.addstatus_code = nil -} - -// SetMethod sets the "method" field. -func (m *LinLogMutation) SetMethod(s string) { - m.method = &s -} - -// Method returns the value of the "method" field in the mutation. -func (m *LinLogMutation) Method() (r string, exists bool) { - v := m.method - if v == nil { - return - } - return *v, true -} - -// OldMethod returns the old "method" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldMethod(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMethod is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMethod requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMethod: %w", err) - } - return oldValue.Method, nil -} - -// ResetMethod resets all changes to the "method" field. -func (m *LinLogMutation) ResetMethod() { - m.method = nil -} - -// SetPath sets the "path" field. -func (m *LinLogMutation) SetPath(s string) { - m._path = &s -} - -// Path returns the value of the "path" field in the mutation. -func (m *LinLogMutation) Path() (r string, exists bool) { - v := m._path - if v == nil { - return - } - return *v, true -} - -// OldPath returns the old "path" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldPath(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldPath is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldPath requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPath: %w", err) - } - return oldValue.Path, nil -} - -// ResetPath resets all changes to the "path" field. -func (m *LinLogMutation) ResetPath() { - m._path = nil -} - -// SetPermission sets the "permission" field. -func (m *LinLogMutation) SetPermission(s string) { - m.permission = &s -} - -// Permission returns the value of the "permission" field in the mutation. -func (m *LinLogMutation) Permission() (r string, exists bool) { - v := m.permission - if v == nil { - return - } - return *v, true -} - -// OldPermission returns the old "permission" field's value of the LinLog entity. -// If the LinLog 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 *LinLogMutation) OldPermission(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldPermission is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldPermission requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPermission: %w", err) - } - return oldValue.Permission, nil -} - -// ResetPermission resets all changes to the "permission" field. -func (m *LinLogMutation) ResetPermission() { - m.permission = nil -} - -// Where appends a list predicates to the LinLogMutation builder. -func (m *LinLogMutation) Where(ps ...predicate.LinLog) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinLogMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinLog). -func (m *LinLogMutation) 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 *LinLogMutation) Fields() []string { - fields := make([]string, 0, 10) - if m.create_time != nil { - fields = append(fields, linlog.FieldCreateTime) - } - if m.update_time != nil { - fields = append(fields, linlog.FieldUpdateTime) - } - if m.delete_time != nil { - fields = append(fields, linlog.FieldDeleteTime) - } - if m.message != nil { - fields = append(fields, linlog.FieldMessage) - } - if m.user_id != nil { - fields = append(fields, linlog.FieldUserID) - } - if m.username != nil { - fields = append(fields, linlog.FieldUsername) - } - if m.status_code != nil { - fields = append(fields, linlog.FieldStatusCode) - } - if m.method != nil { - fields = append(fields, linlog.FieldMethod) - } - if m._path != nil { - fields = append(fields, linlog.FieldPath) - } - if m.permission != nil { - fields = append(fields, linlog.FieldPermission) - } - 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 *LinLogMutation) Field(name string) (ent.Value, bool) { - switch name { - case linlog.FieldCreateTime: - return m.CreateTime() - case linlog.FieldUpdateTime: - return m.UpdateTime() - case linlog.FieldDeleteTime: - return m.DeleteTime() - case linlog.FieldMessage: - return m.Message() - case linlog.FieldUserID: - return m.UserID() - case linlog.FieldUsername: - return m.Username() - case linlog.FieldStatusCode: - return m.StatusCode() - case linlog.FieldMethod: - return m.Method() - case linlog.FieldPath: - return m.Path() - case linlog.FieldPermission: - return m.Permission() - } - 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 *LinLogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case linlog.FieldCreateTime: - return m.OldCreateTime(ctx) - case linlog.FieldUpdateTime: - return m.OldUpdateTime(ctx) - case linlog.FieldDeleteTime: - return m.OldDeleteTime(ctx) - case linlog.FieldMessage: - return m.OldMessage(ctx) - case linlog.FieldUserID: - return m.OldUserID(ctx) - case linlog.FieldUsername: - return m.OldUsername(ctx) - case linlog.FieldStatusCode: - return m.OldStatusCode(ctx) - case linlog.FieldMethod: - return m.OldMethod(ctx) - case linlog.FieldPath: - return m.OldPath(ctx) - case linlog.FieldPermission: - return m.OldPermission(ctx) - } - return nil, fmt.Errorf("unknown LinLog 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 *LinLogMutation) SetField(name string, value ent.Value) error { - switch name { - case linlog.FieldCreateTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreateTime(v) - return nil - case linlog.FieldUpdateTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdateTime(v) - return nil - case linlog.FieldDeleteTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeleteTime(v) - return nil - case linlog.FieldMessage: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMessage(v) - return nil - case linlog.FieldUserID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case linlog.FieldUsername: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUsername(v) - return nil - case linlog.FieldStatusCode: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatusCode(v) - return nil - case linlog.FieldMethod: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMethod(v) - return nil - case linlog.FieldPath: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPath(v) - return nil - case linlog.FieldPermission: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPermission(v) - return nil - } - return fmt.Errorf("unknown LinLog field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinLogMutation) AddedFields() []string { - var fields []string - if m.adduser_id != nil { - fields = append(fields, linlog.FieldUserID) - } - if m.addstatus_code != nil { - fields = append(fields, linlog.FieldStatusCode) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *LinLogMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case linlog.FieldUserID: - return m.AddedUserID() - case linlog.FieldStatusCode: - return m.AddedStatusCode() - } - 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 *LinLogMutation) AddField(name string, value ent.Value) error { - switch name { - case linlog.FieldUserID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddUserID(v) - return nil - case linlog.FieldStatusCode: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddStatusCode(v) - return nil - } - return fmt.Errorf("unknown LinLog numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinLogMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinLogMutation) 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 *LinLogMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinLog 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 *LinLogMutation) ResetField(name string) error { - switch name { - case linlog.FieldCreateTime: - m.ResetCreateTime() - return nil - case linlog.FieldUpdateTime: - m.ResetUpdateTime() - return nil - case linlog.FieldDeleteTime: - m.ResetDeleteTime() - return nil - case linlog.FieldMessage: - m.ResetMessage() - return nil - case linlog.FieldUserID: - m.ResetUserID() - return nil - case linlog.FieldUsername: - m.ResetUsername() - return nil - case linlog.FieldStatusCode: - m.ResetStatusCode() - return nil - case linlog.FieldMethod: - m.ResetMethod() - return nil - case linlog.FieldPath: - m.ResetPath() - return nil - case linlog.FieldPermission: - m.ResetPermission() - return nil - } - return fmt.Errorf("unknown LinLog field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinLogMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinLogMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinLogMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinLogMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinLogMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinLogMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *LinLogMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown LinLog 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 *LinLogMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown LinLog edge %s", name) -} - -// LinPermissionMutation represents an operation that mutates the LinPermission nodes in the graph. -type LinPermissionMutation struct { - config - op Op - typ string - id *int - name *string - module *string - mount *int8 - addmount *int8 - clearedFields map[string]struct{} - lin_group map[int]struct{} - removedlin_group map[int]struct{} - clearedlin_group bool - done bool - oldValue func(context.Context) (*LinPermission, error) - predicates []predicate.LinPermission -} - -var _ ent.Mutation = (*LinPermissionMutation)(nil) - -// linpermissionOption allows management of the mutation configuration using functional options. -type linpermissionOption func(*LinPermissionMutation) - -// newLinPermissionMutation creates new mutation for the LinPermission entity. -func newLinPermissionMutation(c config, op Op, opts ...linpermissionOption) *LinPermissionMutation { - m := &LinPermissionMutation{ - config: c, - op: op, - typ: TypeLinPermission, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinPermissionID sets the ID field of the mutation. -func withLinPermissionID(id int) linpermissionOption { - return func(m *LinPermissionMutation) { - var ( - err error - once sync.Once - value *LinPermission - ) - m.oldValue = func(ctx context.Context) (*LinPermission, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinPermission.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinPermission sets the old LinPermission of the mutation. -func withLinPermission(node *LinPermission) linpermissionOption { - return func(m *LinPermissionMutation) { - m.oldValue = func(context.Context) (*LinPermission, 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 LinPermissionMutation) 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 LinPermissionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinPermissionMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetName sets the "name" field. -func (m *LinPermissionMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *LinPermissionMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true -} - -// OldName returns the old "name" field's value of the LinPermission entity. -// If the LinPermission 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 *LinPermissionMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) - } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *LinPermissionMutation) ResetName() { - m.name = nil -} - -// SetModule sets the "module" field. -func (m *LinPermissionMutation) SetModule(s string) { - m.module = &s -} - -// Module returns the value of the "module" field in the mutation. -func (m *LinPermissionMutation) Module() (r string, exists bool) { - v := m.module - if v == nil { - return - } - return *v, true -} - -// OldModule returns the old "module" field's value of the LinPermission entity. -// If the LinPermission 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 *LinPermissionMutation) OldModule(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldModule is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldModule requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModule: %w", err) - } - return oldValue.Module, nil -} - -// ResetModule resets all changes to the "module" field. -func (m *LinPermissionMutation) ResetModule() { - m.module = nil -} - -// SetMount sets the "mount" field. -func (m *LinPermissionMutation) SetMount(i int8) { - m.mount = &i - m.addmount = nil -} - -// Mount returns the value of the "mount" field in the mutation. -func (m *LinPermissionMutation) Mount() (r int8, exists bool) { - v := m.mount - if v == nil { - return - } - return *v, true -} - -// OldMount returns the old "mount" field's value of the LinPermission entity. -// If the LinPermission 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 *LinPermissionMutation) OldMount(ctx context.Context) (v int8, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMount is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMount requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMount: %w", err) - } - return oldValue.Mount, nil -} - -// AddMount adds i to the "mount" field. -func (m *LinPermissionMutation) AddMount(i int8) { - if m.addmount != nil { - *m.addmount += i - } else { - m.addmount = &i - } -} - -// AddedMount returns the value that was added to the "mount" field in this mutation. -func (m *LinPermissionMutation) AddedMount() (r int8, exists bool) { - v := m.addmount - if v == nil { - return - } - return *v, true -} - -// ResetMount resets all changes to the "mount" field. -func (m *LinPermissionMutation) ResetMount() { - m.mount = nil - m.addmount = nil -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by ids. -func (m *LinPermissionMutation) AddLinGroupIDs(ids ...int) { - if m.lin_group == nil { - m.lin_group = make(map[int]struct{}) - } - for i := range ids { - m.lin_group[ids[i]] = struct{}{} - } -} - -// ClearLinGroup clears the "lin_group" edge to the LinGroup entity. -func (m *LinPermissionMutation) ClearLinGroup() { - m.clearedlin_group = true -} - -// LinGroupCleared reports if the "lin_group" edge to the LinGroup entity was cleared. -func (m *LinPermissionMutation) LinGroupCleared() bool { - return m.clearedlin_group -} - -// RemoveLinGroupIDs removes the "lin_group" edge to the LinGroup entity by IDs. -func (m *LinPermissionMutation) RemoveLinGroupIDs(ids ...int) { - if m.removedlin_group == nil { - m.removedlin_group = make(map[int]struct{}) - } - for i := range ids { - delete(m.lin_group, ids[i]) - m.removedlin_group[ids[i]] = struct{}{} - } -} - -// RemovedLinGroup returns the removed IDs of the "lin_group" edge to the LinGroup entity. -func (m *LinPermissionMutation) RemovedLinGroupIDs() (ids []int) { - for id := range m.removedlin_group { - ids = append(ids, id) - } - return -} - -// LinGroupIDs returns the "lin_group" edge IDs in the mutation. -func (m *LinPermissionMutation) LinGroupIDs() (ids []int) { - for id := range m.lin_group { - ids = append(ids, id) - } - return -} - -// ResetLinGroup resets all changes to the "lin_group" edge. -func (m *LinPermissionMutation) ResetLinGroup() { - m.lin_group = nil - m.clearedlin_group = false - m.removedlin_group = nil -} - -// Where appends a list predicates to the LinPermissionMutation builder. -func (m *LinPermissionMutation) Where(ps ...predicate.LinPermission) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinPermissionMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinPermission). -func (m *LinPermissionMutation) 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 *LinPermissionMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.name != nil { - fields = append(fields, linpermission.FieldName) - } - if m.module != nil { - fields = append(fields, linpermission.FieldModule) - } - if m.mount != nil { - fields = append(fields, linpermission.FieldMount) - } - 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 *LinPermissionMutation) Field(name string) (ent.Value, bool) { - switch name { - case linpermission.FieldName: - return m.Name() - case linpermission.FieldModule: - return m.Module() - case linpermission.FieldMount: - return m.Mount() - } - 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 *LinPermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case linpermission.FieldName: - return m.OldName(ctx) - case linpermission.FieldModule: - return m.OldModule(ctx) - case linpermission.FieldMount: - return m.OldMount(ctx) - } - return nil, fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) SetField(name string, value ent.Value) error { - switch name { - case linpermission.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case linpermission.FieldModule: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModule(v) - return nil - case linpermission.FieldMount: - v, ok := value.(int8) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMount(v) - return nil - } - return fmt.Errorf("unknown LinPermission field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinPermissionMutation) AddedFields() []string { - var fields []string - if m.addmount != nil { - fields = append(fields, linpermission.FieldMount) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *LinPermissionMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case linpermission.FieldMount: - return m.AddedMount() - } - 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 *LinPermissionMutation) AddField(name string, value ent.Value) error { - switch name { - case linpermission.FieldMount: - v, ok := value.(int8) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMount(v) - return nil - } - return fmt.Errorf("unknown LinPermission numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinPermissionMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinPermissionMutation) 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 *LinPermissionMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) ResetField(name string) error { - switch name { - case linpermission.FieldName: - m.ResetName() - return nil - case linpermission.FieldModule: - m.ResetModule() - return nil - case linpermission.FieldMount: - m.ResetMount() - return nil - } - return fmt.Errorf("unknown LinPermission field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinPermissionMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.lin_group != nil { - edges = append(edges, linpermission.EdgeLinGroup) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinPermissionMutation) AddedIDs(name string) []ent.Value { - switch name { - case linpermission.EdgeLinGroup: - ids := make([]ent.Value, 0, len(m.lin_group)) - for id := range m.lin_group { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinPermissionMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removedlin_group != nil { - edges = append(edges, linpermission.EdgeLinGroup) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinPermissionMutation) RemovedIDs(name string) []ent.Value { - switch name { - case linpermission.EdgeLinGroup: - ids := make([]ent.Value, 0, len(m.removedlin_group)) - for id := range m.removedlin_group { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinPermissionMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedlin_group { - edges = append(edges, linpermission.EdgeLinGroup) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinPermissionMutation) EdgeCleared(name string) bool { - switch name { - case linpermission.EdgeLinGroup: - return m.clearedlin_group - } - 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 *LinPermissionMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) ResetEdge(name string) error { - switch name { - case linpermission.EdgeLinGroup: - m.ResetLinGroup() - return nil - } - return fmt.Errorf("unknown LinPermission edge %s", name) -} - -// LinUserMutation represents an operation that mutates the LinUser nodes in the graph. -type LinUserMutation struct { - config - op Op - typ string - id *int - create_time *time.Time - update_time *time.Time - delete_time *time.Time - username *string - nickname *string - avatar *string - email *string - clearedFields map[string]struct{} - lin_user_identiy map[int]struct{} - removedlin_user_identiy map[int]struct{} - clearedlin_user_identiy bool - lin_group map[int]struct{} - removedlin_group map[int]struct{} - clearedlin_group bool - done bool - oldValue func(context.Context) (*LinUser, error) - predicates []predicate.LinUser -} - -var _ ent.Mutation = (*LinUserMutation)(nil) - -// linuserOption allows management of the mutation configuration using functional options. -type linuserOption func(*LinUserMutation) - -// newLinUserMutation creates new mutation for the LinUser entity. -func newLinUserMutation(c config, op Op, opts ...linuserOption) *LinUserMutation { - m := &LinUserMutation{ - config: c, - op: op, - typ: TypeLinUser, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinUserID sets the ID field of the mutation. -func withLinUserID(id int) linuserOption { - return func(m *LinUserMutation) { - var ( - err error - once sync.Once - value *LinUser - ) - m.oldValue = func(ctx context.Context) (*LinUser, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinUser.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinUser sets the old LinUser of the mutation. -func withLinUser(node *LinUser) linuserOption { - return func(m *LinUserMutation) { - m.oldValue = func(context.Context) (*LinUser, 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 LinUserMutation) 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 LinUserMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinUserMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetCreateTime sets the "create_time" field. -func (m *LinUserMutation) SetCreateTime(t time.Time) { - m.create_time = &t -} - -// CreateTime returns the value of the "create_time" field in the mutation. -func (m *LinUserMutation) CreateTime() (r time.Time, exists bool) { - v := m.create_time - if v == nil { - return - } - return *v, true -} - -// OldCreateTime returns the old "create_time" field's value of the LinUser entity. -// If the LinUser 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 *LinUserMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) - } - return oldValue.CreateTime, nil -} - -// ResetCreateTime resets all changes to the "create_time" field. -func (m *LinUserMutation) ResetCreateTime() { - m.create_time = nil -} - -// SetUpdateTime sets the "update_time" field. -func (m *LinUserMutation) SetUpdateTime(t time.Time) { - m.update_time = &t -} - -// UpdateTime returns the value of the "update_time" field in the mutation. -func (m *LinUserMutation) UpdateTime() (r time.Time, exists bool) { - v := m.update_time - if v == nil { - return - } - return *v, true -} - -// OldUpdateTime returns the old "update_time" field's value of the LinUser entity. -// If the LinUser 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 *LinUserMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) - } - return oldValue.UpdateTime, nil -} - -// ResetUpdateTime resets all changes to the "update_time" field. -func (m *LinUserMutation) ResetUpdateTime() { - m.update_time = nil -} - -// SetDeleteTime sets the "delete_time" field. -func (m *LinUserMutation) SetDeleteTime(t time.Time) { - m.delete_time = &t -} - -// DeleteTime returns the value of the "delete_time" field in the mutation. -func (m *LinUserMutation) DeleteTime() (r time.Time, exists bool) { - v := m.delete_time - if v == nil { - return - } - return *v, true -} - -// OldDeleteTime returns the old "delete_time" field's value of the LinUser entity. -// If the LinUser 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 *LinUserMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) - } - return oldValue.DeleteTime, nil -} - -// ResetDeleteTime resets all changes to the "delete_time" field. -func (m *LinUserMutation) ResetDeleteTime() { - m.delete_time = nil -} - -// SetUsername sets the "username" field. -func (m *LinUserMutation) SetUsername(s string) { - m.username = &s -} - -// Username returns the value of the "username" field in the mutation. -func (m *LinUserMutation) Username() (r string, exists bool) { - v := m.username - if v == nil { - return - } - return *v, true -} - -// OldUsername returns the old "username" field's value of the LinUser entity. -// If the LinUser 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 *LinUserMutation) OldUsername(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUsername is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldUsername requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUsername: %w", err) - } - return oldValue.Username, nil -} - -// ResetUsername resets all changes to the "username" field. -func (m *LinUserMutation) ResetUsername() { - m.username = nil -} - -// SetNickname sets the "nickname" field. -func (m *LinUserMutation) SetNickname(s string) { - m.nickname = &s -} - -// Nickname returns the value of the "nickname" field in the mutation. -func (m *LinUserMutation) 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 LinUser entity. -// If the LinUser 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 *LinUserMutation) OldNickname(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldNickname is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("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 -} - -// ResetNickname resets all changes to the "nickname" field. -func (m *LinUserMutation) ResetNickname() { - m.nickname = nil -} - -// SetAvatar sets the "avatar" field. -func (m *LinUserMutation) SetAvatar(s string) { - m.avatar = &s -} - -// Avatar returns the value of the "avatar" field in the mutation. -func (m *LinUserMutation) Avatar() (r string, exists bool) { - v := m.avatar - if v == nil { - return - } - return *v, true -} - -// OldAvatar returns the old "avatar" field's value of the LinUser entity. -// If the LinUser 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 *LinUserMutation) OldAvatar(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldAvatar is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldAvatar requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAvatar: %w", err) - } - return oldValue.Avatar, nil -} - -// ResetAvatar resets all changes to the "avatar" field. -func (m *LinUserMutation) ResetAvatar() { - m.avatar = nil -} - -// SetEmail sets the "email" field. -func (m *LinUserMutation) SetEmail(s string) { - m.email = &s -} - -// Email returns the value of the "email" field in the mutation. -func (m *LinUserMutation) 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 LinUser entity. -// If the LinUser 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 *LinUserMutation) OldEmail(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldEmail is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("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 -} - -// ResetEmail resets all changes to the "email" field. -func (m *LinUserMutation) ResetEmail() { - m.email = nil -} - -// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by ids. -func (m *LinUserMutation) AddLinUserIdentiyIDs(ids ...int) { - if m.lin_user_identiy == nil { - m.lin_user_identiy = make(map[int]struct{}) - } - for i := range ids { - m.lin_user_identiy[ids[i]] = struct{}{} - } -} - -// ClearLinUserIdentiy clears the "lin_user_identiy" edge to the LinUserIdentiy entity. -func (m *LinUserMutation) ClearLinUserIdentiy() { - m.clearedlin_user_identiy = true -} - -// LinUserIdentiyCleared reports if the "lin_user_identiy" edge to the LinUserIdentiy entity was cleared. -func (m *LinUserMutation) LinUserIdentiyCleared() bool { - return m.clearedlin_user_identiy -} - -// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. -func (m *LinUserMutation) RemoveLinUserIdentiyIDs(ids ...int) { - if m.removedlin_user_identiy == nil { - m.removedlin_user_identiy = make(map[int]struct{}) - } - for i := range ids { - delete(m.lin_user_identiy, ids[i]) - m.removedlin_user_identiy[ids[i]] = struct{}{} - } -} - -// RemovedLinUserIdentiy returns the removed IDs of the "lin_user_identiy" edge to the LinUserIdentiy entity. -func (m *LinUserMutation) RemovedLinUserIdentiyIDs() (ids []int) { - for id := range m.removedlin_user_identiy { - ids = append(ids, id) - } - return -} - -// LinUserIdentiyIDs returns the "lin_user_identiy" edge IDs in the mutation. -func (m *LinUserMutation) LinUserIdentiyIDs() (ids []int) { - for id := range m.lin_user_identiy { - ids = append(ids, id) - } - return -} - -// ResetLinUserIdentiy resets all changes to the "lin_user_identiy" edge. -func (m *LinUserMutation) ResetLinUserIdentiy() { - m.lin_user_identiy = nil - m.clearedlin_user_identiy = false - m.removedlin_user_identiy = nil -} - -// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by ids. -func (m *LinUserMutation) AddLinGroupIDs(ids ...int) { - if m.lin_group == nil { - m.lin_group = make(map[int]struct{}) - } - for i := range ids { - m.lin_group[ids[i]] = struct{}{} - } -} - -// ClearLinGroup clears the "lin_group" edge to the LinGroup entity. -func (m *LinUserMutation) ClearLinGroup() { - m.clearedlin_group = true -} - -// LinGroupCleared reports if the "lin_group" edge to the LinGroup entity was cleared. -func (m *LinUserMutation) LinGroupCleared() bool { - return m.clearedlin_group -} - -// RemoveLinGroupIDs removes the "lin_group" edge to the LinGroup entity by IDs. -func (m *LinUserMutation) RemoveLinGroupIDs(ids ...int) { - if m.removedlin_group == nil { - m.removedlin_group = make(map[int]struct{}) - } - for i := range ids { - delete(m.lin_group, ids[i]) - m.removedlin_group[ids[i]] = struct{}{} - } -} - -// RemovedLinGroup returns the removed IDs of the "lin_group" edge to the LinGroup entity. -func (m *LinUserMutation) RemovedLinGroupIDs() (ids []int) { - for id := range m.removedlin_group { - ids = append(ids, id) - } - return -} - -// LinGroupIDs returns the "lin_group" edge IDs in the mutation. -func (m *LinUserMutation) LinGroupIDs() (ids []int) { - for id := range m.lin_group { - ids = append(ids, id) - } - return -} - -// ResetLinGroup resets all changes to the "lin_group" edge. -func (m *LinUserMutation) ResetLinGroup() { - m.lin_group = nil - m.clearedlin_group = false - m.removedlin_group = nil -} - -// Where appends a list predicates to the LinUserMutation builder. -func (m *LinUserMutation) Where(ps ...predicate.LinUser) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinUserMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinUser). -func (m *LinUserMutation) 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 *LinUserMutation) Fields() []string { - fields := make([]string, 0, 7) - if m.create_time != nil { - fields = append(fields, linuser.FieldCreateTime) - } - if m.update_time != nil { - fields = append(fields, linuser.FieldUpdateTime) - } - if m.delete_time != nil { - fields = append(fields, linuser.FieldDeleteTime) - } - if m.username != nil { - fields = append(fields, linuser.FieldUsername) - } - if m.nickname != nil { - fields = append(fields, linuser.FieldNickname) - } - if m.avatar != nil { - fields = append(fields, linuser.FieldAvatar) - } - if m.email != nil { - fields = append(fields, linuser.FieldEmail) - } - 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 *LinUserMutation) Field(name string) (ent.Value, bool) { - switch name { - case linuser.FieldCreateTime: - return m.CreateTime() - case linuser.FieldUpdateTime: - return m.UpdateTime() - case linuser.FieldDeleteTime: - return m.DeleteTime() - case linuser.FieldUsername: - return m.Username() - case linuser.FieldNickname: - return m.Nickname() - case linuser.FieldAvatar: - return m.Avatar() - case linuser.FieldEmail: - return m.Email() - } - 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 *LinUserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case linuser.FieldCreateTime: - return m.OldCreateTime(ctx) - case linuser.FieldUpdateTime: - return m.OldUpdateTime(ctx) - case linuser.FieldDeleteTime: - return m.OldDeleteTime(ctx) - case linuser.FieldUsername: - return m.OldUsername(ctx) - case linuser.FieldNickname: - return m.OldNickname(ctx) - case linuser.FieldAvatar: - return m.OldAvatar(ctx) - case linuser.FieldEmail: - return m.OldEmail(ctx) - } - return nil, fmt.Errorf("unknown LinUser 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 *LinUserMutation) SetField(name string, value ent.Value) error { - switch name { - case linuser.FieldCreateTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreateTime(v) - return nil - case linuser.FieldUpdateTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdateTime(v) - return nil - case linuser.FieldDeleteTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeleteTime(v) - return nil - case linuser.FieldUsername: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUsername(v) - return nil - case linuser.FieldNickname: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetNickname(v) - return nil - case linuser.FieldAvatar: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAvatar(v) - return nil - case linuser.FieldEmail: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmail(v) - return nil - } - return fmt.Errorf("unknown LinUser field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinUserMutation) 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 *LinUserMutation) 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 *LinUserMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown LinUser numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinUserMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinUserMutation) 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 *LinUserMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinUser 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 *LinUserMutation) ResetField(name string) error { - switch name { - case linuser.FieldCreateTime: - m.ResetCreateTime() - return nil - case linuser.FieldUpdateTime: - m.ResetUpdateTime() - return nil - case linuser.FieldDeleteTime: - m.ResetDeleteTime() - return nil - case linuser.FieldUsername: - m.ResetUsername() - return nil - case linuser.FieldNickname: - m.ResetNickname() - return nil - case linuser.FieldAvatar: - m.ResetAvatar() - return nil - case linuser.FieldEmail: - m.ResetEmail() - return nil - } - return fmt.Errorf("unknown LinUser field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinUserMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.lin_user_identiy != nil { - edges = append(edges, linuser.EdgeLinUserIdentiy) - } - if m.lin_group != nil { - edges = append(edges, linuser.EdgeLinGroup) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinUserMutation) AddedIDs(name string) []ent.Value { - switch name { - case linuser.EdgeLinUserIdentiy: - ids := make([]ent.Value, 0, len(m.lin_user_identiy)) - for id := range m.lin_user_identiy { - ids = append(ids, id) - } - return ids - case linuser.EdgeLinGroup: - ids := make([]ent.Value, 0, len(m.lin_group)) - for id := range m.lin_group { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinUserMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - if m.removedlin_user_identiy != nil { - edges = append(edges, linuser.EdgeLinUserIdentiy) - } - if m.removedlin_group != nil { - edges = append(edges, linuser.EdgeLinGroup) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinUserMutation) RemovedIDs(name string) []ent.Value { - switch name { - case linuser.EdgeLinUserIdentiy: - ids := make([]ent.Value, 0, len(m.removedlin_user_identiy)) - for id := range m.removedlin_user_identiy { - ids = append(ids, id) - } - return ids - case linuser.EdgeLinGroup: - ids := make([]ent.Value, 0, len(m.removedlin_group)) - for id := range m.removedlin_group { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinUserMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedlin_user_identiy { - edges = append(edges, linuser.EdgeLinUserIdentiy) - } - if m.clearedlin_group { - edges = append(edges, linuser.EdgeLinGroup) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinUserMutation) EdgeCleared(name string) bool { - switch name { - case linuser.EdgeLinUserIdentiy: - return m.clearedlin_user_identiy - case linuser.EdgeLinGroup: - return m.clearedlin_group - } - 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 *LinUserMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown LinUser 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 *LinUserMutation) ResetEdge(name string) error { - switch name { - case linuser.EdgeLinUserIdentiy: - m.ResetLinUserIdentiy() - return nil - case linuser.EdgeLinGroup: - m.ResetLinGroup() - return nil - } - return fmt.Errorf("unknown LinUser edge %s", name) -} - -// LinUserIdentiyMutation represents an operation that mutates the LinUserIdentiy nodes in the graph. -type LinUserIdentiyMutation struct { - config - op Op - typ string - id *int - user_id *int - adduser_id *int - identity_type *string - identifier *string - credential *string - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*LinUserIdentiy, error) - predicates []predicate.LinUserIdentiy -} - -var _ ent.Mutation = (*LinUserIdentiyMutation)(nil) - -// linuseridentiyOption allows management of the mutation configuration using functional options. -type linuseridentiyOption func(*LinUserIdentiyMutation) - -// newLinUserIdentiyMutation creates new mutation for the LinUserIdentiy entity. -func newLinUserIdentiyMutation(c config, op Op, opts ...linuseridentiyOption) *LinUserIdentiyMutation { - m := &LinUserIdentiyMutation{ - config: c, - op: op, - typ: TypeLinUserIdentiy, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withLinUserIdentiyID sets the ID field of the mutation. -func withLinUserIdentiyID(id int) linuseridentiyOption { - return func(m *LinUserIdentiyMutation) { - var ( - err error - once sync.Once - value *LinUserIdentiy - ) - m.oldValue = func(ctx context.Context) (*LinUserIdentiy, error) { - once.Do(func() { - if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") - } else { - value, err = m.Client().LinUserIdentiy.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withLinUserIdentiy sets the old LinUserIdentiy of the mutation. -func withLinUserIdentiy(node *LinUserIdentiy) linuseridentiyOption { - return func(m *LinUserIdentiyMutation) { - m.oldValue = func(context.Context) (*LinUserIdentiy, 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 LinUserIdentiyMutation) 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 LinUserIdentiyMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("model: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *LinUserIdentiyMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// SetUserID sets the "user_id" field. -func (m *LinUserIdentiyMutation) SetUserID(i int) { - m.user_id = &i - m.adduser_id = nil -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *LinUserIdentiyMutation) UserID() (r int, exists bool) { - v := m.user_id - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the LinUserIdentiy entity. -// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldUserID(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("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 -} - -// AddUserID adds i to the "user_id" field. -func (m *LinUserIdentiyMutation) AddUserID(i int) { - if m.adduser_id != nil { - *m.adduser_id += i - } else { - m.adduser_id = &i - } -} - -// AddedUserID returns the value that was added to the "user_id" field in this mutation. -func (m *LinUserIdentiyMutation) AddedUserID() (r int, exists bool) { - v := m.adduser_id - if v == nil { - return - } - return *v, true -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *LinUserIdentiyMutation) ResetUserID() { - m.user_id = nil - m.adduser_id = nil -} - -// SetIdentityType sets the "identity_type" field. -func (m *LinUserIdentiyMutation) SetIdentityType(s string) { - m.identity_type = &s -} - -// IdentityType returns the value of the "identity_type" field in the mutation. -func (m *LinUserIdentiyMutation) IdentityType() (r string, exists bool) { - v := m.identity_type - if v == nil { - return - } - return *v, true -} - -// OldIdentityType returns the old "identity_type" field's value of the LinUserIdentiy entity. -// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldIdentityType(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldIdentityType is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldIdentityType requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldIdentityType: %w", err) - } - return oldValue.IdentityType, nil -} - -// ResetIdentityType resets all changes to the "identity_type" field. -func (m *LinUserIdentiyMutation) ResetIdentityType() { - m.identity_type = nil -} - -// SetIdentifier sets the "identifier" field. -func (m *LinUserIdentiyMutation) SetIdentifier(s string) { - m.identifier = &s -} - -// Identifier returns the value of the "identifier" field in the mutation. -func (m *LinUserIdentiyMutation) Identifier() (r string, exists bool) { - v := m.identifier - if v == nil { - return - } - return *v, true -} - -// OldIdentifier returns the old "identifier" field's value of the LinUserIdentiy entity. -// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldIdentifier(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldIdentifier is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldIdentifier requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldIdentifier: %w", err) - } - return oldValue.Identifier, nil -} - -// ResetIdentifier resets all changes to the "identifier" field. -func (m *LinUserIdentiyMutation) ResetIdentifier() { - m.identifier = nil -} - -// SetCredential sets the "credential" field. -func (m *LinUserIdentiyMutation) SetCredential(s string) { - m.credential = &s -} - -// Credential returns the value of the "credential" field in the mutation. -func (m *LinUserIdentiyMutation) Credential() (r string, exists bool) { - v := m.credential - if v == nil { - return - } - return *v, true -} - -// OldCredential returns the old "credential" field's value of the LinUserIdentiy entity. -// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldCredential(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldCredential is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldCredential requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCredential: %w", err) - } - return oldValue.Credential, nil -} - -// ResetCredential resets all changes to the "credential" field. -func (m *LinUserIdentiyMutation) ResetCredential() { - m.credential = nil -} - -// Where appends a list predicates to the LinUserIdentiyMutation builder. -func (m *LinUserIdentiyMutation) Where(ps ...predicate.LinUserIdentiy) { - m.predicates = append(m.predicates, ps...) -} - -// Op returns the operation name. -func (m *LinUserIdentiyMutation) Op() Op { - return m.op -} - -// Type returns the node type of this mutation (LinUserIdentiy). -func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) Fields() []string { - fields := make([]string, 0, 4) - if m.user_id != nil { - fields = append(fields, linuseridentiy.FieldUserID) - } - if m.identity_type != nil { - fields = append(fields, linuseridentiy.FieldIdentityType) - } - if m.identifier != nil { - fields = append(fields, linuseridentiy.FieldIdentifier) - } - if m.credential != nil { - fields = append(fields, linuseridentiy.FieldCredential) - } - 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 *LinUserIdentiyMutation) Field(name string) (ent.Value, bool) { - switch name { - case linuseridentiy.FieldUserID: - return m.UserID() - case linuseridentiy.FieldIdentityType: - return m.IdentityType() - case linuseridentiy.FieldIdentifier: - return m.Identifier() - case linuseridentiy.FieldCredential: - return m.Credential() - } - 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 *LinUserIdentiyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case linuseridentiy.FieldUserID: - return m.OldUserID(ctx) - case linuseridentiy.FieldIdentityType: - return m.OldIdentityType(ctx) - case linuseridentiy.FieldIdentifier: - return m.OldIdentifier(ctx) - case linuseridentiy.FieldCredential: - return m.OldCredential(ctx) - } - return nil, fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) SetField(name string, value ent.Value) error { - switch name { - case linuseridentiy.FieldUserID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case linuseridentiy.FieldIdentityType: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIdentityType(v) - return nil - case linuseridentiy.FieldIdentifier: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIdentifier(v) - return nil - case linuseridentiy.FieldCredential: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCredential(v) - return nil - } - return fmt.Errorf("unknown LinUserIdentiy field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *LinUserIdentiyMutation) AddedFields() []string { - var fields []string - if m.adduser_id != nil { - fields = append(fields, linuseridentiy.FieldUserID) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *LinUserIdentiyMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case linuseridentiy.FieldUserID: - return m.AddedUserID() - } - 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 *LinUserIdentiyMutation) AddField(name string, value ent.Value) error { - switch name { - case linuseridentiy.FieldUserID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddUserID(v) - return nil - } - return fmt.Errorf("unknown LinUserIdentiy numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *LinUserIdentiyMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) ClearField(name string) error { - return fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) ResetField(name string) error { - switch name { - case linuseridentiy.FieldUserID: - m.ResetUserID() - return nil - case linuseridentiy.FieldIdentityType: - m.ResetIdentityType() - return nil - case linuseridentiy.FieldIdentifier: - m.ResetIdentifier() - return nil - case linuseridentiy.FieldCredential: - m.ResetCredential() - return nil - } - return fmt.Errorf("unknown LinUserIdentiy field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *LinUserIdentiyMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *LinUserIdentiyMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *LinUserIdentiyMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *LinUserIdentiyMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LinUserIdentiyMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *LinUserIdentiyMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *LinUserIdentiyMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown LinUserIdentiy edge %s", name) -} diff --git a/internal/data/model/predicate/predicate.go b/internal/data/model/predicate/predicate.go deleted file mode 100644 index 4d1fa5e..0000000 --- a/internal/data/model/predicate/predicate.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package predicate - -import ( - "entgo.io/ent/dialect/sql" -) - -// Book is the predicate function for book builders. -type Book func(*sql.Selector) - -// LinFile is the predicate function for linfile builders. -type LinFile func(*sql.Selector) - -// LinGroup is the predicate function for lingroup builders. -type LinGroup func(*sql.Selector) - -// LinGroupPermission is the predicate function for lingrouppermission builders. -type LinGroupPermission func(*sql.Selector) - -// LinLog is the predicate function for linlog builders. -type LinLog func(*sql.Selector) - -// LinPermission is the predicate function for linpermission builders. -type LinPermission func(*sql.Selector) - -// LinUser is the predicate function for linuser builders. -type LinUser func(*sql.Selector) - -// LinUserIdentiy is the predicate function for linuseridentiy builders. -type LinUserIdentiy func(*sql.Selector) diff --git a/internal/data/model/runtime.go b/internal/data/model/runtime.go deleted file mode 100644 index 345205e..0000000 --- a/internal/data/model/runtime.go +++ /dev/null @@ -1,58 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "lin-cms-go/internal/data/ent/schema" - "lin-cms-go/internal/data/model/linlog" - "lin-cms-go/internal/data/model/linuser" - "time" -) - -// The init function reads all schema descriptors with runtime code -// (default values, validators, hooks and policies) and stitches it -// to their package variables. -func init() { - linlogMixin := schema.LinLog{}.Mixin() - linlogMixinFields0 := linlogMixin[0].Fields() - _ = linlogMixinFields0 - linlogFields := schema.LinLog{}.Fields() - _ = linlogFields - // linlogDescCreateTime is the schema descriptor for create_time field. - linlogDescCreateTime := linlogMixinFields0[0].Descriptor() - // linlog.DefaultCreateTime holds the default value on creation for the create_time field. - linlog.DefaultCreateTime = linlogDescCreateTime.Default.(func() time.Time) - // linlogDescUpdateTime is the schema descriptor for update_time field. - linlogDescUpdateTime := linlogMixinFields0[1].Descriptor() - // linlog.DefaultUpdateTime holds the default value on creation for the update_time field. - linlog.DefaultUpdateTime = linlogDescUpdateTime.Default.(func() time.Time) - // linlog.UpdateDefaultUpdateTime holds the default value on update for the update_time field. - linlog.UpdateDefaultUpdateTime = linlogDescUpdateTime.UpdateDefault.(func() time.Time) - // linlogDescDeleteTime is the schema descriptor for delete_time field. - linlogDescDeleteTime := linlogMixinFields0[2].Descriptor() - // linlog.DefaultDeleteTime holds the default value on creation for the delete_time field. - linlog.DefaultDeleteTime = linlogDescDeleteTime.Default.(func() time.Time) - linuserMixin := schema.LinUser{}.Mixin() - linuserMixinFields0 := linuserMixin[0].Fields() - _ = linuserMixinFields0 - linuserFields := schema.LinUser{}.Fields() - _ = linuserFields - // linuserDescCreateTime is the schema descriptor for create_time field. - linuserDescCreateTime := linuserMixinFields0[0].Descriptor() - // linuser.DefaultCreateTime holds the default value on creation for the create_time field. - linuser.DefaultCreateTime = linuserDescCreateTime.Default.(func() time.Time) - // linuserDescUpdateTime is the schema descriptor for update_time field. - linuserDescUpdateTime := linuserMixinFields0[1].Descriptor() - // linuser.DefaultUpdateTime holds the default value on creation for the update_time field. - linuser.DefaultUpdateTime = linuserDescUpdateTime.Default.(func() time.Time) - // linuser.UpdateDefaultUpdateTime holds the default value on update for the update_time field. - linuser.UpdateDefaultUpdateTime = linuserDescUpdateTime.UpdateDefault.(func() time.Time) - // linuserDescDeleteTime is the schema descriptor for delete_time field. - linuserDescDeleteTime := linuserMixinFields0[2].Descriptor() - // linuser.DefaultDeleteTime holds the default value on creation for the delete_time field. - linuser.DefaultDeleteTime = linuserDescDeleteTime.Default.(func() time.Time) - // linuserDescAvatar is the schema descriptor for avatar field. - linuserDescAvatar := linuserFields[2].Descriptor() - // linuser.DefaultAvatar holds the default value on creation for the avatar field. - linuser.DefaultAvatar = linuserDescAvatar.Default.(string) -} diff --git a/internal/data/model/runtime/runtime.go b/internal/data/model/runtime/runtime.go deleted file mode 100644 index 73d2fd8..0000000 --- a/internal/data/model/runtime/runtime.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package runtime - -// The schema-stitching logic is generated in lin-cms-go/internal/data/model/runtime.go - -const ( - Version = "v0.9.1" // Version of ent codegen. - Sum = "h1:IG8andyeD79GG24U8Q+1Y45hQXj6gY5evSBcva5gtBk=" // Sum of ent codegen. -) diff --git a/internal/data/model/tx.go b/internal/data/model/tx.go deleted file mode 100644 index c77a3a0..0000000 --- a/internal/data/model/tx.go +++ /dev/null @@ -1,231 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package model - -import ( - "context" - "sync" - - "entgo.io/ent/dialect" -) - -// Tx is a transactional client that is created by calling Client.Tx(). -type Tx struct { - config - // Book is the client for interacting with the Book builders. - Book *BookClient - // LinFile is the client for interacting with the LinFile builders. - LinFile *LinFileClient - // LinGroup is the client for interacting with the LinGroup builders. - LinGroup *LinGroupClient - // LinGroupPermission is the client for interacting with the LinGroupPermission builders. - LinGroupPermission *LinGroupPermissionClient - // LinLog is the client for interacting with the LinLog builders. - LinLog *LinLogClient - // LinPermission is the client for interacting with the LinPermission builders. - LinPermission *LinPermissionClient - // LinUser is the client for interacting with the LinUser builders. - LinUser *LinUserClient - // LinUserIdentiy is the client for interacting with the LinUserIdentiy builders. - LinUserIdentiy *LinUserIdentiyClient - - // lazily loaded. - client *Client - clientOnce sync.Once - - // completion callbacks. - mu sync.Mutex - onCommit []CommitHook - onRollback []RollbackHook - - // ctx lives for the life of the transaction. It is - // the same context used by the underlying connection. - ctx context.Context -} - -type ( - // Committer is the interface that wraps the Committer method. - Committer interface { - Commit(context.Context, *Tx) error - } - - // The CommitFunc type is an adapter to allow the use of ordinary - // function as a Committer. If f is a function with the appropriate - // signature, CommitFunc(f) is a Committer that calls f. - CommitFunc func(context.Context, *Tx) error - - // CommitHook defines the "commit middleware". A function that gets a Committer - // and returns a Committer. For example: - // - // hook := func(next ent.Committer) ent.Committer { - // return ent.CommitFunc(func(context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Commit(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - CommitHook func(Committer) Committer -) - -// Commit calls f(ctx, m). -func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Commit commits the transaction. -func (tx *Tx) Commit() error { - txDriver := tx.config.driver.(*txDriver) - var fn Committer = CommitFunc(func(context.Context, *Tx) error { - return txDriver.tx.Commit() - }) - tx.mu.Lock() - hooks := append([]CommitHook(nil), tx.onCommit...) - tx.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Commit(tx.ctx, tx) -} - -// OnCommit adds a hook to call on commit. -func (tx *Tx) OnCommit(f CommitHook) { - tx.mu.Lock() - defer tx.mu.Unlock() - tx.onCommit = append(tx.onCommit, f) -} - -type ( - // Rollbacker is the interface that wraps the Rollbacker method. - Rollbacker interface { - Rollback(context.Context, *Tx) error - } - - // The RollbackFunc type is an adapter to allow the use of ordinary - // function as a Rollbacker. If f is a function with the appropriate - // signature, RollbackFunc(f) is a Rollbacker that calls f. - RollbackFunc func(context.Context, *Tx) error - - // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker - // and returns a Rollbacker. For example: - // - // hook := func(next ent.Rollbacker) ent.Rollbacker { - // return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Rollback(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - RollbackHook func(Rollbacker) Rollbacker -) - -// Rollback calls f(ctx, m). -func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Rollback rollbacks the transaction. -func (tx *Tx) Rollback() error { - txDriver := tx.config.driver.(*txDriver) - var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { - return txDriver.tx.Rollback() - }) - tx.mu.Lock() - hooks := append([]RollbackHook(nil), tx.onRollback...) - tx.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Rollback(tx.ctx, tx) -} - -// OnRollback adds a hook to call on rollback. -func (tx *Tx) OnRollback(f RollbackHook) { - tx.mu.Lock() - defer tx.mu.Unlock() - tx.onRollback = append(tx.onRollback, f) -} - -// Client returns a Client that binds to current transaction. -func (tx *Tx) Client() *Client { - tx.clientOnce.Do(func() { - tx.client = &Client{config: tx.config} - tx.client.init() - }) - return tx.client -} - -func (tx *Tx) init() { - tx.Book = NewBookClient(tx.config) - tx.LinFile = NewLinFileClient(tx.config) - tx.LinGroup = NewLinGroupClient(tx.config) - tx.LinGroupPermission = NewLinGroupPermissionClient(tx.config) - tx.LinLog = NewLinLogClient(tx.config) - tx.LinPermission = NewLinPermissionClient(tx.config) - tx.LinUser = NewLinUserClient(tx.config) - tx.LinUserIdentiy = NewLinUserIdentiyClient(tx.config) -} - -// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. -// The idea is to support transactions without adding any extra code to the builders. -// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. -// Commit and Rollback are nop for the internal builders and the user must call one -// of them in order to commit or rollback the transaction. -// -// If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: Book.QueryXXX(), the query will be executed -// through the driver which created this transaction. -// -// Note that txDriver is not goroutine safe. -type txDriver struct { - // the driver we started the transaction from. - drv dialect.Driver - // tx is the underlying transaction. - tx dialect.Tx -} - -// newTx creates a new transactional driver. -func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { - tx, err := drv.Tx(ctx) - if err != nil { - return nil, err - } - return &txDriver{tx: tx, drv: drv}, nil -} - -// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls -// from the internal builders. Should be called only by the internal builders. -func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } - -// Dialect returns the dialect of the driver we started the transaction from. -func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } - -// Close is a nop close. -func (*txDriver) Close() error { return nil } - -// Commit is a nop commit for the internal builders. -// User must call `Tx.Commit` in order to commit the transaction. -func (*txDriver) Commit() error { return nil } - -// Rollback is a nop rollback for the internal builders. -// User must call `Tx.Rollback` in order to rollback the transaction. -func (*txDriver) Rollback() error { return nil } - -// Exec calls tx.Exec. -func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { - return tx.tx.Exec(ctx, query, args, v) -} - -// Query calls tx.Query. -func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { - return tx.tx.Query(ctx, query, args, v) -} - -var _ dialect.Driver = (*txDriver)(nil) diff --git a/pkg/core/response.go b/pkg/core/response.go index 85bb7e7..c87c28f 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -13,14 +13,14 @@ type IError struct { Message string `json:"message"` // 提示信息 Data interface{} `json:"data"` // 返回数据 (业务接口定义具体数据结构) Err error `json:"-"` - } type HttpError struct { IError Status int } + func (err IError) Error() (re string) { - return fmt.Sprintf("code=%v, Message=%v,Err=%v", err.Code, err.Message,err.Err) + return fmt.Sprintf("code=%v, Message=%v,Err=%v", err.Code, err.Message, err.Err) } func NewErrorCode(code int) (err error) { @@ -71,25 +71,17 @@ func ParseRequest(c *fiber.Ctx, request interface{}) (err error) { return } -func NewIError(code int,message string) IError { +func NewIError(code int, message string) IError { return IError{ Code: code, Message: message, } } -func InvalidParamsError(c *fiber.Ctx, msg string) error { - - return c.JSON(IError{ - Code: errcode.InvalidParams, - Message: errcode.GetMsg(errcode.InvalidParams), - }) - -} -func NotFoundError( code int) error { +func NotFoundError(code int) error { return HttpError{ - NewIError(code,errcode.GetMsg(code)), + NewIError(code, errcode.GetMsg(code)), fiber.StatusNotFound, } @@ -131,6 +123,6 @@ func HandleServerError(c *fiber.Ctx, err error) error { func (err *HttpError) HandleHttpError(c *fiber.Ctx) error { return c.JSON(HttpError{IError{ - Code: err.Code,Message: err.Message, - },err.Status}) + Code: err.Code, Message: err.Message, + }, err.Status}) } From 49b53964d9ef6a5e85ee877ec4cac7055aa2601a Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 8 Nov 2021 15:27:28 +0800 Subject: [PATCH 29/44] fix: delete lin_group_permission struct --- internal/data/model/book.go | 129 + internal/data/model/book/book.go | 39 + internal/data/model/book/where.go | 596 +++ internal/data/model/book_create.go | 271 + internal/data/model/book_delete.go | 111 + internal/data/model/book_query.go | 960 ++++ internal/data/model/book_update.go | 342 ++ internal/data/model/client.go | 875 ++++ internal/data/model/config.go | 65 + internal/data/model/context.go | 33 + internal/data/model/ent.go | 271 + internal/data/model/enttest/enttest.go | 77 + internal/data/model/hook/hook.go | 281 ++ internal/data/model/linfile.go | 151 + internal/data/model/linfile/linfile.go | 45 + internal/data/model/linfile/where.go | 762 +++ internal/data/model/linfile_create.go | 305 ++ internal/data/model/linfile_delete.go | 111 + internal/data/model/linfile_query.go | 960 ++++ internal/data/model/linfile_update.go | 450 ++ internal/data/model/lingroup.go | 164 + internal/data/model/lingroup/lingroup.go | 59 + internal/data/model/lingroup/where.go | 500 ++ internal/data/model/lingroup_create.go | 324 ++ internal/data/model/lingroup_delete.go | 111 + internal/data/model/lingroup_query.go | 1170 +++++ internal/data/model/lingroup_update.go | 706 +++ internal/data/model/linlog.go | 192 + internal/data/model/linlog/linlog.go | 72 + internal/data/model/linlog/where.go | 1130 +++++ internal/data/model/linlog_create.go | 416 ++ internal/data/model/linlog_delete.go | 111 + internal/data/model/linlog_query.go | 960 ++++ internal/data/model/linlog_update.go | 563 +++ internal/data/model/linpermission.go | 148 + .../data/model/linpermission/linpermission.go | 49 + internal/data/model/linpermission/where.go | 472 ++ internal/data/model/linpermission_create.go | 289 ++ internal/data/model/linpermission_delete.go | 111 + internal/data/model/linpermission_query.go | 1068 ++++ internal/data/model/linpermission_update.go | 525 ++ internal/data/model/linuser.go | 208 + internal/data/model/linuser/linuser.go | 87 + internal/data/model/linuser/where.go | 903 ++++ internal/data/model/linuser_create.go | 447 ++ internal/data/model/linuser_delete.go | 111 + internal/data/model/linuser_query.go | 1134 +++++ internal/data/model/linuser_update.go | 807 +++ internal/data/model/linuseridentiy.go | 140 + .../model/linuseridentiy/linuseridentiy.go | 50 + internal/data/model/linuseridentiy/where.go | 561 +++ internal/data/model/linuseridentiy_create.go | 271 + internal/data/model/linuseridentiy_delete.go | 111 + internal/data/model/linuseridentiy_query.go | 965 ++++ internal/data/model/linuseridentiy_update.go | 370 ++ internal/data/model/migrate/migrate.go | 72 + internal/data/model/migrate/schema.go | 219 + internal/data/model/mutation.go | 4393 +++++++++++++++++ internal/data/model/predicate/predicate.go | 28 + internal/data/model/runtime.go | 58 + internal/data/model/runtime/runtime.go | 10 + internal/data/model/tx.go | 228 + 62 files changed, 27147 insertions(+) create mode 100644 internal/data/model/book.go create mode 100644 internal/data/model/book/book.go create mode 100644 internal/data/model/book/where.go create mode 100644 internal/data/model/book_create.go create mode 100644 internal/data/model/book_delete.go create mode 100644 internal/data/model/book_query.go create mode 100644 internal/data/model/book_update.go create mode 100644 internal/data/model/client.go create mode 100644 internal/data/model/config.go create mode 100644 internal/data/model/context.go create mode 100644 internal/data/model/ent.go create mode 100644 internal/data/model/enttest/enttest.go create mode 100644 internal/data/model/hook/hook.go create mode 100644 internal/data/model/linfile.go create mode 100644 internal/data/model/linfile/linfile.go create mode 100644 internal/data/model/linfile/where.go create mode 100644 internal/data/model/linfile_create.go create mode 100644 internal/data/model/linfile_delete.go create mode 100644 internal/data/model/linfile_query.go create mode 100644 internal/data/model/linfile_update.go create mode 100644 internal/data/model/lingroup.go create mode 100644 internal/data/model/lingroup/lingroup.go create mode 100644 internal/data/model/lingroup/where.go create mode 100644 internal/data/model/lingroup_create.go create mode 100644 internal/data/model/lingroup_delete.go create mode 100644 internal/data/model/lingroup_query.go create mode 100644 internal/data/model/lingroup_update.go create mode 100644 internal/data/model/linlog.go create mode 100644 internal/data/model/linlog/linlog.go create mode 100644 internal/data/model/linlog/where.go create mode 100644 internal/data/model/linlog_create.go create mode 100644 internal/data/model/linlog_delete.go create mode 100644 internal/data/model/linlog_query.go create mode 100644 internal/data/model/linlog_update.go create mode 100644 internal/data/model/linpermission.go create mode 100644 internal/data/model/linpermission/linpermission.go create mode 100644 internal/data/model/linpermission/where.go create mode 100644 internal/data/model/linpermission_create.go create mode 100644 internal/data/model/linpermission_delete.go create mode 100644 internal/data/model/linpermission_query.go create mode 100644 internal/data/model/linpermission_update.go create mode 100644 internal/data/model/linuser.go create mode 100644 internal/data/model/linuser/linuser.go create mode 100644 internal/data/model/linuser/where.go create mode 100644 internal/data/model/linuser_create.go create mode 100644 internal/data/model/linuser_delete.go create mode 100644 internal/data/model/linuser_query.go create mode 100644 internal/data/model/linuser_update.go create mode 100644 internal/data/model/linuseridentiy.go create mode 100644 internal/data/model/linuseridentiy/linuseridentiy.go create mode 100644 internal/data/model/linuseridentiy/where.go create mode 100644 internal/data/model/linuseridentiy_create.go create mode 100644 internal/data/model/linuseridentiy_delete.go create mode 100644 internal/data/model/linuseridentiy_query.go create mode 100644 internal/data/model/linuseridentiy_update.go create mode 100644 internal/data/model/migrate/migrate.go create mode 100644 internal/data/model/migrate/schema.go create mode 100644 internal/data/model/mutation.go create mode 100644 internal/data/model/predicate/predicate.go create mode 100644 internal/data/model/runtime.go create mode 100644 internal/data/model/runtime/runtime.go create mode 100644 internal/data/model/tx.go diff --git a/internal/data/model/book.go b/internal/data/model/book.go new file mode 100644 index 0000000..7714ba0 --- /dev/null +++ b/internal/data/model/book.go @@ -0,0 +1,129 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/book" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// Book is the model entity for the Book schema. +type Book struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // Author holds the value of the "author" field. + Author string `json:"author,omitempty"` + // Summary holds the value of the "summary" field. + Summary string `json:"summary,omitempty"` + // Image holds the value of the "image" field. + Image string `json:"image,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Book) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case book.FieldID: + values[i] = new(sql.NullInt64) + case book.FieldTitle, book.FieldAuthor, book.FieldSummary, book.FieldImage: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Book", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Book fields. +func (b *Book) assignValues(columns []string, values []interface{}) 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 book.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + b.ID = int(value.Int64) + case book.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + b.Title = value.String + } + case book.FieldAuthor: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field author", values[i]) + } else if value.Valid { + b.Author = value.String + } + case book.FieldSummary: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field summary", values[i]) + } else if value.Valid { + b.Summary = value.String + } + case book.FieldImage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field image", values[i]) + } else if value.Valid { + b.Image = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this Book. +// Note that you need to call Book.Unwrap() before calling this method if this Book +// was returned from a transaction, and the transaction was committed or rolled back. +func (b *Book) Update() *BookUpdateOne { + return (&BookClient{config: b.config}).UpdateOne(b) +} + +// Unwrap unwraps the Book 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 (b *Book) Unwrap() *Book { + tx, ok := b.config.driver.(*txDriver) + if !ok { + panic("model: Book is not a transactional entity") + } + b.config.driver = tx.drv + return b +} + +// String implements the fmt.Stringer. +func (b *Book) String() string { + var builder strings.Builder + builder.WriteString("Book(") + builder.WriteString(fmt.Sprintf("id=%v", b.ID)) + builder.WriteString(", title=") + builder.WriteString(b.Title) + builder.WriteString(", author=") + builder.WriteString(b.Author) + builder.WriteString(", summary=") + builder.WriteString(b.Summary) + builder.WriteString(", image=") + builder.WriteString(b.Image) + builder.WriteByte(')') + return builder.String() +} + +// Books is a parsable slice of Book. +type Books []*Book + +func (b Books) config(cfg config) { + for _i := range b { + b[_i].config = cfg + } +} diff --git a/internal/data/model/book/book.go b/internal/data/model/book/book.go new file mode 100644 index 0000000..040d81c --- /dev/null +++ b/internal/data/model/book/book.go @@ -0,0 +1,39 @@ +// Code generated by entc, DO NOT EDIT. + +package book + +const ( + // Label holds the string label denoting the book type in the database. + Label = "book" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldAuthor holds the string denoting the author field in the database. + FieldAuthor = "author" + // FieldSummary holds the string denoting the summary field in the database. + FieldSummary = "summary" + // FieldImage holds the string denoting the image field in the database. + FieldImage = "image" + // Table holds the table name of the book in the database. + Table = "book" +) + +// Columns holds all SQL columns for book fields. +var Columns = []string{ + FieldID, + FieldTitle, + FieldAuthor, + FieldSummary, + FieldImage, +} + +// 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 +} diff --git a/internal/data/model/book/where.go b/internal/data/model/book/where.go new file mode 100644 index 0000000..7812ed5 --- /dev/null +++ b/internal/data/model/book/where.go @@ -0,0 +1,596 @@ +// Code generated by entc, DO NOT EDIT. + +package book + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTitle), v)) + }) +} + +// Author applies equality check predicate on the "author" field. It's identical to AuthorEQ. +func Author(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAuthor), v)) + }) +} + +// Summary applies equality check predicate on the "summary" field. It's identical to SummaryEQ. +func Summary(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSummary), v)) + }) +} + +// Image applies equality check predicate on the "image" field. It's identical to ImageEQ. +func Image(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldImage), v)) + }) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTitle), v)) + }) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldTitle), v)) + }) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldTitle), v...)) + }) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldTitle), v...)) + }) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldTitle), v)) + }) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldTitle), v)) + }) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldTitle), v)) + }) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldTitle), v)) + }) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldTitle), v)) + }) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldTitle), v)) + }) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldTitle), v)) + }) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldTitle), v)) + }) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldTitle), v)) + }) +} + +// AuthorEQ applies the EQ predicate on the "author" field. +func AuthorEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAuthor), v)) + }) +} + +// AuthorNEQ applies the NEQ predicate on the "author" field. +func AuthorNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAuthor), v)) + }) +} + +// AuthorIn applies the In predicate on the "author" field. +func AuthorIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAuthor), v...)) + }) +} + +// AuthorNotIn applies the NotIn predicate on the "author" field. +func AuthorNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAuthor), v...)) + }) +} + +// AuthorGT applies the GT predicate on the "author" field. +func AuthorGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAuthor), v)) + }) +} + +// AuthorGTE applies the GTE predicate on the "author" field. +func AuthorGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAuthor), v)) + }) +} + +// AuthorLT applies the LT predicate on the "author" field. +func AuthorLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAuthor), v)) + }) +} + +// AuthorLTE applies the LTE predicate on the "author" field. +func AuthorLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAuthor), v)) + }) +} + +// AuthorContains applies the Contains predicate on the "author" field. +func AuthorContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldAuthor), v)) + }) +} + +// AuthorHasPrefix applies the HasPrefix predicate on the "author" field. +func AuthorHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldAuthor), v)) + }) +} + +// AuthorHasSuffix applies the HasSuffix predicate on the "author" field. +func AuthorHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldAuthor), v)) + }) +} + +// AuthorEqualFold applies the EqualFold predicate on the "author" field. +func AuthorEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldAuthor), v)) + }) +} + +// AuthorContainsFold applies the ContainsFold predicate on the "author" field. +func AuthorContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldAuthor), v)) + }) +} + +// SummaryEQ applies the EQ predicate on the "summary" field. +func SummaryEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSummary), v)) + }) +} + +// SummaryNEQ applies the NEQ predicate on the "summary" field. +func SummaryNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldSummary), v)) + }) +} + +// SummaryIn applies the In predicate on the "summary" field. +func SummaryIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldSummary), v...)) + }) +} + +// SummaryNotIn applies the NotIn predicate on the "summary" field. +func SummaryNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldSummary), v...)) + }) +} + +// SummaryGT applies the GT predicate on the "summary" field. +func SummaryGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldSummary), v)) + }) +} + +// SummaryGTE applies the GTE predicate on the "summary" field. +func SummaryGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldSummary), v)) + }) +} + +// SummaryLT applies the LT predicate on the "summary" field. +func SummaryLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldSummary), v)) + }) +} + +// SummaryLTE applies the LTE predicate on the "summary" field. +func SummaryLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldSummary), v)) + }) +} + +// SummaryContains applies the Contains predicate on the "summary" field. +func SummaryContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldSummary), v)) + }) +} + +// SummaryHasPrefix applies the HasPrefix predicate on the "summary" field. +func SummaryHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldSummary), v)) + }) +} + +// SummaryHasSuffix applies the HasSuffix predicate on the "summary" field. +func SummaryHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldSummary), v)) + }) +} + +// SummaryEqualFold applies the EqualFold predicate on the "summary" field. +func SummaryEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldSummary), v)) + }) +} + +// SummaryContainsFold applies the ContainsFold predicate on the "summary" field. +func SummaryContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldSummary), v)) + }) +} + +// ImageEQ applies the EQ predicate on the "image" field. +func ImageEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldImage), v)) + }) +} + +// ImageNEQ applies the NEQ predicate on the "image" field. +func ImageNEQ(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldImage), v)) + }) +} + +// ImageIn applies the In predicate on the "image" field. +func ImageIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldImage), v...)) + }) +} + +// ImageNotIn applies the NotIn predicate on the "image" field. +func ImageNotIn(vs ...string) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldImage), v...)) + }) +} + +// ImageGT applies the GT predicate on the "image" field. +func ImageGT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldImage), v)) + }) +} + +// ImageGTE applies the GTE predicate on the "image" field. +func ImageGTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldImage), v)) + }) +} + +// ImageLT applies the LT predicate on the "image" field. +func ImageLT(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldImage), v)) + }) +} + +// ImageLTE applies the LTE predicate on the "image" field. +func ImageLTE(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldImage), v)) + }) +} + +// ImageContains applies the Contains predicate on the "image" field. +func ImageContains(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldImage), v)) + }) +} + +// ImageHasPrefix applies the HasPrefix predicate on the "image" field. +func ImageHasPrefix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldImage), v)) + }) +} + +// ImageHasSuffix applies the HasSuffix predicate on the "image" field. +func ImageHasSuffix(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldImage), v)) + }) +} + +// ImageEqualFold applies the EqualFold predicate on the "image" field. +func ImageEqualFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldImage), v)) + }) +} + +// ImageContainsFold applies the ContainsFold predicate on the "image" field. +func ImageContainsFold(v string) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldImage), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Book) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Book) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Book) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/book_create.go b/internal/data/model/book_create.go new file mode 100644 index 0000000..ba2bd4a --- /dev/null +++ b/internal/data/model/book_create.go @@ -0,0 +1,271 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookCreate is the builder for creating a Book entity. +type BookCreate struct { + config + mutation *BookMutation + hooks []Hook +} + +// SetTitle sets the "title" field. +func (bc *BookCreate) SetTitle(s string) *BookCreate { + bc.mutation.SetTitle(s) + return bc +} + +// SetAuthor sets the "author" field. +func (bc *BookCreate) SetAuthor(s string) *BookCreate { + bc.mutation.SetAuthor(s) + return bc +} + +// SetSummary sets the "summary" field. +func (bc *BookCreate) SetSummary(s string) *BookCreate { + bc.mutation.SetSummary(s) + return bc +} + +// SetImage sets the "image" field. +func (bc *BookCreate) SetImage(s string) *BookCreate { + bc.mutation.SetImage(s) + return bc +} + +// Mutation returns the BookMutation object of the builder. +func (bc *BookCreate) Mutation() *BookMutation { + return bc.mutation +} + +// Save creates the Book in the database. +func (bc *BookCreate) Save(ctx context.Context) (*Book, error) { + var ( + err error + node *Book + ) + if len(bc.hooks) == 0 { + if err = bc.check(); err != nil { + return nil, err + } + node, err = bc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = bc.check(); err != nil { + return nil, err + } + bc.mutation = mutation + if node, err = bc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(bc.hooks) - 1; i >= 0; i-- { + if bc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = bc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (bc *BookCreate) SaveX(ctx context.Context) *Book { + v, err := bc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bc *BookCreate) Exec(ctx context.Context) error { + _, err := bc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bc *BookCreate) ExecX(ctx context.Context) { + if err := bc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (bc *BookCreate) check() error { + if _, ok := bc.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`model: missing required field "title"`)} + } + if _, ok := bc.mutation.Author(); !ok { + return &ValidationError{Name: "author", err: errors.New(`model: missing required field "author"`)} + } + if _, ok := bc.mutation.Summary(); !ok { + return &ValidationError{Name: "summary", err: errors.New(`model: missing required field "summary"`)} + } + if _, ok := bc.mutation.Image(); !ok { + return &ValidationError{Name: "image", err: errors.New(`model: missing required field "image"`)} + } + return nil +} + +func (bc *BookCreate) sqlSave(ctx context.Context) (*Book, error) { + _node, _spec := bc.createSpec() + if err := sqlgraph.CreateNode(ctx, bc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (bc *BookCreate) createSpec() (*Book, *sqlgraph.CreateSpec) { + var ( + _node = &Book{config: bc.config} + _spec = &sqlgraph.CreateSpec{ + Table: book.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + } + ) + if value, ok := bc.mutation.Title(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldTitle, + }) + _node.Title = value + } + if value, ok := bc.mutation.Author(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldAuthor, + }) + _node.Author = value + } + if value, ok := bc.mutation.Summary(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldSummary, + }) + _node.Summary = value + } + if value, ok := bc.mutation.Image(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldImage, + }) + _node.Image = value + } + return _node, _spec +} + +// BookCreateBulk is the builder for creating many Book entities in bulk. +type BookCreateBulk struct { + config + builders []*BookCreate +} + +// Save creates the Book entities in the database. +func (bcb *BookCreateBulk) Save(ctx context.Context) ([]*Book, error) { + specs := make([]*sqlgraph.CreateSpec, len(bcb.builders)) + nodes := make([]*Book, len(bcb.builders)) + mutators := make([]Mutator, len(bcb.builders)) + for i := range bcb.builders { + func(i int, root context.Context) { + builder := bcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, bcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, bcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, bcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (bcb *BookCreateBulk) SaveX(ctx context.Context) []*Book { + v, err := bcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bcb *BookCreateBulk) Exec(ctx context.Context) error { + _, err := bcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bcb *BookCreateBulk) ExecX(ctx context.Context) { + if err := bcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/book_delete.go b/internal/data/model/book_delete.go new file mode 100644 index 0000000..6813e56 --- /dev/null +++ b/internal/data/model/book_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookDelete is the builder for deleting a Book entity. +type BookDelete struct { + config + hooks []Hook + mutation *BookMutation +} + +// Where appends a list predicates to the BookDelete builder. +func (bd *BookDelete) Where(ps ...predicate.Book) *BookDelete { + bd.mutation.Where(ps...) + return bd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (bd *BookDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(bd.hooks) == 0 { + affected, err = bd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + bd.mutation = mutation + affected, err = bd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(bd.hooks) - 1; i >= 0; i-- { + if bd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = bd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bd *BookDelete) ExecX(ctx context.Context) int { + n, err := bd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (bd *BookDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + } + if ps := bd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, bd.driver, _spec) +} + +// BookDeleteOne is the builder for deleting a single Book entity. +type BookDeleteOne struct { + bd *BookDelete +} + +// Exec executes the deletion query. +func (bdo *BookDeleteOne) Exec(ctx context.Context) error { + n, err := bdo.bd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{book.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (bdo *BookDeleteOne) ExecX(ctx context.Context) { + bdo.bd.ExecX(ctx) +} diff --git a/internal/data/model/book_query.go b/internal/data/model/book_query.go new file mode 100644 index 0000000..d27c9e7 --- /dev/null +++ b/internal/data/model/book_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookQuery is the builder for querying Book entities. +type BookQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Book + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the BookQuery builder. +func (bq *BookQuery) Where(ps ...predicate.Book) *BookQuery { + bq.predicates = append(bq.predicates, ps...) + return bq +} + +// Limit adds a limit step to the query. +func (bq *BookQuery) Limit(limit int) *BookQuery { + bq.limit = &limit + return bq +} + +// Offset adds an offset step to the query. +func (bq *BookQuery) Offset(offset int) *BookQuery { + bq.offset = &offset + return bq +} + +// 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 (bq *BookQuery) Unique(unique bool) *BookQuery { + bq.unique = &unique + return bq +} + +// Order adds an order step to the query. +func (bq *BookQuery) Order(o ...OrderFunc) *BookQuery { + bq.order = append(bq.order, o...) + return bq +} + +// First returns the first Book entity from the query. +// Returns a *NotFoundError when no Book was found. +func (bq *BookQuery) First(ctx context.Context) (*Book, error) { + nodes, err := bq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{book.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (bq *BookQuery) FirstX(ctx context.Context) *Book { + node, err := bq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Book ID from the query. +// Returns a *NotFoundError when no Book ID was found. +func (bq *BookQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{book.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (bq *BookQuery) FirstIDX(ctx context.Context) int { + id, err := bq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last Book entity from the query. +// Returns a *NotFoundError when no Book was found. +func (bq *BookQuery) Last(ctx context.Context) (*Book, error) { + nodes, err := bq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{book.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (bq *BookQuery) LastX(ctx context.Context) *Book { + node, err := bq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last Book ID from the query. +// Returns a *NotFoundError when no Book ID was found. +func (bq *BookQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{book.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (bq *BookQuery) LastIDX(ctx context.Context) int { + id, err := bq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Book entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one Book entity is not found. +// Returns a *NotFoundError when no Book entities are found. +func (bq *BookQuery) Only(ctx context.Context) (*Book, error) { + nodes, err := bq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{book.Label} + default: + return nil, &NotSingularError{book.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (bq *BookQuery) OnlyX(ctx context.Context) *Book { + node, err := bq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Book ID in the query. +// Returns a *NotSingularError when exactly one Book ID is not found. +// Returns a *NotFoundError when no entities are found. +func (bq *BookQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{book.Label} + default: + err = &NotSingularError{book.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (bq *BookQuery) OnlyIDX(ctx context.Context) int { + id, err := bq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Books. +func (bq *BookQuery) All(ctx context.Context) ([]*Book, error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + return bq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (bq *BookQuery) AllX(ctx context.Context) []*Book { + nodes, err := bq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Book IDs. +func (bq *BookQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := bq.Select(book.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (bq *BookQuery) IDsX(ctx context.Context) []int { + ids, err := bq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (bq *BookQuery) Count(ctx context.Context) (int, error) { + if err := bq.prepareQuery(ctx); err != nil { + return 0, err + } + return bq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (bq *BookQuery) CountX(ctx context.Context) int { + count, err := bq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (bq *BookQuery) Exist(ctx context.Context) (bool, error) { + if err := bq.prepareQuery(ctx); err != nil { + return false, err + } + return bq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (bq *BookQuery) ExistX(ctx context.Context) bool { + exist, err := bq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BookQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (bq *BookQuery) Clone() *BookQuery { + if bq == nil { + return nil + } + return &BookQuery{ + config: bq.config, + limit: bq.limit, + offset: bq.offset, + order: append([]OrderFunc{}, bq.order...), + predicates: append([]predicate.Book{}, bq.predicates...), + // clone intermediate query. + sql: bq.sql.Clone(), + path: bq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Title string `json:"title,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Book.Query(). +// GroupBy(book.FieldTitle). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (bq *BookQuery) GroupBy(field string, fields ...string) *BookGroupBy { + group := &BookGroupBy{config: bq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + return bq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Title string `json:"title,omitempty"` +// } +// +// client.Book.Query(). +// Select(book.FieldTitle). +// Scan(ctx, &v) +// +func (bq *BookQuery) Select(fields ...string) *BookSelect { + bq.fields = append(bq.fields, fields...) + return &BookSelect{BookQuery: bq} +} + +func (bq *BookQuery) prepareQuery(ctx context.Context) error { + for _, f := range bq.fields { + if !book.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if bq.path != nil { + prev, err := bq.path(ctx) + if err != nil { + return err + } + bq.sql = prev + } + return nil +} + +func (bq *BookQuery) sqlAll(ctx context.Context) ([]*Book, error) { + var ( + nodes = []*Book{} + _spec = bq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Book{config: bq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, bq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (bq *BookQuery) sqlCount(ctx context.Context) (int, error) { + _spec := bq.querySpec() + return sqlgraph.CountNodes(ctx, bq.driver, _spec) +} + +func (bq *BookQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := bq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (bq *BookQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + Columns: book.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + From: bq.sql, + Unique: true, + } + if unique := bq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := bq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, book.FieldID) + for i := range fields { + if fields[i] != book.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := bq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := bq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := bq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := bq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (bq *BookQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(bq.driver.Dialect()) + t1 := builder.Table(book.Table) + columns := bq.fields + if len(columns) == 0 { + columns = book.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if bq.sql != nil { + selector = bq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range bq.predicates { + p(selector) + } + for _, p := range bq.order { + p(selector) + } + if offset := bq.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 := bq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// BookGroupBy is the group-by builder for Book entities. +type BookGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (bgb *BookGroupBy) Aggregate(fns ...AggregateFunc) *BookGroupBy { + bgb.fns = append(bgb.fns, fns...) + return bgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (bgb *BookGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := bgb.path(ctx) + if err != nil { + return err + } + bgb.sql = query + return bgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (bgb *BookGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := bgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (bgb *BookGroupBy) StringsX(ctx context.Context) []string { + v, err := bgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = bgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (bgb *BookGroupBy) StringX(ctx context.Context) string { + v, err := bgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (bgb *BookGroupBy) IntsX(ctx context.Context) []int { + v, err := bgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = bgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (bgb *BookGroupBy) IntX(ctx context.Context) int { + v, err := bgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (bgb *BookGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := bgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = bgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (bgb *BookGroupBy) Float64X(ctx context.Context) float64 { + v, err := bgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(bgb.fields) > 1 { + return nil, errors.New("model: BookGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := bgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (bgb *BookGroupBy) BoolsX(ctx context.Context) []bool { + v, err := bgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (bgb *BookGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = bgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (bgb *BookGroupBy) BoolX(ctx context.Context) bool { + v, err := bgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (bgb *BookGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range bgb.fields { + if !book.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := bgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := bgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (bgb *BookGroupBy) sqlQuery() *sql.Selector { + selector := bgb.sql.Select() + aggregation := make([]string, 0, len(bgb.fns)) + for _, fn := range bgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(bgb.fields)+len(bgb.fns)) + for _, f := range bgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(bgb.fields...)...) +} + +// BookSelect is the builder for selecting fields of Book entities. +type BookSelect struct { + *BookQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (bs *BookSelect) Scan(ctx context.Context, v interface{}) error { + if err := bs.prepareQuery(ctx); err != nil { + return err + } + bs.sql = bs.BookQuery.sqlQuery(ctx) + return bs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (bs *BookSelect) ScanX(ctx context.Context, v interface{}) { + if err := bs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Strings(ctx context.Context) ([]string, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (bs *BookSelect) StringsX(ctx context.Context) []string { + v, err := bs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = bs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (bs *BookSelect) StringX(ctx context.Context) string { + v, err := bs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Ints(ctx context.Context) ([]int, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (bs *BookSelect) IntsX(ctx context.Context) []int { + v, err := bs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = bs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (bs *BookSelect) IntX(ctx context.Context) int { + v, err := bs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (bs *BookSelect) Float64sX(ctx context.Context) []float64 { + v, err := bs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = bs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (bs *BookSelect) Float64X(ctx context.Context) float64 { + v, err := bs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Bools(ctx context.Context) ([]bool, error) { + if len(bs.fields) > 1 { + return nil, errors.New("model: BookSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := bs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (bs *BookSelect) BoolsX(ctx context.Context) []bool { + v, err := bs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (bs *BookSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = bs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{book.Label} + default: + err = fmt.Errorf("model: BookSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (bs *BookSelect) BoolX(ctx context.Context) bool { + v, err := bs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (bs *BookSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := bs.sql.Query() + if err := bs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/book_update.go b/internal/data/model/book_update.go new file mode 100644 index 0000000..1d409aa --- /dev/null +++ b/internal/data/model/book_update.go @@ -0,0 +1,342 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BookUpdate is the builder for updating Book entities. +type BookUpdate struct { + config + hooks []Hook + mutation *BookMutation +} + +// Where appends a list predicates to the BookUpdate builder. +func (bu *BookUpdate) Where(ps ...predicate.Book) *BookUpdate { + bu.mutation.Where(ps...) + return bu +} + +// SetTitle sets the "title" field. +func (bu *BookUpdate) SetTitle(s string) *BookUpdate { + bu.mutation.SetTitle(s) + return bu +} + +// SetAuthor sets the "author" field. +func (bu *BookUpdate) SetAuthor(s string) *BookUpdate { + bu.mutation.SetAuthor(s) + return bu +} + +// SetSummary sets the "summary" field. +func (bu *BookUpdate) SetSummary(s string) *BookUpdate { + bu.mutation.SetSummary(s) + return bu +} + +// SetImage sets the "image" field. +func (bu *BookUpdate) SetImage(s string) *BookUpdate { + bu.mutation.SetImage(s) + return bu +} + +// Mutation returns the BookMutation object of the builder. +func (bu *BookUpdate) Mutation() *BookMutation { + return bu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (bu *BookUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(bu.hooks) == 0 { + affected, err = bu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + bu.mutation = mutation + affected, err = bu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(bu.hooks) - 1; i >= 0; i-- { + if bu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = bu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (bu *BookUpdate) SaveX(ctx context.Context) int { + affected, err := bu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (bu *BookUpdate) Exec(ctx context.Context) error { + _, err := bu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bu *BookUpdate) ExecX(ctx context.Context) { + if err := bu.Exec(ctx); err != nil { + panic(err) + } +} + +func (bu *BookUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + Columns: book.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + } + if ps := bu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := bu.mutation.Title(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldTitle, + }) + } + if value, ok := bu.mutation.Author(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldAuthor, + }) + } + if value, ok := bu.mutation.Summary(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldSummary, + }) + } + if value, ok := bu.mutation.Image(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldImage, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, bu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{book.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// BookUpdateOne is the builder for updating a single Book entity. +type BookUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BookMutation +} + +// SetTitle sets the "title" field. +func (buo *BookUpdateOne) SetTitle(s string) *BookUpdateOne { + buo.mutation.SetTitle(s) + return buo +} + +// SetAuthor sets the "author" field. +func (buo *BookUpdateOne) SetAuthor(s string) *BookUpdateOne { + buo.mutation.SetAuthor(s) + return buo +} + +// SetSummary sets the "summary" field. +func (buo *BookUpdateOne) SetSummary(s string) *BookUpdateOne { + buo.mutation.SetSummary(s) + return buo +} + +// SetImage sets the "image" field. +func (buo *BookUpdateOne) SetImage(s string) *BookUpdateOne { + buo.mutation.SetImage(s) + return buo +} + +// Mutation returns the BookMutation object of the builder. +func (buo *BookUpdateOne) Mutation() *BookMutation { + return buo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (buo *BookUpdateOne) Select(field string, fields ...string) *BookUpdateOne { + buo.fields = append([]string{field}, fields...) + return buo +} + +// Save executes the query and returns the updated Book entity. +func (buo *BookUpdateOne) Save(ctx context.Context) (*Book, error) { + var ( + err error + node *Book + ) + if len(buo.hooks) == 0 { + node, err = buo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + buo.mutation = mutation + node, err = buo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(buo.hooks) - 1; i >= 0; i-- { + if buo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = buo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, buo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (buo *BookUpdateOne) SaveX(ctx context.Context) *Book { + node, err := buo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (buo *BookUpdateOne) Exec(ctx context.Context) error { + _, err := buo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (buo *BookUpdateOne) ExecX(ctx context.Context) { + if err := buo.Exec(ctx); err != nil { + panic(err) + } +} + +func (buo *BookUpdateOne) sqlSave(ctx context.Context) (_node *Book, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: book.Table, + Columns: book.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: book.FieldID, + }, + }, + } + id, ok := buo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Book.ID for update")} + } + _spec.Node.ID.Value = id + if fields := buo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, book.FieldID) + for _, f := range fields { + if !book.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != book.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := buo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := buo.mutation.Title(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldTitle, + }) + } + if value, ok := buo.mutation.Author(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldAuthor, + }) + } + if value, ok := buo.mutation.Summary(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldSummary, + }) + } + if value, ok := buo.mutation.Image(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: book.FieldImage, + }) + } + _node = &Book{config: buo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, buo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{book.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/client.go b/internal/data/model/client.go new file mode 100644 index 0000000..50875c7 --- /dev/null +++ b/internal/data/model/client.go @@ -0,0 +1,875 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "log" + + "lin-cms-go/internal/data/model/migrate" + + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Book is the client for interacting with the Book builders. + Book *BookClient + // LinFile is the client for interacting with the LinFile builders. + LinFile *LinFileClient + // LinGroup is the client for interacting with the LinGroup builders. + LinGroup *LinGroupClient + // LinLog is the client for interacting with the LinLog builders. + LinLog *LinLogClient + // LinPermission is the client for interacting with the LinPermission builders. + LinPermission *LinPermissionClient + // LinUser is the client for interacting with the LinUser builders. + LinUser *LinUserClient + // LinUserIdentiy is the client for interacting with the LinUserIdentiy builders. + LinUserIdentiy *LinUserIdentiyClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Book = NewBookClient(c.config) + c.LinFile = NewLinFileClient(c.config) + c.LinGroup = NewLinGroupClient(c.config) + c.LinLog = NewLinLogClient(c.config) + c.LinPermission = NewLinPermissionClient(c.config) + c.LinUser = NewLinUserClient(c.config) + c.LinUserIdentiy = NewLinUserIdentiyClient(c.config) +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("model: cannot start a transaction within a transaction") + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("model: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Book: NewBookClient(cfg), + LinFile: NewLinFileClient(cfg), + LinGroup: NewLinGroupClient(cfg), + LinLog: NewLinLogClient(cfg), + LinPermission: NewLinPermissionClient(cfg), + LinUser: NewLinUserClient(cfg), + LinUserIdentiy: NewLinUserIdentiyClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + config: cfg, + Book: NewBookClient(cfg), + LinFile: NewLinFileClient(cfg), + LinGroup: NewLinGroupClient(cfg), + LinLog: NewLinLogClient(cfg), + LinPermission: NewLinPermissionClient(cfg), + LinUser: NewLinUserClient(cfg), + LinUserIdentiy: NewLinUserIdentiyClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Book. +// Query(). +// Count(ctx) +// +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Book.Use(hooks...) + c.LinFile.Use(hooks...) + c.LinGroup.Use(hooks...) + c.LinLog.Use(hooks...) + c.LinPermission.Use(hooks...) + c.LinUser.Use(hooks...) + c.LinUserIdentiy.Use(hooks...) +} + +// BookClient is a client for the Book schema. +type BookClient struct { + config +} + +// NewBookClient returns a client for the Book from the given config. +func NewBookClient(c config) *BookClient { + return &BookClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `book.Hooks(f(g(h())))`. +func (c *BookClient) Use(hooks ...Hook) { + c.hooks.Book = append(c.hooks.Book, hooks...) +} + +// Create returns a create builder for Book. +func (c *BookClient) Create() *BookCreate { + mutation := newBookMutation(c.config, OpCreate) + return &BookCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Book entities. +func (c *BookClient) CreateBulk(builders ...*BookCreate) *BookCreateBulk { + return &BookCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Book. +func (c *BookClient) Update() *BookUpdate { + mutation := newBookMutation(c.config, OpUpdate) + return &BookUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BookClient) UpdateOne(b *Book) *BookUpdateOne { + mutation := newBookMutation(c.config, OpUpdateOne, withBook(b)) + return &BookUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BookClient) UpdateOneID(id int) *BookUpdateOne { + mutation := newBookMutation(c.config, OpUpdateOne, withBookID(id)) + return &BookUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Book. +func (c *BookClient) Delete() *BookDelete { + mutation := newBookMutation(c.config, OpDelete) + return &BookDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *BookClient) DeleteOne(b *Book) *BookDeleteOne { + return c.DeleteOneID(b.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *BookClient) DeleteOneID(id int) *BookDeleteOne { + builder := c.Delete().Where(book.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BookDeleteOne{builder} +} + +// Query returns a query builder for Book. +func (c *BookClient) Query() *BookQuery { + return &BookQuery{ + config: c.config, + } +} + +// Get returns a Book entity by its id. +func (c *BookClient) Get(ctx context.Context, id int) (*Book, error) { + return c.Query().Where(book.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BookClient) GetX(ctx context.Context, id int) *Book { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BookClient) Hooks() []Hook { + return c.hooks.Book +} + +// LinFileClient is a client for the LinFile schema. +type LinFileClient struct { + config +} + +// NewLinFileClient returns a client for the LinFile from the given config. +func NewLinFileClient(c config) *LinFileClient { + return &LinFileClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linfile.Hooks(f(g(h())))`. +func (c *LinFileClient) Use(hooks ...Hook) { + c.hooks.LinFile = append(c.hooks.LinFile, hooks...) +} + +// Create returns a create builder for LinFile. +func (c *LinFileClient) Create() *LinFileCreate { + mutation := newLinFileMutation(c.config, OpCreate) + return &LinFileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinFile entities. +func (c *LinFileClient) CreateBulk(builders ...*LinFileCreate) *LinFileCreateBulk { + return &LinFileCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinFile. +func (c *LinFileClient) Update() *LinFileUpdate { + mutation := newLinFileMutation(c.config, OpUpdate) + return &LinFileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinFileClient) UpdateOne(lf *LinFile) *LinFileUpdateOne { + mutation := newLinFileMutation(c.config, OpUpdateOne, withLinFile(lf)) + return &LinFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinFileClient) UpdateOneID(id int) *LinFileUpdateOne { + mutation := newLinFileMutation(c.config, OpUpdateOne, withLinFileID(id)) + return &LinFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinFile. +func (c *LinFileClient) Delete() *LinFileDelete { + mutation := newLinFileMutation(c.config, OpDelete) + return &LinFileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinFileClient) DeleteOne(lf *LinFile) *LinFileDeleteOne { + return c.DeleteOneID(lf.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinFileClient) DeleteOneID(id int) *LinFileDeleteOne { + builder := c.Delete().Where(linfile.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinFileDeleteOne{builder} +} + +// Query returns a query builder for LinFile. +func (c *LinFileClient) Query() *LinFileQuery { + return &LinFileQuery{ + config: c.config, + } +} + +// Get returns a LinFile entity by its id. +func (c *LinFileClient) Get(ctx context.Context, id int) (*LinFile, error) { + return c.Query().Where(linfile.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinFileClient) GetX(ctx context.Context, id int) *LinFile { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinFileClient) Hooks() []Hook { + return c.hooks.LinFile +} + +// LinGroupClient is a client for the LinGroup schema. +type LinGroupClient struct { + config +} + +// NewLinGroupClient returns a client for the LinGroup from the given config. +func NewLinGroupClient(c config) *LinGroupClient { + return &LinGroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `lingroup.Hooks(f(g(h())))`. +func (c *LinGroupClient) Use(hooks ...Hook) { + c.hooks.LinGroup = append(c.hooks.LinGroup, hooks...) +} + +// Create returns a create builder for LinGroup. +func (c *LinGroupClient) Create() *LinGroupCreate { + mutation := newLinGroupMutation(c.config, OpCreate) + return &LinGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinGroup entities. +func (c *LinGroupClient) CreateBulk(builders ...*LinGroupCreate) *LinGroupCreateBulk { + return &LinGroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinGroup. +func (c *LinGroupClient) Update() *LinGroupUpdate { + mutation := newLinGroupMutation(c.config, OpUpdate) + return &LinGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinGroupClient) UpdateOne(lg *LinGroup) *LinGroupUpdateOne { + mutation := newLinGroupMutation(c.config, OpUpdateOne, withLinGroup(lg)) + return &LinGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinGroupClient) UpdateOneID(id int) *LinGroupUpdateOne { + mutation := newLinGroupMutation(c.config, OpUpdateOne, withLinGroupID(id)) + return &LinGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinGroup. +func (c *LinGroupClient) Delete() *LinGroupDelete { + mutation := newLinGroupMutation(c.config, OpDelete) + return &LinGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinGroupClient) DeleteOne(lg *LinGroup) *LinGroupDeleteOne { + return c.DeleteOneID(lg.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinGroupClient) DeleteOneID(id int) *LinGroupDeleteOne { + builder := c.Delete().Where(lingroup.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinGroupDeleteOne{builder} +} + +// Query returns a query builder for LinGroup. +func (c *LinGroupClient) Query() *LinGroupQuery { + return &LinGroupQuery{ + config: c.config, + } +} + +// Get returns a LinGroup entity by its id. +func (c *LinGroupClient) Get(ctx context.Context, id int) (*LinGroup, error) { + return c.Query().Where(lingroup.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinGroupClient) GetX(ctx context.Context, id int) *LinGroup { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinUser queries the lin_user edge of a LinGroup. +func (c *LinGroupClient) QueryLinUser(lg *LinGroup) *LinUserQuery { + query := &LinUserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lg.ID + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, id), + sqlgraph.To(linuser.Table, linuser.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, lingroup.LinUserTable, lingroup.LinUserPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lg.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLinPermission queries the lin_permission edge of a LinGroup. +func (c *LinGroupClient) QueryLinPermission(lg *LinGroup) *LinPermissionQuery { + query := &LinPermissionQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lg.ID + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, id), + sqlgraph.To(linpermission.Table, linpermission.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, lingroup.LinPermissionTable, lingroup.LinPermissionPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lg.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinGroupClient) Hooks() []Hook { + return c.hooks.LinGroup +} + +// LinLogClient is a client for the LinLog schema. +type LinLogClient struct { + config +} + +// NewLinLogClient returns a client for the LinLog from the given config. +func NewLinLogClient(c config) *LinLogClient { + return &LinLogClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linlog.Hooks(f(g(h())))`. +func (c *LinLogClient) Use(hooks ...Hook) { + c.hooks.LinLog = append(c.hooks.LinLog, hooks...) +} + +// Create returns a create builder for LinLog. +func (c *LinLogClient) Create() *LinLogCreate { + mutation := newLinLogMutation(c.config, OpCreate) + return &LinLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinLog entities. +func (c *LinLogClient) CreateBulk(builders ...*LinLogCreate) *LinLogCreateBulk { + return &LinLogCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinLog. +func (c *LinLogClient) Update() *LinLogUpdate { + mutation := newLinLogMutation(c.config, OpUpdate) + return &LinLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinLogClient) UpdateOne(ll *LinLog) *LinLogUpdateOne { + mutation := newLinLogMutation(c.config, OpUpdateOne, withLinLog(ll)) + return &LinLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinLogClient) UpdateOneID(id int) *LinLogUpdateOne { + mutation := newLinLogMutation(c.config, OpUpdateOne, withLinLogID(id)) + return &LinLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinLog. +func (c *LinLogClient) Delete() *LinLogDelete { + mutation := newLinLogMutation(c.config, OpDelete) + return &LinLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinLogClient) DeleteOne(ll *LinLog) *LinLogDeleteOne { + return c.DeleteOneID(ll.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinLogClient) DeleteOneID(id int) *LinLogDeleteOne { + builder := c.Delete().Where(linlog.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinLogDeleteOne{builder} +} + +// Query returns a query builder for LinLog. +func (c *LinLogClient) Query() *LinLogQuery { + return &LinLogQuery{ + config: c.config, + } +} + +// Get returns a LinLog entity by its id. +func (c *LinLogClient) Get(ctx context.Context, id int) (*LinLog, error) { + return c.Query().Where(linlog.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinLogClient) GetX(ctx context.Context, id int) *LinLog { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinLogClient) Hooks() []Hook { + return c.hooks.LinLog +} + +// LinPermissionClient is a client for the LinPermission schema. +type LinPermissionClient struct { + config +} + +// NewLinPermissionClient returns a client for the LinPermission from the given config. +func NewLinPermissionClient(c config) *LinPermissionClient { + return &LinPermissionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linpermission.Hooks(f(g(h())))`. +func (c *LinPermissionClient) Use(hooks ...Hook) { + c.hooks.LinPermission = append(c.hooks.LinPermission, hooks...) +} + +// Create returns a create builder for LinPermission. +func (c *LinPermissionClient) Create() *LinPermissionCreate { + mutation := newLinPermissionMutation(c.config, OpCreate) + return &LinPermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinPermission entities. +func (c *LinPermissionClient) CreateBulk(builders ...*LinPermissionCreate) *LinPermissionCreateBulk { + return &LinPermissionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinPermission. +func (c *LinPermissionClient) Update() *LinPermissionUpdate { + mutation := newLinPermissionMutation(c.config, OpUpdate) + return &LinPermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinPermissionClient) UpdateOne(lp *LinPermission) *LinPermissionUpdateOne { + mutation := newLinPermissionMutation(c.config, OpUpdateOne, withLinPermission(lp)) + return &LinPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinPermissionClient) UpdateOneID(id int) *LinPermissionUpdateOne { + mutation := newLinPermissionMutation(c.config, OpUpdateOne, withLinPermissionID(id)) + return &LinPermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinPermission. +func (c *LinPermissionClient) Delete() *LinPermissionDelete { + mutation := newLinPermissionMutation(c.config, OpDelete) + return &LinPermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinPermissionClient) DeleteOne(lp *LinPermission) *LinPermissionDeleteOne { + return c.DeleteOneID(lp.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinPermissionClient) DeleteOneID(id int) *LinPermissionDeleteOne { + builder := c.Delete().Where(linpermission.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinPermissionDeleteOne{builder} +} + +// Query returns a query builder for LinPermission. +func (c *LinPermissionClient) Query() *LinPermissionQuery { + return &LinPermissionQuery{ + config: c.config, + } +} + +// Get returns a LinPermission entity by its id. +func (c *LinPermissionClient) Get(ctx context.Context, id int) (*LinPermission, error) { + return c.Query().Where(linpermission.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinPermissionClient) GetX(ctx context.Context, id int) *LinPermission { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinGroup queries the lin_group edge of a LinPermission. +func (c *LinPermissionClient) QueryLinGroup(lp *LinPermission) *LinGroupQuery { + query := &LinGroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lp.ID + step := sqlgraph.NewStep( + sqlgraph.From(linpermission.Table, linpermission.FieldID, id), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, linpermission.LinGroupTable, linpermission.LinGroupPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lp.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinPermissionClient) Hooks() []Hook { + return c.hooks.LinPermission +} + +// LinUserClient is a client for the LinUser schema. +type LinUserClient struct { + config +} + +// NewLinUserClient returns a client for the LinUser from the given config. +func NewLinUserClient(c config) *LinUserClient { + return &LinUserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linuser.Hooks(f(g(h())))`. +func (c *LinUserClient) Use(hooks ...Hook) { + c.hooks.LinUser = append(c.hooks.LinUser, hooks...) +} + +// Create returns a create builder for LinUser. +func (c *LinUserClient) Create() *LinUserCreate { + mutation := newLinUserMutation(c.config, OpCreate) + return &LinUserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinUser entities. +func (c *LinUserClient) CreateBulk(builders ...*LinUserCreate) *LinUserCreateBulk { + return &LinUserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinUser. +func (c *LinUserClient) Update() *LinUserUpdate { + mutation := newLinUserMutation(c.config, OpUpdate) + return &LinUserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinUserClient) UpdateOne(lu *LinUser) *LinUserUpdateOne { + mutation := newLinUserMutation(c.config, OpUpdateOne, withLinUser(lu)) + return &LinUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinUserClient) UpdateOneID(id int) *LinUserUpdateOne { + mutation := newLinUserMutation(c.config, OpUpdateOne, withLinUserID(id)) + return &LinUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinUser. +func (c *LinUserClient) Delete() *LinUserDelete { + mutation := newLinUserMutation(c.config, OpDelete) + return &LinUserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinUserClient) DeleteOne(lu *LinUser) *LinUserDeleteOne { + return c.DeleteOneID(lu.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinUserClient) DeleteOneID(id int) *LinUserDeleteOne { + builder := c.Delete().Where(linuser.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinUserDeleteOne{builder} +} + +// Query returns a query builder for LinUser. +func (c *LinUserClient) Query() *LinUserQuery { + return &LinUserQuery{ + config: c.config, + } +} + +// Get returns a LinUser entity by its id. +func (c *LinUserClient) Get(ctx context.Context, id int) (*LinUser, error) { + return c.Query().Where(linuser.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinUserClient) GetX(ctx context.Context, id int) *LinUser { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinUserIdentiy queries the lin_user_identiy edge of a LinUser. +func (c *LinUserClient) QueryLinUserIdentiy(lu *LinUser) *LinUserIdentiyQuery { + query := &LinUserIdentiyQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lu.ID + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, id), + sqlgraph.To(linuseridentiy.Table, linuseridentiy.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, linuser.LinUserIdentiyTable, linuser.LinUserIdentiyColumn), + ) + fromV = sqlgraph.Neighbors(lu.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLinGroup queries the lin_group edge of a LinUser. +func (c *LinUserClient) QueryLinGroup(lu *LinUser) *LinGroupQuery { + query := &LinGroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := lu.ID + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, id), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, linuser.LinGroupTable, linuser.LinGroupPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(lu.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinUserClient) Hooks() []Hook { + return c.hooks.LinUser +} + +// LinUserIdentiyClient is a client for the LinUserIdentiy schema. +type LinUserIdentiyClient struct { + config +} + +// NewLinUserIdentiyClient returns a client for the LinUserIdentiy from the given config. +func NewLinUserIdentiyClient(c config) *LinUserIdentiyClient { + return &LinUserIdentiyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `linuseridentiy.Hooks(f(g(h())))`. +func (c *LinUserIdentiyClient) Use(hooks ...Hook) { + c.hooks.LinUserIdentiy = append(c.hooks.LinUserIdentiy, hooks...) +} + +// Create returns a create builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Create() *LinUserIdentiyCreate { + mutation := newLinUserIdentiyMutation(c.config, OpCreate) + return &LinUserIdentiyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LinUserIdentiy entities. +func (c *LinUserIdentiyClient) CreateBulk(builders ...*LinUserIdentiyCreate) *LinUserIdentiyCreateBulk { + return &LinUserIdentiyCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Update() *LinUserIdentiyUpdate { + mutation := newLinUserIdentiyMutation(c.config, OpUpdate) + return &LinUserIdentiyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinUserIdentiyClient) UpdateOne(lui *LinUserIdentiy) *LinUserIdentiyUpdateOne { + mutation := newLinUserIdentiyMutation(c.config, OpUpdateOne, withLinUserIdentiy(lui)) + return &LinUserIdentiyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinUserIdentiyClient) UpdateOneID(id int) *LinUserIdentiyUpdateOne { + mutation := newLinUserIdentiyMutation(c.config, OpUpdateOne, withLinUserIdentiyID(id)) + return &LinUserIdentiyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Delete() *LinUserIdentiyDelete { + mutation := newLinUserIdentiyMutation(c.config, OpDelete) + return &LinUserIdentiyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *LinUserIdentiyClient) DeleteOne(lui *LinUserIdentiy) *LinUserIdentiyDeleteOne { + return c.DeleteOneID(lui.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *LinUserIdentiyClient) DeleteOneID(id int) *LinUserIdentiyDeleteOne { + builder := c.Delete().Where(linuseridentiy.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinUserIdentiyDeleteOne{builder} +} + +// Query returns a query builder for LinUserIdentiy. +func (c *LinUserIdentiyClient) Query() *LinUserIdentiyQuery { + return &LinUserIdentiyQuery{ + config: c.config, + } +} + +// Get returns a LinUserIdentiy entity by its id. +func (c *LinUserIdentiyClient) Get(ctx context.Context, id int) (*LinUserIdentiy, error) { + return c.Query().Where(linuseridentiy.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinUserIdentiyClient) GetX(ctx context.Context, id int) *LinUserIdentiy { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LinUserIdentiyClient) Hooks() []Hook { + return c.hooks.LinUserIdentiy +} diff --git a/internal/data/model/config.go b/internal/data/model/config.go new file mode 100644 index 0000000..766e15d --- /dev/null +++ b/internal/data/model/config.go @@ -0,0 +1,65 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" +) + +// Option function to configure the client. +type Option func(*config) + +// Config is the configuration for the client and its builder. +type config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...interface{}) + // hooks to execute on mutations. + hooks *hooks +} + +// hooks per client, for fast access. +type hooks struct { + Book []ent.Hook + LinFile []ent.Hook + LinGroup []ent.Hook + LinLog []ent.Hook + LinPermission []ent.Hook + LinUser []ent.Hook + LinUserIdentiy []ent.Hook +} + +// Options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...interface{})) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} diff --git a/internal/data/model/context.go b/internal/data/model/context.go new file mode 100644 index 0000000..37c8e62 --- /dev/null +++ b/internal/data/model/context.go @@ -0,0 +1,33 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} diff --git a/internal/data/model/ent.go b/internal/data/model/ent.go new file mode 100644 index 0000000..79c1b13 --- /dev/null +++ b/internal/data/model/ent.go @@ -0,0 +1,271 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +// OrderFunc applies an ordering on the sql selector. +type OrderFunc func(*sql.Selector) + +// columnChecker returns a function indicates if the column exists in the given column. +func columnChecker(table string) func(string) error { + checks := map[string]func(string) bool{ + book.Table: book.ValidColumn, + linfile.Table: linfile.ValidColumn, + lingroup.Table: lingroup.ValidColumn, + linlog.Table: linlog.ValidColumn, + linpermission.Table: linpermission.ValidColumn, + linuser.Table: linuser.ValidColumn, + linuseridentiy.Table: linuseridentiy.ValidColumn, + } + check, ok := checks[table] + if !ok { + return func(string) error { + return fmt.Errorf("unknown table %q", table) + } + } + return func(column string) error { + if !check(column) { + return fmt.Errorf("unknown column %q for table %q", column, table) + } + return nil + } +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("model: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("model: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(model.As(model.Sum(field1), "sum_field1"), (model.As(model.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +// +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("model: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "model: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "model: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "model: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "model: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} diff --git a/internal/data/model/enttest/enttest.go b/internal/data/model/enttest/enttest.go new file mode 100644 index 0000000..ea44042 --- /dev/null +++ b/internal/data/model/enttest/enttest.go @@ -0,0 +1,77 @@ +// Code generated by entc, DO NOT EDIT. + +package enttest + +import ( + "context" + "lin-cms-go/internal/data/model" + // required by schema hooks. + _ "lin-cms-go/internal/data/model/runtime" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...interface{}) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []model.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...model.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls model.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *model.Client { + o := newOptions(opts) + c, err := model.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} + +// NewClient calls model.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *model.Client { + o := newOptions(opts) + c := model.NewClient(o.opts...) + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} diff --git a/internal/data/model/hook/hook.go b/internal/data/model/hook/hook.go new file mode 100644 index 0000000..74af3f4 --- /dev/null +++ b/internal/data/model/hook/hook.go @@ -0,0 +1,281 @@ +// Code generated by entc, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model" +) + +// The BookFunc type is an adapter to allow the use of ordinary +// function as Book mutator. +type BookFunc func(context.Context, *model.BookMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f BookFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.BookMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.BookMutation", m) + } + return f(ctx, mv) +} + +// The LinFileFunc type is an adapter to allow the use of ordinary +// function as LinFile mutator. +type LinFileFunc func(context.Context, *model.LinFileMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinFileFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinFileMutation", m) + } + return f(ctx, mv) +} + +// The LinGroupFunc type is an adapter to allow the use of ordinary +// function as LinGroup mutator. +type LinGroupFunc func(context.Context, *model.LinGroupMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinGroupFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinGroupMutation", m) + } + return f(ctx, mv) +} + +// The LinLogFunc type is an adapter to allow the use of ordinary +// function as LinLog mutator. +type LinLogFunc func(context.Context, *model.LinLogMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinLogFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinLogMutation", m) + } + return f(ctx, mv) +} + +// The LinPermissionFunc type is an adapter to allow the use of ordinary +// function as LinPermission mutator. +type LinPermissionFunc func(context.Context, *model.LinPermissionMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinPermissionFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinPermissionMutation", m) + } + return f(ctx, mv) +} + +// The LinUserFunc type is an adapter to allow the use of ordinary +// function as LinUser mutator. +type LinUserFunc func(context.Context, *model.LinUserMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinUserFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinUserMutation", m) + } + return f(ctx, mv) +} + +// The LinUserIdentiyFunc type is an adapter to allow the use of ordinary +// function as LinUserIdentiy mutator. +type LinUserIdentiyFunc func(context.Context, *model.LinUserIdentiyMutation) (model.Value, error) + +// Mutate calls f(ctx, m). +func (f LinUserIdentiyFunc) Mutate(ctx context.Context, m model.Mutation) (model.Value, error) { + mv, ok := m.(*model.LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *model.LinUserIdentiyMutation", m) + } + return f(ctx, mv) +} + +// Condition is a hook condition function. +type Condition func(context.Context, model.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m model.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m model.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m model.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op model.Op) Condition { + return func(_ context.Context, m model.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m model.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m model.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m model.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +// +func If(hk model.Hook, cond Condition) model.Hook { + return func(next model.Mutator) model.Mutator { + return model.MutateFunc(func(ctx context.Context, m model.Mutation) (model.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, model.Delete|model.Create) +// +func On(hk model.Hook, op model.Op) model.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, model.Update|model.UpdateOne) +// +func Unless(hk model.Hook, op model.Op) model.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) model.Hook { + return func(model.Mutator) model.Mutator { + return model.MutateFunc(func(context.Context, model.Mutation) (model.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []model.Hook { +// return []model.Hook{ +// Reject(model.Delete|model.Update), +// } +// } +// +func Reject(op model.Op) model.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []model.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...model.Hook) Chain { + return Chain{append([]model.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() model.Hook { + return func(mutator model.Mutator) model.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...model.Hook) Chain { + newHooks := make([]model.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/internal/data/model/linfile.go b/internal/data/model/linfile.go new file mode 100644 index 0000000..56803ca --- /dev/null +++ b/internal/data/model/linfile.go @@ -0,0 +1,151 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linfile" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinFile is the model entity for the LinFile schema. +type LinFile struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // Type holds the value of the "type" field. + // 1 LOCAL 本地,2 REMOTE 远程 + Type int8 `json:"type,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Extension holds the value of the "extension" field. + Extension string `json:"extension,omitempty"` + // Size holds the value of the "size" field. + Size int `json:"size,omitempty"` + // Md5 holds the value of the "md5" field. + // md5值,防止上传重复文件 + Md5 string `json:"md5,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinFile) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linfile.FieldID, linfile.FieldType, linfile.FieldSize: + values[i] = new(sql.NullInt64) + case linfile.FieldPath, linfile.FieldName, linfile.FieldExtension, linfile.FieldMd5: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type LinFile", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinFile fields. +func (lf *LinFile) assignValues(columns []string, values []interface{}) 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 linfile.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lf.ID = int(value.Int64) + case linfile.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + lf.Path = value.String + } + case linfile.FieldType: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + lf.Type = int8(value.Int64) + } + case linfile.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + lf.Name = value.String + } + case linfile.FieldExtension: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field extension", values[i]) + } else if value.Valid { + lf.Extension = value.String + } + case linfile.FieldSize: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field size", values[i]) + } else if value.Valid { + lf.Size = int(value.Int64) + } + case linfile.FieldMd5: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field md5", values[i]) + } else if value.Valid { + lf.Md5 = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this LinFile. +// Note that you need to call LinFile.Unwrap() before calling this method if this LinFile +// was returned from a transaction, and the transaction was committed or rolled back. +func (lf *LinFile) Update() *LinFileUpdateOne { + return (&LinFileClient{config: lf.config}).UpdateOne(lf) +} + +// Unwrap unwraps the LinFile 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 (lf *LinFile) Unwrap() *LinFile { + tx, ok := lf.config.driver.(*txDriver) + if !ok { + panic("model: LinFile is not a transactional entity") + } + lf.config.driver = tx.drv + return lf +} + +// String implements the fmt.Stringer. +func (lf *LinFile) String() string { + var builder strings.Builder + builder.WriteString("LinFile(") + builder.WriteString(fmt.Sprintf("id=%v", lf.ID)) + builder.WriteString(", path=") + builder.WriteString(lf.Path) + builder.WriteString(", type=") + builder.WriteString(fmt.Sprintf("%v", lf.Type)) + builder.WriteString(", name=") + builder.WriteString(lf.Name) + builder.WriteString(", extension=") + builder.WriteString(lf.Extension) + builder.WriteString(", size=") + builder.WriteString(fmt.Sprintf("%v", lf.Size)) + builder.WriteString(", md5=") + builder.WriteString(lf.Md5) + builder.WriteByte(')') + return builder.String() +} + +// LinFiles is a parsable slice of LinFile. +type LinFiles []*LinFile + +func (lf LinFiles) config(cfg config) { + for _i := range lf { + lf[_i].config = cfg + } +} diff --git a/internal/data/model/linfile/linfile.go b/internal/data/model/linfile/linfile.go new file mode 100644 index 0000000..a5da84e --- /dev/null +++ b/internal/data/model/linfile/linfile.go @@ -0,0 +1,45 @@ +// Code generated by entc, DO NOT EDIT. + +package linfile + +const ( + // Label holds the string label denoting the linfile type in the database. + Label = "lin_file" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldExtension holds the string denoting the extension field in the database. + FieldExtension = "extension" + // FieldSize holds the string denoting the size field in the database. + FieldSize = "size" + // FieldMd5 holds the string denoting the md5 field in the database. + FieldMd5 = "md5" + // Table holds the table name of the linfile in the database. + Table = "lin_file" +) + +// Columns holds all SQL columns for linfile fields. +var Columns = []string{ + FieldID, + FieldPath, + FieldType, + FieldName, + FieldExtension, + FieldSize, + FieldMd5, +} + +// 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 +} diff --git a/internal/data/model/linfile/where.go b/internal/data/model/linfile/where.go new file mode 100644 index 0000000..7d1c3b1 --- /dev/null +++ b/internal/data/model/linfile/where.go @@ -0,0 +1,762 @@ +// Code generated by entc, DO NOT EDIT. + +package linfile + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldType), v)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Extension applies equality check predicate on the "extension" field. It's identical to ExtensionEQ. +func Extension(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldExtension), v)) + }) +} + +// Size applies equality check predicate on the "size" field. It's identical to SizeEQ. +func Size(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSize), v)) + }) +} + +// Md5 applies equality check predicate on the "md5" field. It's identical to Md5EQ. +func Md5(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMd5), v)) + }) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPath), v)) + }) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPath), v...)) + }) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPath), v...)) + }) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPath), v)) + }) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPath), v)) + }) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPath), v)) + }) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPath), v)) + }) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldPath), v)) + }) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldPath), v)) + }) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldPath), v)) + }) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldPath), v)) + }) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldPath), v)) + }) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldType), v)) + }) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldType), v)) + }) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...int8) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldType), v...)) + }) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...int8) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldType), v...)) + }) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldType), v)) + }) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldType), v)) + }) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldType), v)) + }) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v int8) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldType), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// ExtensionEQ applies the EQ predicate on the "extension" field. +func ExtensionEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldExtension), v)) + }) +} + +// ExtensionNEQ applies the NEQ predicate on the "extension" field. +func ExtensionNEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldExtension), v)) + }) +} + +// ExtensionIn applies the In predicate on the "extension" field. +func ExtensionIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldExtension), v...)) + }) +} + +// ExtensionNotIn applies the NotIn predicate on the "extension" field. +func ExtensionNotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldExtension), v...)) + }) +} + +// ExtensionGT applies the GT predicate on the "extension" field. +func ExtensionGT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldExtension), v)) + }) +} + +// ExtensionGTE applies the GTE predicate on the "extension" field. +func ExtensionGTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldExtension), v)) + }) +} + +// ExtensionLT applies the LT predicate on the "extension" field. +func ExtensionLT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldExtension), v)) + }) +} + +// ExtensionLTE applies the LTE predicate on the "extension" field. +func ExtensionLTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldExtension), v)) + }) +} + +// ExtensionContains applies the Contains predicate on the "extension" field. +func ExtensionContains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldExtension), v)) + }) +} + +// ExtensionHasPrefix applies the HasPrefix predicate on the "extension" field. +func ExtensionHasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldExtension), v)) + }) +} + +// ExtensionHasSuffix applies the HasSuffix predicate on the "extension" field. +func ExtensionHasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldExtension), v)) + }) +} + +// ExtensionEqualFold applies the EqualFold predicate on the "extension" field. +func ExtensionEqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldExtension), v)) + }) +} + +// ExtensionContainsFold applies the ContainsFold predicate on the "extension" field. +func ExtensionContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldExtension), v)) + }) +} + +// SizeEQ applies the EQ predicate on the "size" field. +func SizeEQ(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldSize), v)) + }) +} + +// SizeNEQ applies the NEQ predicate on the "size" field. +func SizeNEQ(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldSize), v)) + }) +} + +// SizeIn applies the In predicate on the "size" field. +func SizeIn(vs ...int) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldSize), v...)) + }) +} + +// SizeNotIn applies the NotIn predicate on the "size" field. +func SizeNotIn(vs ...int) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldSize), v...)) + }) +} + +// SizeGT applies the GT predicate on the "size" field. +func SizeGT(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldSize), v)) + }) +} + +// SizeGTE applies the GTE predicate on the "size" field. +func SizeGTE(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldSize), v)) + }) +} + +// SizeLT applies the LT predicate on the "size" field. +func SizeLT(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldSize), v)) + }) +} + +// SizeLTE applies the LTE predicate on the "size" field. +func SizeLTE(v int) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldSize), v)) + }) +} + +// Md5EQ applies the EQ predicate on the "md5" field. +func Md5EQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMd5), v)) + }) +} + +// Md5NEQ applies the NEQ predicate on the "md5" field. +func Md5NEQ(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMd5), v)) + }) +} + +// Md5In applies the In predicate on the "md5" field. +func Md5In(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMd5), v...)) + }) +} + +// Md5NotIn applies the NotIn predicate on the "md5" field. +func Md5NotIn(vs ...string) predicate.LinFile { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinFile(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMd5), v...)) + }) +} + +// Md5GT applies the GT predicate on the "md5" field. +func Md5GT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMd5), v)) + }) +} + +// Md5GTE applies the GTE predicate on the "md5" field. +func Md5GTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMd5), v)) + }) +} + +// Md5LT applies the LT predicate on the "md5" field. +func Md5LT(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMd5), v)) + }) +} + +// Md5LTE applies the LTE predicate on the "md5" field. +func Md5LTE(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMd5), v)) + }) +} + +// Md5Contains applies the Contains predicate on the "md5" field. +func Md5Contains(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldMd5), v)) + }) +} + +// Md5HasPrefix applies the HasPrefix predicate on the "md5" field. +func Md5HasPrefix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldMd5), v)) + }) +} + +// Md5HasSuffix applies the HasSuffix predicate on the "md5" field. +func Md5HasSuffix(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldMd5), v)) + }) +} + +// Md5EqualFold applies the EqualFold predicate on the "md5" field. +func Md5EqualFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldMd5), v)) + }) +} + +// Md5ContainsFold applies the ContainsFold predicate on the "md5" field. +func Md5ContainsFold(v string) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldMd5), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinFile) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinFile) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinFile) predicate.LinFile { + return predicate.LinFile(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linfile_create.go b/internal/data/model/linfile_create.go new file mode 100644 index 0000000..617d719 --- /dev/null +++ b/internal/data/model/linfile_create.go @@ -0,0 +1,305 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linfile" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileCreate is the builder for creating a LinFile entity. +type LinFileCreate struct { + config + mutation *LinFileMutation + hooks []Hook +} + +// SetPath sets the "path" field. +func (lfc *LinFileCreate) SetPath(s string) *LinFileCreate { + lfc.mutation.SetPath(s) + return lfc +} + +// SetType sets the "type" field. +func (lfc *LinFileCreate) SetType(i int8) *LinFileCreate { + lfc.mutation.SetType(i) + return lfc +} + +// SetName sets the "name" field. +func (lfc *LinFileCreate) SetName(s string) *LinFileCreate { + lfc.mutation.SetName(s) + return lfc +} + +// SetExtension sets the "extension" field. +func (lfc *LinFileCreate) SetExtension(s string) *LinFileCreate { + lfc.mutation.SetExtension(s) + return lfc +} + +// SetSize sets the "size" field. +func (lfc *LinFileCreate) SetSize(i int) *LinFileCreate { + lfc.mutation.SetSize(i) + return lfc +} + +// SetMd5 sets the "md5" field. +func (lfc *LinFileCreate) SetMd5(s string) *LinFileCreate { + lfc.mutation.SetMd5(s) + return lfc +} + +// Mutation returns the LinFileMutation object of the builder. +func (lfc *LinFileCreate) Mutation() *LinFileMutation { + return lfc.mutation +} + +// Save creates the LinFile in the database. +func (lfc *LinFileCreate) Save(ctx context.Context) (*LinFile, error) { + var ( + err error + node *LinFile + ) + if len(lfc.hooks) == 0 { + if err = lfc.check(); err != nil { + return nil, err + } + node, err = lfc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lfc.check(); err != nil { + return nil, err + } + lfc.mutation = mutation + if node, err = lfc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lfc.hooks) - 1; i >= 0; i-- { + if lfc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lfc *LinFileCreate) SaveX(ctx context.Context) *LinFile { + v, err := lfc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lfc *LinFileCreate) Exec(ctx context.Context) error { + _, err := lfc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfc *LinFileCreate) ExecX(ctx context.Context) { + if err := lfc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lfc *LinFileCreate) check() error { + if _, ok := lfc.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`model: missing required field "path"`)} + } + if _, ok := lfc.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`model: missing required field "type"`)} + } + if _, ok := lfc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} + } + if _, ok := lfc.mutation.Extension(); !ok { + return &ValidationError{Name: "extension", err: errors.New(`model: missing required field "extension"`)} + } + if _, ok := lfc.mutation.Size(); !ok { + return &ValidationError{Name: "size", err: errors.New(`model: missing required field "size"`)} + } + if _, ok := lfc.mutation.Md5(); !ok { + return &ValidationError{Name: "md5", err: errors.New(`model: missing required field "md5"`)} + } + return nil +} + +func (lfc *LinFileCreate) sqlSave(ctx context.Context) (*LinFile, error) { + _node, _spec := lfc.createSpec() + if err := sqlgraph.CreateNode(ctx, lfc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lfc *LinFileCreate) createSpec() (*LinFile, *sqlgraph.CreateSpec) { + var ( + _node = &LinFile{config: lfc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linfile.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + } + ) + if value, ok := lfc.mutation.Path(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldPath, + }) + _node.Path = value + } + if value, ok := lfc.mutation.GetType(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + _node.Type = value + } + if value, ok := lfc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldName, + }) + _node.Name = value + } + if value, ok := lfc.mutation.Extension(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldExtension, + }) + _node.Extension = value + } + if value, ok := lfc.mutation.Size(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + _node.Size = value + } + if value, ok := lfc.mutation.Md5(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldMd5, + }) + _node.Md5 = value + } + return _node, _spec +} + +// LinFileCreateBulk is the builder for creating many LinFile entities in bulk. +type LinFileCreateBulk struct { + config + builders []*LinFileCreate +} + +// Save creates the LinFile entities in the database. +func (lfcb *LinFileCreateBulk) Save(ctx context.Context) ([]*LinFile, error) { + specs := make([]*sqlgraph.CreateSpec, len(lfcb.builders)) + nodes := make([]*LinFile, len(lfcb.builders)) + mutators := make([]Mutator, len(lfcb.builders)) + for i := range lfcb.builders { + func(i int, root context.Context) { + builder := lfcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lfcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lfcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lfcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lfcb *LinFileCreateBulk) SaveX(ctx context.Context) []*LinFile { + v, err := lfcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lfcb *LinFileCreateBulk) Exec(ctx context.Context) error { + _, err := lfcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfcb *LinFileCreateBulk) ExecX(ctx context.Context) { + if err := lfcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linfile_delete.go b/internal/data/model/linfile_delete.go new file mode 100644 index 0000000..f767b58 --- /dev/null +++ b/internal/data/model/linfile_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileDelete is the builder for deleting a LinFile entity. +type LinFileDelete struct { + config + hooks []Hook + mutation *LinFileMutation +} + +// Where appends a list predicates to the LinFileDelete builder. +func (lfd *LinFileDelete) Where(ps ...predicate.LinFile) *LinFileDelete { + lfd.mutation.Where(ps...) + return lfd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lfd *LinFileDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lfd.hooks) == 0 { + affected, err = lfd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lfd.mutation = mutation + affected, err = lfd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lfd.hooks) - 1; i >= 0; i-- { + if lfd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfd *LinFileDelete) ExecX(ctx context.Context) int { + n, err := lfd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lfd *LinFileDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + } + if ps := lfd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lfd.driver, _spec) +} + +// LinFileDeleteOne is the builder for deleting a single LinFile entity. +type LinFileDeleteOne struct { + lfd *LinFileDelete +} + +// Exec executes the deletion query. +func (lfdo *LinFileDeleteOne) Exec(ctx context.Context) error { + n, err := lfdo.lfd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linfile.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfdo *LinFileDeleteOne) ExecX(ctx context.Context) { + lfdo.lfd.ExecX(ctx) +} diff --git a/internal/data/model/linfile_query.go b/internal/data/model/linfile_query.go new file mode 100644 index 0000000..43a7c54 --- /dev/null +++ b/internal/data/model/linfile_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileQuery is the builder for querying LinFile entities. +type LinFileQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinFile + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinFileQuery builder. +func (lfq *LinFileQuery) Where(ps ...predicate.LinFile) *LinFileQuery { + lfq.predicates = append(lfq.predicates, ps...) + return lfq +} + +// Limit adds a limit step to the query. +func (lfq *LinFileQuery) Limit(limit int) *LinFileQuery { + lfq.limit = &limit + return lfq +} + +// Offset adds an offset step to the query. +func (lfq *LinFileQuery) Offset(offset int) *LinFileQuery { + lfq.offset = &offset + return lfq +} + +// 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 (lfq *LinFileQuery) Unique(unique bool) *LinFileQuery { + lfq.unique = &unique + return lfq +} + +// Order adds an order step to the query. +func (lfq *LinFileQuery) Order(o ...OrderFunc) *LinFileQuery { + lfq.order = append(lfq.order, o...) + return lfq +} + +// First returns the first LinFile entity from the query. +// Returns a *NotFoundError when no LinFile was found. +func (lfq *LinFileQuery) First(ctx context.Context) (*LinFile, error) { + nodes, err := lfq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linfile.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lfq *LinFileQuery) FirstX(ctx context.Context) *LinFile { + node, err := lfq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinFile ID from the query. +// Returns a *NotFoundError when no LinFile ID was found. +func (lfq *LinFileQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lfq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linfile.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lfq *LinFileQuery) FirstIDX(ctx context.Context) int { + id, err := lfq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinFile entity from the query. +// Returns a *NotFoundError when no LinFile was found. +func (lfq *LinFileQuery) Last(ctx context.Context) (*LinFile, error) { + nodes, err := lfq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linfile.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lfq *LinFileQuery) LastX(ctx context.Context) *LinFile { + node, err := lfq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinFile ID from the query. +// Returns a *NotFoundError when no LinFile ID was found. +func (lfq *LinFileQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lfq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linfile.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lfq *LinFileQuery) LastIDX(ctx context.Context) int { + id, err := lfq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinFile entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinFile entity is not found. +// Returns a *NotFoundError when no LinFile entities are found. +func (lfq *LinFileQuery) Only(ctx context.Context) (*LinFile, error) { + nodes, err := lfq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linfile.Label} + default: + return nil, &NotSingularError{linfile.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lfq *LinFileQuery) OnlyX(ctx context.Context) *LinFile { + node, err := lfq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinFile ID in the query. +// Returns a *NotSingularError when exactly one LinFile ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lfq *LinFileQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lfq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linfile.Label} + default: + err = &NotSingularError{linfile.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lfq *LinFileQuery) OnlyIDX(ctx context.Context) int { + id, err := lfq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinFiles. +func (lfq *LinFileQuery) All(ctx context.Context) ([]*LinFile, error) { + if err := lfq.prepareQuery(ctx); err != nil { + return nil, err + } + return lfq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lfq *LinFileQuery) AllX(ctx context.Context) []*LinFile { + nodes, err := lfq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinFile IDs. +func (lfq *LinFileQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lfq.Select(linfile.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lfq *LinFileQuery) IDsX(ctx context.Context) []int { + ids, err := lfq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lfq *LinFileQuery) Count(ctx context.Context) (int, error) { + if err := lfq.prepareQuery(ctx); err != nil { + return 0, err + } + return lfq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lfq *LinFileQuery) CountX(ctx context.Context) int { + count, err := lfq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lfq *LinFileQuery) Exist(ctx context.Context) (bool, error) { + if err := lfq.prepareQuery(ctx); err != nil { + return false, err + } + return lfq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lfq *LinFileQuery) ExistX(ctx context.Context) bool { + exist, err := lfq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinFileQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lfq *LinFileQuery) Clone() *LinFileQuery { + if lfq == nil { + return nil + } + return &LinFileQuery{ + config: lfq.config, + limit: lfq.limit, + offset: lfq.offset, + order: append([]OrderFunc{}, lfq.order...), + predicates: append([]predicate.LinFile{}, lfq.predicates...), + // clone intermediate query. + sql: lfq.sql.Clone(), + path: lfq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Path string `json:"path,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinFile.Query(). +// GroupBy(linfile.FieldPath). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lfq *LinFileQuery) GroupBy(field string, fields ...string) *LinFileGroupBy { + group := &LinFileGroupBy{config: lfq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lfq.prepareQuery(ctx); err != nil { + return nil, err + } + return lfq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Path string `json:"path,omitempty"` +// } +// +// client.LinFile.Query(). +// Select(linfile.FieldPath). +// Scan(ctx, &v) +// +func (lfq *LinFileQuery) Select(fields ...string) *LinFileSelect { + lfq.fields = append(lfq.fields, fields...) + return &LinFileSelect{LinFileQuery: lfq} +} + +func (lfq *LinFileQuery) prepareQuery(ctx context.Context) error { + for _, f := range lfq.fields { + if !linfile.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lfq.path != nil { + prev, err := lfq.path(ctx) + if err != nil { + return err + } + lfq.sql = prev + } + return nil +} + +func (lfq *LinFileQuery) sqlAll(ctx context.Context) ([]*LinFile, error) { + var ( + nodes = []*LinFile{} + _spec = lfq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinFile{config: lfq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lfq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (lfq *LinFileQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lfq.querySpec() + return sqlgraph.CountNodes(ctx, lfq.driver, _spec) +} + +func (lfq *LinFileQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lfq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lfq *LinFileQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + Columns: linfile.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + From: lfq.sql, + Unique: true, + } + if unique := lfq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lfq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linfile.FieldID) + for i := range fields { + if fields[i] != linfile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lfq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lfq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lfq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lfq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lfq *LinFileQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lfq.driver.Dialect()) + t1 := builder.Table(linfile.Table) + columns := lfq.fields + if len(columns) == 0 { + columns = linfile.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lfq.sql != nil { + selector = lfq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lfq.predicates { + p(selector) + } + for _, p := range lfq.order { + p(selector) + } + if offset := lfq.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 := lfq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinFileGroupBy is the group-by builder for LinFile entities. +type LinFileGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lfgb *LinFileGroupBy) Aggregate(fns ...AggregateFunc) *LinFileGroupBy { + lfgb.fns = append(lfgb.fns, fns...) + return lfgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lfgb *LinFileGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lfgb.path(ctx) + if err != nil { + return err + } + lfgb.sql = query + return lfgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lfgb *LinFileGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lfgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lfgb *LinFileGroupBy) StringsX(ctx context.Context) []string { + v, err := lfgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lfgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lfgb *LinFileGroupBy) StringX(ctx context.Context) string { + v, err := lfgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lfgb *LinFileGroupBy) IntsX(ctx context.Context) []int { + v, err := lfgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lfgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lfgb *LinFileGroupBy) IntX(ctx context.Context) int { + v, err := lfgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lfgb *LinFileGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lfgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lfgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lfgb *LinFileGroupBy) Float64X(ctx context.Context) float64 { + v, err := lfgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lfgb.fields) > 1 { + return nil, errors.New("model: LinFileGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lfgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lfgb *LinFileGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lfgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lfgb *LinFileGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lfgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lfgb *LinFileGroupBy) BoolX(ctx context.Context) bool { + v, err := lfgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lfgb *LinFileGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lfgb.fields { + if !linfile.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lfgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lfgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lfgb *LinFileGroupBy) sqlQuery() *sql.Selector { + selector := lfgb.sql.Select() + aggregation := make([]string, 0, len(lfgb.fns)) + for _, fn := range lfgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lfgb.fields)+len(lfgb.fns)) + for _, f := range lfgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lfgb.fields...)...) +} + +// LinFileSelect is the builder for selecting fields of LinFile entities. +type LinFileSelect struct { + *LinFileQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lfs *LinFileSelect) Scan(ctx context.Context, v interface{}) error { + if err := lfs.prepareQuery(ctx); err != nil { + return err + } + lfs.sql = lfs.LinFileQuery.sqlQuery(ctx) + return lfs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lfs *LinFileSelect) ScanX(ctx context.Context, v interface{}) { + if err := lfs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Strings(ctx context.Context) ([]string, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lfs *LinFileSelect) StringsX(ctx context.Context) []string { + v, err := lfs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lfs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lfs *LinFileSelect) StringX(ctx context.Context) string { + v, err := lfs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Ints(ctx context.Context) ([]int, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lfs *LinFileSelect) IntsX(ctx context.Context) []int { + v, err := lfs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lfs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lfs *LinFileSelect) IntX(ctx context.Context) int { + v, err := lfs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lfs *LinFileSelect) Float64sX(ctx context.Context) []float64 { + v, err := lfs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lfs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lfs *LinFileSelect) Float64X(ctx context.Context) float64 { + v, err := lfs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lfs.fields) > 1 { + return nil, errors.New("model: LinFileSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lfs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lfs *LinFileSelect) BoolsX(ctx context.Context) []bool { + v, err := lfs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lfs *LinFileSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lfs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linfile.Label} + default: + err = fmt.Errorf("model: LinFileSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lfs *LinFileSelect) BoolX(ctx context.Context) bool { + v, err := lfs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lfs *LinFileSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lfs.sql.Query() + if err := lfs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linfile_update.go b/internal/data/model/linfile_update.go new file mode 100644 index 0000000..d640e3a --- /dev/null +++ b/internal/data/model/linfile_update.go @@ -0,0 +1,450 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinFileUpdate is the builder for updating LinFile entities. +type LinFileUpdate struct { + config + hooks []Hook + mutation *LinFileMutation +} + +// Where appends a list predicates to the LinFileUpdate builder. +func (lfu *LinFileUpdate) Where(ps ...predicate.LinFile) *LinFileUpdate { + lfu.mutation.Where(ps...) + return lfu +} + +// SetPath sets the "path" field. +func (lfu *LinFileUpdate) SetPath(s string) *LinFileUpdate { + lfu.mutation.SetPath(s) + return lfu +} + +// SetType sets the "type" field. +func (lfu *LinFileUpdate) SetType(i int8) *LinFileUpdate { + lfu.mutation.ResetType() + lfu.mutation.SetType(i) + return lfu +} + +// AddType adds i to the "type" field. +func (lfu *LinFileUpdate) AddType(i int8) *LinFileUpdate { + lfu.mutation.AddType(i) + return lfu +} + +// SetName sets the "name" field. +func (lfu *LinFileUpdate) SetName(s string) *LinFileUpdate { + lfu.mutation.SetName(s) + return lfu +} + +// SetExtension sets the "extension" field. +func (lfu *LinFileUpdate) SetExtension(s string) *LinFileUpdate { + lfu.mutation.SetExtension(s) + return lfu +} + +// SetSize sets the "size" field. +func (lfu *LinFileUpdate) SetSize(i int) *LinFileUpdate { + lfu.mutation.ResetSize() + lfu.mutation.SetSize(i) + return lfu +} + +// AddSize adds i to the "size" field. +func (lfu *LinFileUpdate) AddSize(i int) *LinFileUpdate { + lfu.mutation.AddSize(i) + return lfu +} + +// SetMd5 sets the "md5" field. +func (lfu *LinFileUpdate) SetMd5(s string) *LinFileUpdate { + lfu.mutation.SetMd5(s) + return lfu +} + +// Mutation returns the LinFileMutation object of the builder. +func (lfu *LinFileUpdate) Mutation() *LinFileMutation { + return lfu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lfu *LinFileUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lfu.hooks) == 0 { + affected, err = lfu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lfu.mutation = mutation + affected, err = lfu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lfu.hooks) - 1; i >= 0; i-- { + if lfu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lfu *LinFileUpdate) SaveX(ctx context.Context) int { + affected, err := lfu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lfu *LinFileUpdate) Exec(ctx context.Context) error { + _, err := lfu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfu *LinFileUpdate) ExecX(ctx context.Context) { + if err := lfu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lfu *LinFileUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + Columns: linfile.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + } + if ps := lfu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lfu.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldPath, + }) + } + if value, ok := lfu.mutation.GetType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfu.mutation.AddedType(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldName, + }) + } + if value, ok := lfu.mutation.Extension(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldExtension, + }) + } + if value, ok := lfu.mutation.Size(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfu.mutation.AddedSize(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfu.mutation.Md5(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldMd5, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, lfu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linfile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinFileUpdateOne is the builder for updating a single LinFile entity. +type LinFileUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinFileMutation +} + +// SetPath sets the "path" field. +func (lfuo *LinFileUpdateOne) SetPath(s string) *LinFileUpdateOne { + lfuo.mutation.SetPath(s) + return lfuo +} + +// SetType sets the "type" field. +func (lfuo *LinFileUpdateOne) SetType(i int8) *LinFileUpdateOne { + lfuo.mutation.ResetType() + lfuo.mutation.SetType(i) + return lfuo +} + +// AddType adds i to the "type" field. +func (lfuo *LinFileUpdateOne) AddType(i int8) *LinFileUpdateOne { + lfuo.mutation.AddType(i) + return lfuo +} + +// SetName sets the "name" field. +func (lfuo *LinFileUpdateOne) SetName(s string) *LinFileUpdateOne { + lfuo.mutation.SetName(s) + return lfuo +} + +// SetExtension sets the "extension" field. +func (lfuo *LinFileUpdateOne) SetExtension(s string) *LinFileUpdateOne { + lfuo.mutation.SetExtension(s) + return lfuo +} + +// SetSize sets the "size" field. +func (lfuo *LinFileUpdateOne) SetSize(i int) *LinFileUpdateOne { + lfuo.mutation.ResetSize() + lfuo.mutation.SetSize(i) + return lfuo +} + +// AddSize adds i to the "size" field. +func (lfuo *LinFileUpdateOne) AddSize(i int) *LinFileUpdateOne { + lfuo.mutation.AddSize(i) + return lfuo +} + +// SetMd5 sets the "md5" field. +func (lfuo *LinFileUpdateOne) SetMd5(s string) *LinFileUpdateOne { + lfuo.mutation.SetMd5(s) + return lfuo +} + +// Mutation returns the LinFileMutation object of the builder. +func (lfuo *LinFileUpdateOne) Mutation() *LinFileMutation { + return lfuo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lfuo *LinFileUpdateOne) Select(field string, fields ...string) *LinFileUpdateOne { + lfuo.fields = append([]string{field}, fields...) + return lfuo +} + +// Save executes the query and returns the updated LinFile entity. +func (lfuo *LinFileUpdateOne) Save(ctx context.Context) (*LinFile, error) { + var ( + err error + node *LinFile + ) + if len(lfuo.hooks) == 0 { + node, err = lfuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinFileMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lfuo.mutation = mutation + node, err = lfuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lfuo.hooks) - 1; i >= 0; i-- { + if lfuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lfuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lfuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lfuo *LinFileUpdateOne) SaveX(ctx context.Context) *LinFile { + node, err := lfuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lfuo *LinFileUpdateOne) Exec(ctx context.Context) error { + _, err := lfuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lfuo *LinFileUpdateOne) ExecX(ctx context.Context) { + if err := lfuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lfuo *LinFileUpdateOne) sqlSave(ctx context.Context) (_node *LinFile, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linfile.Table, + Columns: linfile.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linfile.FieldID, + }, + }, + } + id, ok := lfuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinFile.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lfuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linfile.FieldID) + for _, f := range fields { + if !linfile.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linfile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lfuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lfuo.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldPath, + }) + } + if value, ok := lfuo.mutation.GetType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfuo.mutation.AddedType(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linfile.FieldType, + }) + } + if value, ok := lfuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldName, + }) + } + if value, ok := lfuo.mutation.Extension(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldExtension, + }) + } + if value, ok := lfuo.mutation.Size(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfuo.mutation.AddedSize(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linfile.FieldSize, + }) + } + if value, ok := lfuo.mutation.Md5(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linfile.FieldMd5, + }) + } + _node = &LinFile{config: lfuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lfuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linfile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/lingroup.go b/internal/data/model/lingroup.go new file mode 100644 index 0000000..6972969 --- /dev/null +++ b/internal/data/model/lingroup.go @@ -0,0 +1,164 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinGroup is the model entity for the LinGroup schema. +type LinGroup struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + // 分组名称,例如:搬砖者 + Name string `json:"name,omitempty"` + // Info holds the value of the "info" field. + // 分组信息:例如:搬砖的人 + Info string `json:"info,omitempty"` + // Level holds the value of the "level" field. + // 分组级别 1:root 2:guest 3:user(root、guest分组只能存在一个) + Level int8 `json:"level,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinGroupQuery when eager-loading is set. + Edges LinGroupEdges `json:"edges"` +} + +// LinGroupEdges holds the relations/edges for other nodes in the graph. +type LinGroupEdges struct { + // LinUser holds the value of the lin_user edge. + LinUser []*LinUser `json:"lin_user,omitempty"` + // LinPermission holds the value of the lin_permission edge. + LinPermission []*LinPermission `json:"lin_permission,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// LinUserOrErr returns the LinUser value or an error if the edge +// was not loaded in eager-loading. +func (e LinGroupEdges) LinUserOrErr() ([]*LinUser, error) { + if e.loadedTypes[0] { + return e.LinUser, nil + } + return nil, &NotLoadedError{edge: "lin_user"} +} + +// LinPermissionOrErr returns the LinPermission value or an error if the edge +// was not loaded in eager-loading. +func (e LinGroupEdges) LinPermissionOrErr() ([]*LinPermission, error) { + if e.loadedTypes[1] { + return e.LinPermission, nil + } + return nil, &NotLoadedError{edge: "lin_permission"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinGroup) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case lingroup.FieldID, lingroup.FieldLevel: + values[i] = new(sql.NullInt64) + case lingroup.FieldName, lingroup.FieldInfo: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type LinGroup", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinGroup fields. +func (lg *LinGroup) assignValues(columns []string, values []interface{}) 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 lingroup.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lg.ID = int(value.Int64) + case lingroup.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + lg.Name = value.String + } + case lingroup.FieldInfo: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field info", values[i]) + } else if value.Valid { + lg.Info = value.String + } + case lingroup.FieldLevel: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field level", values[i]) + } else if value.Valid { + lg.Level = int8(value.Int64) + } + } + } + return nil +} + +// QueryLinUser queries the "lin_user" edge of the LinGroup entity. +func (lg *LinGroup) QueryLinUser() *LinUserQuery { + return (&LinGroupClient{config: lg.config}).QueryLinUser(lg) +} + +// QueryLinPermission queries the "lin_permission" edge of the LinGroup entity. +func (lg *LinGroup) QueryLinPermission() *LinPermissionQuery { + return (&LinGroupClient{config: lg.config}).QueryLinPermission(lg) +} + +// Update returns a builder for updating this LinGroup. +// Note that you need to call LinGroup.Unwrap() before calling this method if this LinGroup +// was returned from a transaction, and the transaction was committed or rolled back. +func (lg *LinGroup) Update() *LinGroupUpdateOne { + return (&LinGroupClient{config: lg.config}).UpdateOne(lg) +} + +// Unwrap unwraps the LinGroup 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 (lg *LinGroup) Unwrap() *LinGroup { + tx, ok := lg.config.driver.(*txDriver) + if !ok { + panic("model: LinGroup is not a transactional entity") + } + lg.config.driver = tx.drv + return lg +} + +// String implements the fmt.Stringer. +func (lg *LinGroup) String() string { + var builder strings.Builder + builder.WriteString("LinGroup(") + builder.WriteString(fmt.Sprintf("id=%v", lg.ID)) + builder.WriteString(", name=") + builder.WriteString(lg.Name) + builder.WriteString(", info=") + builder.WriteString(lg.Info) + builder.WriteString(", level=") + builder.WriteString(fmt.Sprintf("%v", lg.Level)) + builder.WriteByte(')') + return builder.String() +} + +// LinGroups is a parsable slice of LinGroup. +type LinGroups []*LinGroup + +func (lg LinGroups) config(cfg config) { + for _i := range lg { + lg[_i].config = cfg + } +} diff --git a/internal/data/model/lingroup/lingroup.go b/internal/data/model/lingroup/lingroup.go new file mode 100644 index 0000000..9e1e505 --- /dev/null +++ b/internal/data/model/lingroup/lingroup.go @@ -0,0 +1,59 @@ +// Code generated by entc, DO NOT EDIT. + +package lingroup + +const ( + // Label holds the string label denoting the lingroup type in the database. + Label = "lin_group" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldInfo holds the string denoting the info field in the database. + FieldInfo = "info" + // FieldLevel holds the string denoting the level field in the database. + FieldLevel = "level" + // EdgeLinUser holds the string denoting the lin_user edge name in mutations. + EdgeLinUser = "lin_user" + // EdgeLinPermission holds the string denoting the lin_permission edge name in mutations. + EdgeLinPermission = "lin_permission" + // Table holds the table name of the lingroup in the database. + Table = "lin_group" + // LinUserTable is the table that holds the lin_user relation/edge. The primary key declared below. + LinUserTable = "lin_user_group" + // LinUserInverseTable is the table name for the LinUser entity. + // It exists in this package in order to avoid circular dependency with the "linuser" package. + LinUserInverseTable = "lin_user" + // LinPermissionTable is the table that holds the lin_permission relation/edge. The primary key declared below. + LinPermissionTable = "lin_group_permission" + // LinPermissionInverseTable is the table name for the LinPermission entity. + // It exists in this package in order to avoid circular dependency with the "linpermission" package. + LinPermissionInverseTable = "lin_permission" +) + +// Columns holds all SQL columns for lingroup fields. +var Columns = []string{ + FieldID, + FieldName, + FieldInfo, + FieldLevel, +} + +var ( + // LinUserPrimaryKey and LinUserColumn2 are the table columns denoting the + // primary key for the lin_user relation (M2M). + LinUserPrimaryKey = []string{"user_id", "group_id"} + // LinPermissionPrimaryKey and LinPermissionColumn2 are the table columns denoting the + // primary key for the lin_permission relation (M2M). + LinPermissionPrimaryKey = []string{"permission_id", "group_id"} +) + +// 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 +} diff --git a/internal/data/model/lingroup/where.go b/internal/data/model/lingroup/where.go new file mode 100644 index 0000000..d4c70dd --- /dev/null +++ b/internal/data/model/lingroup/where.go @@ -0,0 +1,500 @@ +// Code generated by entc, DO NOT EDIT. + +package lingroup + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Info applies equality check predicate on the "info" field. It's identical to InfoEQ. +func Info(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldInfo), v)) + }) +} + +// Level applies equality check predicate on the "level" field. It's identical to LevelEQ. +func Level(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldLevel), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// InfoEQ applies the EQ predicate on the "info" field. +func InfoEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldInfo), v)) + }) +} + +// InfoNEQ applies the NEQ predicate on the "info" field. +func InfoNEQ(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldInfo), v)) + }) +} + +// InfoIn applies the In predicate on the "info" field. +func InfoIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldInfo), v...)) + }) +} + +// InfoNotIn applies the NotIn predicate on the "info" field. +func InfoNotIn(vs ...string) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldInfo), v...)) + }) +} + +// InfoGT applies the GT predicate on the "info" field. +func InfoGT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldInfo), v)) + }) +} + +// InfoGTE applies the GTE predicate on the "info" field. +func InfoGTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldInfo), v)) + }) +} + +// InfoLT applies the LT predicate on the "info" field. +func InfoLT(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldInfo), v)) + }) +} + +// InfoLTE applies the LTE predicate on the "info" field. +func InfoLTE(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldInfo), v)) + }) +} + +// InfoContains applies the Contains predicate on the "info" field. +func InfoContains(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldInfo), v)) + }) +} + +// InfoHasPrefix applies the HasPrefix predicate on the "info" field. +func InfoHasPrefix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldInfo), v)) + }) +} + +// InfoHasSuffix applies the HasSuffix predicate on the "info" field. +func InfoHasSuffix(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldInfo), v)) + }) +} + +// InfoEqualFold applies the EqualFold predicate on the "info" field. +func InfoEqualFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldInfo), v)) + }) +} + +// InfoContainsFold applies the ContainsFold predicate on the "info" field. +func InfoContainsFold(v string) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldInfo), v)) + }) +} + +// LevelEQ applies the EQ predicate on the "level" field. +func LevelEQ(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldLevel), v)) + }) +} + +// LevelNEQ applies the NEQ predicate on the "level" field. +func LevelNEQ(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldLevel), v)) + }) +} + +// LevelIn applies the In predicate on the "level" field. +func LevelIn(vs ...int8) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldLevel), v...)) + }) +} + +// LevelNotIn applies the NotIn predicate on the "level" field. +func LevelNotIn(vs ...int8) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldLevel), v...)) + }) +} + +// LevelGT applies the GT predicate on the "level" field. +func LevelGT(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldLevel), v)) + }) +} + +// LevelGTE applies the GTE predicate on the "level" field. +func LevelGTE(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldLevel), v)) + }) +} + +// LevelLT applies the LT predicate on the "level" field. +func LevelLT(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldLevel), v)) + }) +} + +// LevelLTE applies the LTE predicate on the "level" field. +func LevelLTE(v int8) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldLevel), v)) + }) +} + +// HasLinUser applies the HasEdge predicate on the "lin_user" edge. +func HasLinUser() predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinUserTable, LinUserPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinUserWith applies the HasEdge predicate on the "lin_user" edge with a given conditions (other predicates). +func HasLinUserWith(preds ...predicate.LinUser) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinUserTable, LinUserPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasLinPermission applies the HasEdge predicate on the "lin_permission" edge. +func HasLinPermission() predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinPermissionTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinPermissionTable, LinPermissionPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinPermissionWith applies the HasEdge predicate on the "lin_permission" edge with a given conditions (other predicates). +func HasLinPermissionWith(preds ...predicate.LinPermission) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinPermissionInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinPermissionTable, LinPermissionPrimaryKey...), + ) + 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.LinGroup) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinGroup) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinGroup) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/lingroup_create.go b/internal/data/model/lingroup_create.go new file mode 100644 index 0000000..9b3b354 --- /dev/null +++ b/internal/data/model/lingroup_create.go @@ -0,0 +1,324 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupCreate is the builder for creating a LinGroup entity. +type LinGroupCreate struct { + config + mutation *LinGroupMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (lgc *LinGroupCreate) SetName(s string) *LinGroupCreate { + lgc.mutation.SetName(s) + return lgc +} + +// SetInfo sets the "info" field. +func (lgc *LinGroupCreate) SetInfo(s string) *LinGroupCreate { + lgc.mutation.SetInfo(s) + return lgc +} + +// SetLevel sets the "level" field. +func (lgc *LinGroupCreate) SetLevel(i int8) *LinGroupCreate { + lgc.mutation.SetLevel(i) + return lgc +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. +func (lgc *LinGroupCreate) AddLinUserIDs(ids ...int) *LinGroupCreate { + lgc.mutation.AddLinUserIDs(ids...) + return lgc +} + +// AddLinUser adds the "lin_user" edges to the LinUser entity. +func (lgc *LinGroupCreate) AddLinUser(l ...*LinUser) *LinGroupCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgc.AddLinUserIDs(ids...) +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. +func (lgc *LinGroupCreate) AddLinPermissionIDs(ids ...int) *LinGroupCreate { + lgc.mutation.AddLinPermissionIDs(ids...) + return lgc +} + +// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. +func (lgc *LinGroupCreate) AddLinPermission(l ...*LinPermission) *LinGroupCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgc.AddLinPermissionIDs(ids...) +} + +// Mutation returns the LinGroupMutation object of the builder. +func (lgc *LinGroupCreate) Mutation() *LinGroupMutation { + return lgc.mutation +} + +// Save creates the LinGroup in the database. +func (lgc *LinGroupCreate) Save(ctx context.Context) (*LinGroup, error) { + var ( + err error + node *LinGroup + ) + if len(lgc.hooks) == 0 { + if err = lgc.check(); err != nil { + return nil, err + } + node, err = lgc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lgc.check(); err != nil { + return nil, err + } + lgc.mutation = mutation + if node, err = lgc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lgc.hooks) - 1; i >= 0; i-- { + if lgc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lgc *LinGroupCreate) SaveX(ctx context.Context) *LinGroup { + v, err := lgc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lgc *LinGroupCreate) Exec(ctx context.Context) error { + _, err := lgc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgc *LinGroupCreate) ExecX(ctx context.Context) { + if err := lgc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lgc *LinGroupCreate) check() error { + if _, ok := lgc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} + } + if _, ok := lgc.mutation.Info(); !ok { + return &ValidationError{Name: "info", err: errors.New(`model: missing required field "info"`)} + } + if _, ok := lgc.mutation.Level(); !ok { + return &ValidationError{Name: "level", err: errors.New(`model: missing required field "level"`)} + } + return nil +} + +func (lgc *LinGroupCreate) sqlSave(ctx context.Context) (*LinGroup, error) { + _node, _spec := lgc.createSpec() + if err := sqlgraph.CreateNode(ctx, lgc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lgc *LinGroupCreate) createSpec() (*LinGroup, *sqlgraph.CreateSpec) { + var ( + _node = &LinGroup{config: lgc.config} + _spec = &sqlgraph.CreateSpec{ + Table: lingroup.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + } + ) + if value, ok := lgc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldName, + }) + _node.Name = value + } + if value, ok := lgc.mutation.Info(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldInfo, + }) + _node.Info = value + } + if value, ok := lgc.mutation.Level(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + _node.Level = value + } + if nodes := lgc.mutation.LinUserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := lgc.mutation.LinPermissionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinGroupCreateBulk is the builder for creating many LinGroup entities in bulk. +type LinGroupCreateBulk struct { + config + builders []*LinGroupCreate +} + +// Save creates the LinGroup entities in the database. +func (lgcb *LinGroupCreateBulk) Save(ctx context.Context) ([]*LinGroup, error) { + specs := make([]*sqlgraph.CreateSpec, len(lgcb.builders)) + nodes := make([]*LinGroup, len(lgcb.builders)) + mutators := make([]Mutator, len(lgcb.builders)) + for i := range lgcb.builders { + func(i int, root context.Context) { + builder := lgcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lgcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lgcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lgcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lgcb *LinGroupCreateBulk) SaveX(ctx context.Context) []*LinGroup { + v, err := lgcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lgcb *LinGroupCreateBulk) Exec(ctx context.Context) error { + _, err := lgcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgcb *LinGroupCreateBulk) ExecX(ctx context.Context) { + if err := lgcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/lingroup_delete.go b/internal/data/model/lingroup_delete.go new file mode 100644 index 0000000..5e6e856 --- /dev/null +++ b/internal/data/model/lingroup_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupDelete is the builder for deleting a LinGroup entity. +type LinGroupDelete struct { + config + hooks []Hook + mutation *LinGroupMutation +} + +// Where appends a list predicates to the LinGroupDelete builder. +func (lgd *LinGroupDelete) Where(ps ...predicate.LinGroup) *LinGroupDelete { + lgd.mutation.Where(ps...) + return lgd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lgd *LinGroupDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lgd.hooks) == 0 { + affected, err = lgd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgd.mutation = mutation + affected, err = lgd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lgd.hooks) - 1; i >= 0; i-- { + if lgd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgd *LinGroupDelete) ExecX(ctx context.Context) int { + n, err := lgd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lgd *LinGroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + if ps := lgd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lgd.driver, _spec) +} + +// LinGroupDeleteOne is the builder for deleting a single LinGroup entity. +type LinGroupDeleteOne struct { + lgd *LinGroupDelete +} + +// Exec executes the deletion query. +func (lgdo *LinGroupDeleteOne) Exec(ctx context.Context) error { + n, err := lgdo.lgd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{lingroup.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgdo *LinGroupDeleteOne) ExecX(ctx context.Context) { + lgdo.lgd.ExecX(ctx) +} diff --git a/internal/data/model/lingroup_query.go b/internal/data/model/lingroup_query.go new file mode 100644 index 0000000..b9e8d72 --- /dev/null +++ b/internal/data/model/lingroup_query.go @@ -0,0 +1,1170 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupQuery is the builder for querying LinGroup entities. +type LinGroupQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinGroup + // eager-loading edges. + withLinUser *LinUserQuery + withLinPermission *LinPermissionQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinGroupQuery builder. +func (lgq *LinGroupQuery) Where(ps ...predicate.LinGroup) *LinGroupQuery { + lgq.predicates = append(lgq.predicates, ps...) + return lgq +} + +// Limit adds a limit step to the query. +func (lgq *LinGroupQuery) Limit(limit int) *LinGroupQuery { + lgq.limit = &limit + return lgq +} + +// Offset adds an offset step to the query. +func (lgq *LinGroupQuery) Offset(offset int) *LinGroupQuery { + lgq.offset = &offset + return lgq +} + +// 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 (lgq *LinGroupQuery) Unique(unique bool) *LinGroupQuery { + lgq.unique = &unique + return lgq +} + +// Order adds an order step to the query. +func (lgq *LinGroupQuery) Order(o ...OrderFunc) *LinGroupQuery { + lgq.order = append(lgq.order, o...) + return lgq +} + +// QueryLinUser chains the current query on the "lin_user" edge. +func (lgq *LinGroupQuery) QueryLinUser() *LinUserQuery { + query := &LinUserQuery{config: lgq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lgq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, selector), + sqlgraph.To(linuser.Table, linuser.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, lingroup.LinUserTable, lingroup.LinUserPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lgq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryLinPermission chains the current query on the "lin_permission" edge. +func (lgq *LinGroupQuery) QueryLinPermission() *LinPermissionQuery { + query := &LinPermissionQuery{config: lgq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lgq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(lingroup.Table, lingroup.FieldID, selector), + sqlgraph.To(linpermission.Table, linpermission.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, lingroup.LinPermissionTable, lingroup.LinPermissionPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lgq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LinGroup entity from the query. +// Returns a *NotFoundError when no LinGroup was found. +func (lgq *LinGroupQuery) First(ctx context.Context) (*LinGroup, error) { + nodes, err := lgq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{lingroup.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lgq *LinGroupQuery) FirstX(ctx context.Context) *LinGroup { + node, err := lgq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinGroup ID from the query. +// Returns a *NotFoundError when no LinGroup ID was found. +func (lgq *LinGroupQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{lingroup.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lgq *LinGroupQuery) FirstIDX(ctx context.Context) int { + id, err := lgq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinGroup entity from the query. +// Returns a *NotFoundError when no LinGroup was found. +func (lgq *LinGroupQuery) Last(ctx context.Context) (*LinGroup, error) { + nodes, err := lgq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{lingroup.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lgq *LinGroupQuery) LastX(ctx context.Context) *LinGroup { + node, err := lgq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinGroup ID from the query. +// Returns a *NotFoundError when no LinGroup ID was found. +func (lgq *LinGroupQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{lingroup.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lgq *LinGroupQuery) LastIDX(ctx context.Context) int { + id, err := lgq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinGroup entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinGroup entity is not found. +// Returns a *NotFoundError when no LinGroup entities are found. +func (lgq *LinGroupQuery) Only(ctx context.Context) (*LinGroup, error) { + nodes, err := lgq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{lingroup.Label} + default: + return nil, &NotSingularError{lingroup.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lgq *LinGroupQuery) OnlyX(ctx context.Context) *LinGroup { + node, err := lgq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinGroup ID in the query. +// Returns a *NotSingularError when exactly one LinGroup ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lgq *LinGroupQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lgq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = &NotSingularError{lingroup.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lgq *LinGroupQuery) OnlyIDX(ctx context.Context) int { + id, err := lgq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinGroups. +func (lgq *LinGroupQuery) All(ctx context.Context) ([]*LinGroup, error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + return lgq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lgq *LinGroupQuery) AllX(ctx context.Context) []*LinGroup { + nodes, err := lgq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinGroup IDs. +func (lgq *LinGroupQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lgq.Select(lingroup.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lgq *LinGroupQuery) IDsX(ctx context.Context) []int { + ids, err := lgq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lgq *LinGroupQuery) Count(ctx context.Context) (int, error) { + if err := lgq.prepareQuery(ctx); err != nil { + return 0, err + } + return lgq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lgq *LinGroupQuery) CountX(ctx context.Context) int { + count, err := lgq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lgq *LinGroupQuery) Exist(ctx context.Context) (bool, error) { + if err := lgq.prepareQuery(ctx); err != nil { + return false, err + } + return lgq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lgq *LinGroupQuery) ExistX(ctx context.Context) bool { + exist, err := lgq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinGroupQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lgq *LinGroupQuery) Clone() *LinGroupQuery { + if lgq == nil { + return nil + } + return &LinGroupQuery{ + config: lgq.config, + limit: lgq.limit, + offset: lgq.offset, + order: append([]OrderFunc{}, lgq.order...), + predicates: append([]predicate.LinGroup{}, lgq.predicates...), + withLinUser: lgq.withLinUser.Clone(), + withLinPermission: lgq.withLinPermission.Clone(), + // clone intermediate query. + sql: lgq.sql.Clone(), + path: lgq.path, + } +} + +// WithLinUser tells the query-builder to eager-load the nodes that are connected to +// the "lin_user" edge. The optional arguments are used to configure the query builder of the edge. +func (lgq *LinGroupQuery) WithLinUser(opts ...func(*LinUserQuery)) *LinGroupQuery { + query := &LinUserQuery{config: lgq.config} + for _, opt := range opts { + opt(query) + } + lgq.withLinUser = query + return lgq +} + +// WithLinPermission tells the query-builder to eager-load the nodes that are connected to +// the "lin_permission" edge. The optional arguments are used to configure the query builder of the edge. +func (lgq *LinGroupQuery) WithLinPermission(opts ...func(*LinPermissionQuery)) *LinGroupQuery { + query := &LinPermissionQuery{config: lgq.config} + for _, opt := range opts { + opt(query) + } + lgq.withLinPermission = query + return lgq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinGroup.Query(). +// GroupBy(lingroup.FieldName). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lgq *LinGroupQuery) GroupBy(field string, fields ...string) *LinGroupGroupBy { + group := &LinGroupGroupBy{config: lgq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lgq.prepareQuery(ctx); err != nil { + return nil, err + } + return lgq.sqlQuery(ctx), nil + } + return group +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.LinGroup.Query(). +// Select(lingroup.FieldName). +// Scan(ctx, &v) +// +func (lgq *LinGroupQuery) Select(fields ...string) *LinGroupSelect { + lgq.fields = append(lgq.fields, fields...) + return &LinGroupSelect{LinGroupQuery: lgq} +} + +func (lgq *LinGroupQuery) prepareQuery(ctx context.Context) error { + for _, f := range lgq.fields { + if !lingroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lgq.path != nil { + prev, err := lgq.path(ctx) + if err != nil { + return err + } + lgq.sql = prev + } + return nil +} + +func (lgq *LinGroupQuery) sqlAll(ctx context.Context) ([]*LinGroup, error) { + var ( + nodes = []*LinGroup{} + _spec = lgq.querySpec() + loadedTypes = [2]bool{ + lgq.withLinUser != nil, + lgq.withLinPermission != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinGroup{config: lgq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lgq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := lgq.withLinUser; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinGroup, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinUser = []*LinUser{} + } + var ( + edgeids []int + edges = make(map[int][]*LinGroup) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(lingroup.LinUserPrimaryKey[0], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, lgq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_user": %w`, err) + } + query.Where(linuser.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_user" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinUser = append(nodes[i].Edges.LinUser, n) + } + } + } + + if query := lgq.withLinPermission; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinGroup, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinPermission = []*LinPermission{} + } + var ( + edgeids []int + edges = make(map[int][]*LinGroup) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(lingroup.LinPermissionPrimaryKey[1], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, lgq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_permission": %w`, err) + } + query.Where(linpermission.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_permission" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinPermission = append(nodes[i].Edges.LinPermission, n) + } + } + } + + return nodes, nil +} + +func (lgq *LinGroupQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lgq.querySpec() + return sqlgraph.CountNodes(ctx, lgq.driver, _spec) +} + +func (lgq *LinGroupQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lgq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lgq *LinGroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + Columns: lingroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + From: lgq.sql, + Unique: true, + } + if unique := lgq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lgq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, lingroup.FieldID) + for i := range fields { + if fields[i] != lingroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lgq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lgq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lgq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lgq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lgq *LinGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lgq.driver.Dialect()) + t1 := builder.Table(lingroup.Table) + columns := lgq.fields + if len(columns) == 0 { + columns = lingroup.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lgq.sql != nil { + selector = lgq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lgq.predicates { + p(selector) + } + for _, p := range lgq.order { + p(selector) + } + if offset := lgq.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 := lgq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinGroupGroupBy is the group-by builder for LinGroup entities. +type LinGroupGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lggb *LinGroupGroupBy) Aggregate(fns ...AggregateFunc) *LinGroupGroupBy { + lggb.fns = append(lggb.fns, fns...) + return lggb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lggb *LinGroupGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lggb.path(ctx) + if err != nil { + return err + } + lggb.sql = query + return lggb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lggb *LinGroupGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lggb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lggb *LinGroupGroupBy) StringsX(ctx context.Context) []string { + v, err := lggb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lggb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lggb *LinGroupGroupBy) StringX(ctx context.Context) string { + v, err := lggb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lggb *LinGroupGroupBy) IntsX(ctx context.Context) []int { + v, err := lggb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lggb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lggb *LinGroupGroupBy) IntX(ctx context.Context) int { + v, err := lggb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lggb *LinGroupGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lggb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lggb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lggb *LinGroupGroupBy) Float64X(ctx context.Context) float64 { + v, err := lggb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lggb.fields) > 1 { + return nil, errors.New("model: LinGroupGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lggb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lggb *LinGroupGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lggb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lggb *LinGroupGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lggb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lggb *LinGroupGroupBy) BoolX(ctx context.Context) bool { + v, err := lggb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lggb *LinGroupGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lggb.fields { + if !lingroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lggb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lggb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lggb *LinGroupGroupBy) sqlQuery() *sql.Selector { + selector := lggb.sql.Select() + aggregation := make([]string, 0, len(lggb.fns)) + for _, fn := range lggb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lggb.fields)+len(lggb.fns)) + for _, f := range lggb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lggb.fields...)...) +} + +// LinGroupSelect is the builder for selecting fields of LinGroup entities. +type LinGroupSelect struct { + *LinGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lgs *LinGroupSelect) Scan(ctx context.Context, v interface{}) error { + if err := lgs.prepareQuery(ctx); err != nil { + return err + } + lgs.sql = lgs.LinGroupQuery.sqlQuery(ctx) + return lgs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lgs *LinGroupSelect) ScanX(ctx context.Context, v interface{}) { + if err := lgs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Strings(ctx context.Context) ([]string, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lgs *LinGroupSelect) StringsX(ctx context.Context) []string { + v, err := lgs.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lgs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lgs *LinGroupSelect) StringX(ctx context.Context) string { + v, err := lgs.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Ints(ctx context.Context) ([]int, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lgs *LinGroupSelect) IntsX(ctx context.Context) []int { + v, err := lgs.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lgs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lgs *LinGroupSelect) IntX(ctx context.Context) int { + v, err := lgs.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lgs *LinGroupSelect) Float64sX(ctx context.Context) []float64 { + v, err := lgs.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lgs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lgs *LinGroupSelect) Float64X(ctx context.Context) float64 { + v, err := lgs.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lgs.fields) > 1 { + return nil, errors.New("model: LinGroupSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lgs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lgs *LinGroupSelect) BoolsX(ctx context.Context) []bool { + v, err := lgs.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lgs *LinGroupSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lgs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{lingroup.Label} + default: + err = fmt.Errorf("model: LinGroupSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lgs *LinGroupSelect) BoolX(ctx context.Context) bool { + v, err := lgs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lgs *LinGroupSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lgs.sql.Query() + if err := lgs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/lingroup_update.go b/internal/data/model/lingroup_update.go new file mode 100644 index 0000000..09bd286 --- /dev/null +++ b/internal/data/model/lingroup_update.go @@ -0,0 +1,706 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinGroupUpdate is the builder for updating LinGroup entities. +type LinGroupUpdate struct { + config + hooks []Hook + mutation *LinGroupMutation +} + +// Where appends a list predicates to the LinGroupUpdate builder. +func (lgu *LinGroupUpdate) Where(ps ...predicate.LinGroup) *LinGroupUpdate { + lgu.mutation.Where(ps...) + return lgu +} + +// SetName sets the "name" field. +func (lgu *LinGroupUpdate) SetName(s string) *LinGroupUpdate { + lgu.mutation.SetName(s) + return lgu +} + +// SetInfo sets the "info" field. +func (lgu *LinGroupUpdate) SetInfo(s string) *LinGroupUpdate { + lgu.mutation.SetInfo(s) + return lgu +} + +// SetLevel sets the "level" field. +func (lgu *LinGroupUpdate) SetLevel(i int8) *LinGroupUpdate { + lgu.mutation.ResetLevel() + lgu.mutation.SetLevel(i) + return lgu +} + +// AddLevel adds i to the "level" field. +func (lgu *LinGroupUpdate) AddLevel(i int8) *LinGroupUpdate { + lgu.mutation.AddLevel(i) + return lgu +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. +func (lgu *LinGroupUpdate) AddLinUserIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.AddLinUserIDs(ids...) + return lgu +} + +// AddLinUser adds the "lin_user" edges to the LinUser entity. +func (lgu *LinGroupUpdate) AddLinUser(l ...*LinUser) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.AddLinUserIDs(ids...) +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. +func (lgu *LinGroupUpdate) AddLinPermissionIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.AddLinPermissionIDs(ids...) + return lgu +} + +// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. +func (lgu *LinGroupUpdate) AddLinPermission(l ...*LinPermission) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.AddLinPermissionIDs(ids...) +} + +// Mutation returns the LinGroupMutation object of the builder. +func (lgu *LinGroupUpdate) Mutation() *LinGroupMutation { + return lgu.mutation +} + +// ClearLinUser clears all "lin_user" edges to the LinUser entity. +func (lgu *LinGroupUpdate) ClearLinUser() *LinGroupUpdate { + lgu.mutation.ClearLinUser() + return lgu +} + +// RemoveLinUserIDs removes the "lin_user" edge to LinUser entities by IDs. +func (lgu *LinGroupUpdate) RemoveLinUserIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.RemoveLinUserIDs(ids...) + return lgu +} + +// RemoveLinUser removes "lin_user" edges to LinUser entities. +func (lgu *LinGroupUpdate) RemoveLinUser(l ...*LinUser) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.RemoveLinUserIDs(ids...) +} + +// ClearLinPermission clears all "lin_permission" edges to the LinPermission entity. +func (lgu *LinGroupUpdate) ClearLinPermission() *LinGroupUpdate { + lgu.mutation.ClearLinPermission() + return lgu +} + +// RemoveLinPermissionIDs removes the "lin_permission" edge to LinPermission entities by IDs. +func (lgu *LinGroupUpdate) RemoveLinPermissionIDs(ids ...int) *LinGroupUpdate { + lgu.mutation.RemoveLinPermissionIDs(ids...) + return lgu +} + +// RemoveLinPermission removes "lin_permission" edges to LinPermission entities. +func (lgu *LinGroupUpdate) RemoveLinPermission(l ...*LinPermission) *LinGroupUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lgu.RemoveLinPermissionIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lgu *LinGroupUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lgu.hooks) == 0 { + affected, err = lgu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lgu.mutation = mutation + affected, err = lgu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lgu.hooks) - 1; i >= 0; i-- { + if lgu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lgu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lgu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lgu *LinGroupUpdate) SaveX(ctx context.Context) int { + affected, err := lgu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lgu *LinGroupUpdate) Exec(ctx context.Context) error { + _, err := lgu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lgu *LinGroupUpdate) ExecX(ctx context.Context) { + if err := lgu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lgu *LinGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + Columns: lingroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + if ps := lgu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lgu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldName, + }) + } + if value, ok := lgu.mutation.Info(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldInfo, + }) + } + if value, ok := lgu.mutation.Level(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if value, ok := lgu.mutation.AddedLevel(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if lgu.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.RemovedLinUserIDs(); len(nodes) > 0 && !lgu.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.LinUserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if lgu.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.RemovedLinPermissionIDs(); len(nodes) > 0 && !lgu.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lgu.mutation.LinPermissionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, lgu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{lingroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinGroupUpdateOne is the builder for updating a single LinGroup entity. +type LinGroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinGroupMutation +} + +// SetName sets the "name" field. +func (lguo *LinGroupUpdateOne) SetName(s string) *LinGroupUpdateOne { + lguo.mutation.SetName(s) + return lguo +} + +// SetInfo sets the "info" field. +func (lguo *LinGroupUpdateOne) SetInfo(s string) *LinGroupUpdateOne { + lguo.mutation.SetInfo(s) + return lguo +} + +// SetLevel sets the "level" field. +func (lguo *LinGroupUpdateOne) SetLevel(i int8) *LinGroupUpdateOne { + lguo.mutation.ResetLevel() + lguo.mutation.SetLevel(i) + return lguo +} + +// AddLevel adds i to the "level" field. +func (lguo *LinGroupUpdateOne) AddLevel(i int8) *LinGroupUpdateOne { + lguo.mutation.AddLevel(i) + return lguo +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by IDs. +func (lguo *LinGroupUpdateOne) AddLinUserIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.AddLinUserIDs(ids...) + return lguo +} + +// AddLinUser adds the "lin_user" edges to the LinUser entity. +func (lguo *LinGroupUpdateOne) AddLinUser(l ...*LinUser) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.AddLinUserIDs(ids...) +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by IDs. +func (lguo *LinGroupUpdateOne) AddLinPermissionIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.AddLinPermissionIDs(ids...) + return lguo +} + +// AddLinPermission adds the "lin_permission" edges to the LinPermission entity. +func (lguo *LinGroupUpdateOne) AddLinPermission(l ...*LinPermission) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.AddLinPermissionIDs(ids...) +} + +// Mutation returns the LinGroupMutation object of the builder. +func (lguo *LinGroupUpdateOne) Mutation() *LinGroupMutation { + return lguo.mutation +} + +// ClearLinUser clears all "lin_user" edges to the LinUser entity. +func (lguo *LinGroupUpdateOne) ClearLinUser() *LinGroupUpdateOne { + lguo.mutation.ClearLinUser() + return lguo +} + +// RemoveLinUserIDs removes the "lin_user" edge to LinUser entities by IDs. +func (lguo *LinGroupUpdateOne) RemoveLinUserIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.RemoveLinUserIDs(ids...) + return lguo +} + +// RemoveLinUser removes "lin_user" edges to LinUser entities. +func (lguo *LinGroupUpdateOne) RemoveLinUser(l ...*LinUser) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.RemoveLinUserIDs(ids...) +} + +// ClearLinPermission clears all "lin_permission" edges to the LinPermission entity. +func (lguo *LinGroupUpdateOne) ClearLinPermission() *LinGroupUpdateOne { + lguo.mutation.ClearLinPermission() + return lguo +} + +// RemoveLinPermissionIDs removes the "lin_permission" edge to LinPermission entities by IDs. +func (lguo *LinGroupUpdateOne) RemoveLinPermissionIDs(ids ...int) *LinGroupUpdateOne { + lguo.mutation.RemoveLinPermissionIDs(ids...) + return lguo +} + +// RemoveLinPermission removes "lin_permission" edges to LinPermission entities. +func (lguo *LinGroupUpdateOne) RemoveLinPermission(l ...*LinPermission) *LinGroupUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lguo.RemoveLinPermissionIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lguo *LinGroupUpdateOne) Select(field string, fields ...string) *LinGroupUpdateOne { + lguo.fields = append([]string{field}, fields...) + return lguo +} + +// Save executes the query and returns the updated LinGroup entity. +func (lguo *LinGroupUpdateOne) Save(ctx context.Context) (*LinGroup, error) { + var ( + err error + node *LinGroup + ) + if len(lguo.hooks) == 0 { + node, err = lguo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lguo.mutation = mutation + node, err = lguo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lguo.hooks) - 1; i >= 0; i-- { + if lguo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lguo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lguo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lguo *LinGroupUpdateOne) SaveX(ctx context.Context) *LinGroup { + node, err := lguo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lguo *LinGroupUpdateOne) Exec(ctx context.Context) error { + _, err := lguo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lguo *LinGroupUpdateOne) ExecX(ctx context.Context) { + if err := lguo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lguo *LinGroupUpdateOne) sqlSave(ctx context.Context) (_node *LinGroup, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: lingroup.Table, + Columns: lingroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + id, ok := lguo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinGroup.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lguo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, lingroup.FieldID) + for _, f := range fields { + if !lingroup.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != lingroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lguo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lguo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldName, + }) + } + if value, ok := lguo.mutation.Info(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: lingroup.FieldInfo, + }) + } + if value, ok := lguo.mutation.Level(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if value, ok := lguo.mutation.AddedLevel(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: lingroup.FieldLevel, + }) + } + if lguo.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.RemovedLinUserIDs(); len(nodes) > 0 && !lguo.mutation.LinUserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.LinUserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: lingroup.LinUserTable, + Columns: lingroup.LinUserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if lguo.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.RemovedLinPermissionIDs(); len(nodes) > 0 && !lguo.mutation.LinPermissionCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lguo.mutation.LinPermissionIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: lingroup.LinPermissionTable, + Columns: lingroup.LinPermissionPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LinGroup{config: lguo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lguo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{lingroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linlog.go b/internal/data/model/linlog.go new file mode 100644 index 0000000..8aa0545 --- /dev/null +++ b/internal/data/model/linlog.go @@ -0,0 +1,192 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linlog" + "strings" + "time" + + "entgo.io/ent/dialect/sql" +) + +// LinLog is the model entity for the LinLog schema. +type LinLog struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` + // Message holds the value of the "message" field. + Message string `json:"message,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // Username holds the value of the "username" field. + Username string `json:"username,omitempty"` + // StatusCode holds the value of the "status_code" field. + StatusCode int `json:"status_code,omitempty"` + // Method holds the value of the "method" field. + Method string `json:"method,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // Permission holds the value of the "permission" field. + Permission string `json:"permission,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinLog) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linlog.FieldID, linlog.FieldUserID, linlog.FieldStatusCode: + values[i] = new(sql.NullInt64) + case linlog.FieldMessage, linlog.FieldUsername, linlog.FieldMethod, linlog.FieldPath, linlog.FieldPermission: + values[i] = new(sql.NullString) + case linlog.FieldCreateTime, linlog.FieldUpdateTime, linlog.FieldDeleteTime: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type LinLog", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinLog fields. +func (ll *LinLog) assignValues(columns []string, values []interface{}) 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 linlog.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ll.ID = int(value.Int64) + case linlog.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + ll.CreateTime = value.Time + } + case linlog.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + ll.UpdateTime = value.Time + } + case linlog.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + ll.DeleteTime = value.Time + } + case linlog.FieldMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message", values[i]) + } else if value.Valid { + ll.Message = value.String + } + case linlog.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + ll.UserID = int(value.Int64) + } + case linlog.FieldUsername: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value.Valid { + ll.Username = value.String + } + case linlog.FieldStatusCode: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field status_code", values[i]) + } else if value.Valid { + ll.StatusCode = int(value.Int64) + } + case linlog.FieldMethod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field method", values[i]) + } else if value.Valid { + ll.Method = value.String + } + case linlog.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + ll.Path = value.String + } + case linlog.FieldPermission: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field permission", values[i]) + } else if value.Valid { + ll.Permission = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this LinLog. +// Note that you need to call LinLog.Unwrap() before calling this method if this LinLog +// was returned from a transaction, and the transaction was committed or rolled back. +func (ll *LinLog) Update() *LinLogUpdateOne { + return (&LinLogClient{config: ll.config}).UpdateOne(ll) +} + +// Unwrap unwraps the LinLog 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 (ll *LinLog) Unwrap() *LinLog { + tx, ok := ll.config.driver.(*txDriver) + if !ok { + panic("model: LinLog is not a transactional entity") + } + ll.config.driver = tx.drv + return ll +} + +// String implements the fmt.Stringer. +func (ll *LinLog) String() string { + var builder strings.Builder + builder.WriteString("LinLog(") + builder.WriteString(fmt.Sprintf("id=%v", ll.ID)) + builder.WriteString(", create_time=") + builder.WriteString(ll.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(ll.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(ll.DeleteTime.Format(time.ANSIC)) + builder.WriteString(", message=") + builder.WriteString(ll.Message) + builder.WriteString(", user_id=") + builder.WriteString(fmt.Sprintf("%v", ll.UserID)) + builder.WriteString(", username=") + builder.WriteString(ll.Username) + builder.WriteString(", status_code=") + builder.WriteString(fmt.Sprintf("%v", ll.StatusCode)) + builder.WriteString(", method=") + builder.WriteString(ll.Method) + builder.WriteString(", path=") + builder.WriteString(ll.Path) + builder.WriteString(", permission=") + builder.WriteString(ll.Permission) + builder.WriteByte(')') + return builder.String() +} + +// LinLogs is a parsable slice of LinLog. +type LinLogs []*LinLog + +func (ll LinLogs) config(cfg config) { + for _i := range ll { + ll[_i].config = cfg + } +} diff --git a/internal/data/model/linlog/linlog.go b/internal/data/model/linlog/linlog.go new file mode 100644 index 0000000..14f4ab7 --- /dev/null +++ b/internal/data/model/linlog/linlog.go @@ -0,0 +1,72 @@ +// Code generated by entc, DO NOT EDIT. + +package linlog + +import ( + "time" +) + +const ( + // Label holds the string label denoting the linlog type in the database. + Label = "lin_log" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" + // FieldMessage holds the string denoting the message field in the database. + FieldMessage = "message" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldStatusCode holds the string denoting the status_code field in the database. + FieldStatusCode = "status_code" + // FieldMethod holds the string denoting the method field in the database. + FieldMethod = "method" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldPermission holds the string denoting the permission field in the database. + FieldPermission = "permission" + // Table holds the table name of the linlog in the database. + Table = "lin_log" +) + +// Columns holds all SQL columns for linlog fields. +var Columns = []string{ + FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldMessage, + FieldUserID, + FieldUsername, + FieldStatusCode, + FieldMethod, + FieldPath, + FieldPermission, +} + +// 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 ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // DefaultDeleteTime holds the default value on creation for the "delete_time" field. + DefaultDeleteTime func() time.Time +) diff --git a/internal/data/model/linlog/where.go b/internal/data/model/linlog/where.go new file mode 100644 index 0000000..c877f50 --- /dev/null +++ b/internal/data/model/linlog/where.go @@ -0,0 +1,1130 @@ +// Code generated by entc, DO NOT EDIT. + +package linlog + +import ( + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. +func Message(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMessage), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// StatusCode applies equality check predicate on the "status_code" field. It's identical to StatusCodeEQ. +func StatusCode(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatusCode), v)) + }) +} + +// Method applies equality check predicate on the "method" field. It's identical to MethodEQ. +func Method(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMethod), v)) + }) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// Permission applies equality check predicate on the "permission" field. It's identical to PermissionEQ. +func Permission(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPermission), v)) + }) +} + +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + +// MessageEQ applies the EQ predicate on the "message" field. +func MessageEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMessage), v)) + }) +} + +// MessageNEQ applies the NEQ predicate on the "message" field. +func MessageNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMessage), v)) + }) +} + +// MessageIn applies the In predicate on the "message" field. +func MessageIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMessage), v...)) + }) +} + +// MessageNotIn applies the NotIn predicate on the "message" field. +func MessageNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMessage), v...)) + }) +} + +// MessageGT applies the GT predicate on the "message" field. +func MessageGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMessage), v)) + }) +} + +// MessageGTE applies the GTE predicate on the "message" field. +func MessageGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMessage), v)) + }) +} + +// MessageLT applies the LT predicate on the "message" field. +func MessageLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMessage), v)) + }) +} + +// MessageLTE applies the LTE predicate on the "message" field. +func MessageLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMessage), v)) + }) +} + +// MessageContains applies the Contains predicate on the "message" field. +func MessageContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldMessage), v)) + }) +} + +// MessageHasPrefix applies the HasPrefix predicate on the "message" field. +func MessageHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldMessage), v)) + }) +} + +// MessageHasSuffix applies the HasSuffix predicate on the "message" field. +func MessageHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldMessage), v)) + }) +} + +// MessageEqualFold applies the EqualFold predicate on the "message" field. +func MessageEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldMessage), v)) + }) +} + +// MessageContainsFold applies the ContainsFold predicate on the "message" field. +func MessageContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldMessage), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUserID), v...)) + }) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUserID), v)) + }) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUserID), v)) + }) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUserID), v)) + }) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUserID), v)) + }) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUsername), v)) + }) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUsername), v...)) + }) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUsername), v...)) + }) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUsername), v)) + }) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUsername), v)) + }) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUsername), v)) + }) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUsername), v)) + }) +} + +// UsernameContains applies the Contains predicate on the "username" field. +func UsernameContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldUsername), v)) + }) +} + +// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. +func UsernameHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldUsername), v)) + }) +} + +// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. +func UsernameHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldUsername), v)) + }) +} + +// UsernameEqualFold applies the EqualFold predicate on the "username" field. +func UsernameEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldUsername), v)) + }) +} + +// UsernameContainsFold applies the ContainsFold predicate on the "username" field. +func UsernameContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldUsername), v)) + }) +} + +// StatusCodeEQ applies the EQ predicate on the "status_code" field. +func StatusCodeEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeNEQ applies the NEQ predicate on the "status_code" field. +func StatusCodeNEQ(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeIn applies the In predicate on the "status_code" field. +func StatusCodeIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldStatusCode), v...)) + }) +} + +// StatusCodeNotIn applies the NotIn predicate on the "status_code" field. +func StatusCodeNotIn(vs ...int) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldStatusCode), v...)) + }) +} + +// StatusCodeGT applies the GT predicate on the "status_code" field. +func StatusCodeGT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeGTE applies the GTE predicate on the "status_code" field. +func StatusCodeGTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeLT applies the LT predicate on the "status_code" field. +func StatusCodeLT(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldStatusCode), v)) + }) +} + +// StatusCodeLTE applies the LTE predicate on the "status_code" field. +func StatusCodeLTE(v int) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldStatusCode), v)) + }) +} + +// MethodEQ applies the EQ predicate on the "method" field. +func MethodEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMethod), v)) + }) +} + +// MethodNEQ applies the NEQ predicate on the "method" field. +func MethodNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMethod), v)) + }) +} + +// MethodIn applies the In predicate on the "method" field. +func MethodIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMethod), v...)) + }) +} + +// MethodNotIn applies the NotIn predicate on the "method" field. +func MethodNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMethod), v...)) + }) +} + +// MethodGT applies the GT predicate on the "method" field. +func MethodGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMethod), v)) + }) +} + +// MethodGTE applies the GTE predicate on the "method" field. +func MethodGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMethod), v)) + }) +} + +// MethodLT applies the LT predicate on the "method" field. +func MethodLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMethod), v)) + }) +} + +// MethodLTE applies the LTE predicate on the "method" field. +func MethodLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMethod), v)) + }) +} + +// MethodContains applies the Contains predicate on the "method" field. +func MethodContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldMethod), v)) + }) +} + +// MethodHasPrefix applies the HasPrefix predicate on the "method" field. +func MethodHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldMethod), v)) + }) +} + +// MethodHasSuffix applies the HasSuffix predicate on the "method" field. +func MethodHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldMethod), v)) + }) +} + +// MethodEqualFold applies the EqualFold predicate on the "method" field. +func MethodEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldMethod), v)) + }) +} + +// MethodContainsFold applies the ContainsFold predicate on the "method" field. +func MethodContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldMethod), v)) + }) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPath), v)) + }) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPath), v)) + }) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPath), v...)) + }) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPath), v...)) + }) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPath), v)) + }) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPath), v)) + }) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPath), v)) + }) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPath), v)) + }) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldPath), v)) + }) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldPath), v)) + }) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldPath), v)) + }) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldPath), v)) + }) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldPath), v)) + }) +} + +// PermissionEQ applies the EQ predicate on the "permission" field. +func PermissionEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldPermission), v)) + }) +} + +// PermissionNEQ applies the NEQ predicate on the "permission" field. +func PermissionNEQ(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldPermission), v)) + }) +} + +// PermissionIn applies the In predicate on the "permission" field. +func PermissionIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldPermission), v...)) + }) +} + +// PermissionNotIn applies the NotIn predicate on the "permission" field. +func PermissionNotIn(vs ...string) predicate.LinLog { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinLog(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldPermission), v...)) + }) +} + +// PermissionGT applies the GT predicate on the "permission" field. +func PermissionGT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldPermission), v)) + }) +} + +// PermissionGTE applies the GTE predicate on the "permission" field. +func PermissionGTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldPermission), v)) + }) +} + +// PermissionLT applies the LT predicate on the "permission" field. +func PermissionLT(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldPermission), v)) + }) +} + +// PermissionLTE applies the LTE predicate on the "permission" field. +func PermissionLTE(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldPermission), v)) + }) +} + +// PermissionContains applies the Contains predicate on the "permission" field. +func PermissionContains(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldPermission), v)) + }) +} + +// PermissionHasPrefix applies the HasPrefix predicate on the "permission" field. +func PermissionHasPrefix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldPermission), v)) + }) +} + +// PermissionHasSuffix applies the HasSuffix predicate on the "permission" field. +func PermissionHasSuffix(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldPermission), v)) + }) +} + +// PermissionEqualFold applies the EqualFold predicate on the "permission" field. +func PermissionEqualFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldPermission), v)) + }) +} + +// PermissionContainsFold applies the ContainsFold predicate on the "permission" field. +func PermissionContainsFold(v string) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldPermission), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinLog) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinLog) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinLog) predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linlog_create.go b/internal/data/model/linlog_create.go new file mode 100644 index 0000000..9b9b76d --- /dev/null +++ b/internal/data/model/linlog_create.go @@ -0,0 +1,416 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogCreate is the builder for creating a LinLog entity. +type LinLogCreate struct { + config + mutation *LinLogMutation + hooks []Hook +} + +// SetCreateTime sets the "create_time" field. +func (llc *LinLogCreate) SetCreateTime(t time.Time) *LinLogCreate { + llc.mutation.SetCreateTime(t) + return llc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (llc *LinLogCreate) SetNillableCreateTime(t *time.Time) *LinLogCreate { + if t != nil { + llc.SetCreateTime(*t) + } + return llc +} + +// SetUpdateTime sets the "update_time" field. +func (llc *LinLogCreate) SetUpdateTime(t time.Time) *LinLogCreate { + llc.mutation.SetUpdateTime(t) + return llc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (llc *LinLogCreate) SetNillableUpdateTime(t *time.Time) *LinLogCreate { + if t != nil { + llc.SetUpdateTime(*t) + } + return llc +} + +// SetDeleteTime sets the "delete_time" field. +func (llc *LinLogCreate) SetDeleteTime(t time.Time) *LinLogCreate { + llc.mutation.SetDeleteTime(t) + return llc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (llc *LinLogCreate) SetNillableDeleteTime(t *time.Time) *LinLogCreate { + if t != nil { + llc.SetDeleteTime(*t) + } + return llc +} + +// SetMessage sets the "message" field. +func (llc *LinLogCreate) SetMessage(s string) *LinLogCreate { + llc.mutation.SetMessage(s) + return llc +} + +// SetUserID sets the "user_id" field. +func (llc *LinLogCreate) SetUserID(i int) *LinLogCreate { + llc.mutation.SetUserID(i) + return llc +} + +// SetUsername sets the "username" field. +func (llc *LinLogCreate) SetUsername(s string) *LinLogCreate { + llc.mutation.SetUsername(s) + return llc +} + +// SetStatusCode sets the "status_code" field. +func (llc *LinLogCreate) SetStatusCode(i int) *LinLogCreate { + llc.mutation.SetStatusCode(i) + return llc +} + +// SetMethod sets the "method" field. +func (llc *LinLogCreate) SetMethod(s string) *LinLogCreate { + llc.mutation.SetMethod(s) + return llc +} + +// SetPath sets the "path" field. +func (llc *LinLogCreate) SetPath(s string) *LinLogCreate { + llc.mutation.SetPath(s) + return llc +} + +// SetPermission sets the "permission" field. +func (llc *LinLogCreate) SetPermission(s string) *LinLogCreate { + llc.mutation.SetPermission(s) + return llc +} + +// Mutation returns the LinLogMutation object of the builder. +func (llc *LinLogCreate) Mutation() *LinLogMutation { + return llc.mutation +} + +// Save creates the LinLog in the database. +func (llc *LinLogCreate) Save(ctx context.Context) (*LinLog, error) { + var ( + err error + node *LinLog + ) + llc.defaults() + if len(llc.hooks) == 0 { + if err = llc.check(); err != nil { + return nil, err + } + node, err = llc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = llc.check(); err != nil { + return nil, err + } + llc.mutation = mutation + if node, err = llc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(llc.hooks) - 1; i >= 0; i-- { + if llc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = llc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, llc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (llc *LinLogCreate) SaveX(ctx context.Context) *LinLog { + v, err := llc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (llc *LinLogCreate) Exec(ctx context.Context) error { + _, err := llc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (llc *LinLogCreate) ExecX(ctx context.Context) { + if err := llc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (llc *LinLogCreate) defaults() { + if _, ok := llc.mutation.CreateTime(); !ok { + v := linlog.DefaultCreateTime() + llc.mutation.SetCreateTime(v) + } + if _, ok := llc.mutation.UpdateTime(); !ok { + v := linlog.DefaultUpdateTime() + llc.mutation.SetUpdateTime(v) + } + if _, ok := llc.mutation.DeleteTime(); !ok { + v := linlog.DefaultDeleteTime() + llc.mutation.SetDeleteTime(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (llc *LinLogCreate) check() error { + if _, ok := llc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := llc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } + if _, ok := llc.mutation.DeleteTime(); !ok { + return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} + } + if _, ok := llc.mutation.Message(); !ok { + return &ValidationError{Name: "message", err: errors.New(`model: missing required field "message"`)} + } + if _, ok := llc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} + } + if _, ok := llc.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} + } + if _, ok := llc.mutation.StatusCode(); !ok { + return &ValidationError{Name: "status_code", err: errors.New(`model: missing required field "status_code"`)} + } + if _, ok := llc.mutation.Method(); !ok { + return &ValidationError{Name: "method", err: errors.New(`model: missing required field "method"`)} + } + if _, ok := llc.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`model: missing required field "path"`)} + } + if _, ok := llc.mutation.Permission(); !ok { + return &ValidationError{Name: "permission", err: errors.New(`model: missing required field "permission"`)} + } + return nil +} + +func (llc *LinLogCreate) sqlSave(ctx context.Context) (*LinLog, error) { + _node, _spec := llc.createSpec() + if err := sqlgraph.CreateNode(ctx, llc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (llc *LinLogCreate) createSpec() (*LinLog, *sqlgraph.CreateSpec) { + var ( + _node = &LinLog{config: llc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linlog.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + } + ) + if value, ok := llc.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := llc.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := llc.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldDeleteTime, + }) + _node.DeleteTime = value + } + if value, ok := llc.mutation.Message(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMessage, + }) + _node.Message = value + } + if value, ok := llc.mutation.UserID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + _node.UserID = value + } + if value, ok := llc.mutation.Username(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldUsername, + }) + _node.Username = value + } + if value, ok := llc.mutation.StatusCode(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + _node.StatusCode = value + } + if value, ok := llc.mutation.Method(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMethod, + }) + _node.Method = value + } + if value, ok := llc.mutation.Path(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPath, + }) + _node.Path = value + } + if value, ok := llc.mutation.Permission(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPermission, + }) + _node.Permission = value + } + return _node, _spec +} + +// LinLogCreateBulk is the builder for creating many LinLog entities in bulk. +type LinLogCreateBulk struct { + config + builders []*LinLogCreate +} + +// Save creates the LinLog entities in the database. +func (llcb *LinLogCreateBulk) Save(ctx context.Context) ([]*LinLog, error) { + specs := make([]*sqlgraph.CreateSpec, len(llcb.builders)) + nodes := make([]*LinLog, len(llcb.builders)) + mutators := make([]Mutator, len(llcb.builders)) + for i := range llcb.builders { + func(i int, root context.Context) { + builder := llcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, llcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, llcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, llcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (llcb *LinLogCreateBulk) SaveX(ctx context.Context) []*LinLog { + v, err := llcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (llcb *LinLogCreateBulk) Exec(ctx context.Context) error { + _, err := llcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (llcb *LinLogCreateBulk) ExecX(ctx context.Context) { + if err := llcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linlog_delete.go b/internal/data/model/linlog_delete.go new file mode 100644 index 0000000..7b370d2 --- /dev/null +++ b/internal/data/model/linlog_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogDelete is the builder for deleting a LinLog entity. +type LinLogDelete struct { + config + hooks []Hook + mutation *LinLogMutation +} + +// Where appends a list predicates to the LinLogDelete builder. +func (lld *LinLogDelete) Where(ps ...predicate.LinLog) *LinLogDelete { + lld.mutation.Where(ps...) + return lld +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lld *LinLogDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lld.hooks) == 0 { + affected, err = lld.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lld.mutation = mutation + affected, err = lld.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lld.hooks) - 1; i >= 0; i-- { + if lld.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lld.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lld.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lld *LinLogDelete) ExecX(ctx context.Context) int { + n, err := lld.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lld *LinLogDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + } + if ps := lld.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lld.driver, _spec) +} + +// LinLogDeleteOne is the builder for deleting a single LinLog entity. +type LinLogDeleteOne struct { + lld *LinLogDelete +} + +// Exec executes the deletion query. +func (lldo *LinLogDeleteOne) Exec(ctx context.Context) error { + n, err := lldo.lld.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linlog.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lldo *LinLogDeleteOne) ExecX(ctx context.Context) { + lldo.lld.ExecX(ctx) +} diff --git a/internal/data/model/linlog_query.go b/internal/data/model/linlog_query.go new file mode 100644 index 0000000..c734c14 --- /dev/null +++ b/internal/data/model/linlog_query.go @@ -0,0 +1,960 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogQuery is the builder for querying LinLog entities. +type LinLogQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinLog + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinLogQuery builder. +func (llq *LinLogQuery) Where(ps ...predicate.LinLog) *LinLogQuery { + llq.predicates = append(llq.predicates, ps...) + return llq +} + +// Limit adds a limit step to the query. +func (llq *LinLogQuery) Limit(limit int) *LinLogQuery { + llq.limit = &limit + return llq +} + +// Offset adds an offset step to the query. +func (llq *LinLogQuery) Offset(offset int) *LinLogQuery { + llq.offset = &offset + return llq +} + +// 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 (llq *LinLogQuery) Unique(unique bool) *LinLogQuery { + llq.unique = &unique + return llq +} + +// Order adds an order step to the query. +func (llq *LinLogQuery) Order(o ...OrderFunc) *LinLogQuery { + llq.order = append(llq.order, o...) + return llq +} + +// First returns the first LinLog entity from the query. +// Returns a *NotFoundError when no LinLog was found. +func (llq *LinLogQuery) First(ctx context.Context) (*LinLog, error) { + nodes, err := llq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linlog.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (llq *LinLogQuery) FirstX(ctx context.Context) *LinLog { + node, err := llq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinLog ID from the query. +// Returns a *NotFoundError when no LinLog ID was found. +func (llq *LinLogQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = llq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linlog.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (llq *LinLogQuery) FirstIDX(ctx context.Context) int { + id, err := llq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinLog entity from the query. +// Returns a *NotFoundError when no LinLog was found. +func (llq *LinLogQuery) Last(ctx context.Context) (*LinLog, error) { + nodes, err := llq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linlog.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (llq *LinLogQuery) LastX(ctx context.Context) *LinLog { + node, err := llq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinLog ID from the query. +// Returns a *NotFoundError when no LinLog ID was found. +func (llq *LinLogQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = llq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linlog.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (llq *LinLogQuery) LastIDX(ctx context.Context) int { + id, err := llq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinLog entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinLog entity is not found. +// Returns a *NotFoundError when no LinLog entities are found. +func (llq *LinLogQuery) Only(ctx context.Context) (*LinLog, error) { + nodes, err := llq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linlog.Label} + default: + return nil, &NotSingularError{linlog.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (llq *LinLogQuery) OnlyX(ctx context.Context) *LinLog { + node, err := llq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinLog ID in the query. +// Returns a *NotSingularError when exactly one LinLog ID is not found. +// Returns a *NotFoundError when no entities are found. +func (llq *LinLogQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = llq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linlog.Label} + default: + err = &NotSingularError{linlog.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (llq *LinLogQuery) OnlyIDX(ctx context.Context) int { + id, err := llq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinLogs. +func (llq *LinLogQuery) All(ctx context.Context) ([]*LinLog, error) { + if err := llq.prepareQuery(ctx); err != nil { + return nil, err + } + return llq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (llq *LinLogQuery) AllX(ctx context.Context) []*LinLog { + nodes, err := llq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinLog IDs. +func (llq *LinLogQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := llq.Select(linlog.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (llq *LinLogQuery) IDsX(ctx context.Context) []int { + ids, err := llq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (llq *LinLogQuery) Count(ctx context.Context) (int, error) { + if err := llq.prepareQuery(ctx); err != nil { + return 0, err + } + return llq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (llq *LinLogQuery) CountX(ctx context.Context) int { + count, err := llq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (llq *LinLogQuery) Exist(ctx context.Context) (bool, error) { + if err := llq.prepareQuery(ctx); err != nil { + return false, err + } + return llq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (llq *LinLogQuery) ExistX(ctx context.Context) bool { + exist, err := llq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinLogQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (llq *LinLogQuery) Clone() *LinLogQuery { + if llq == nil { + return nil + } + return &LinLogQuery{ + config: llq.config, + limit: llq.limit, + offset: llq.offset, + order: append([]OrderFunc{}, llq.order...), + predicates: append([]predicate.LinLog{}, llq.predicates...), + // clone intermediate query. + sql: llq.sql.Clone(), + path: llq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinLog.Query(). +// GroupBy(linlog.FieldCreateTime). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (llq *LinLogQuery) GroupBy(field string, fields ...string) *LinLogGroupBy { + group := &LinLogGroupBy{config: llq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := llq.prepareQuery(ctx); err != nil { + return nil, err + } + return llq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.LinLog.Query(). +// Select(linlog.FieldCreateTime). +// Scan(ctx, &v) +// +func (llq *LinLogQuery) Select(fields ...string) *LinLogSelect { + llq.fields = append(llq.fields, fields...) + return &LinLogSelect{LinLogQuery: llq} +} + +func (llq *LinLogQuery) prepareQuery(ctx context.Context) error { + for _, f := range llq.fields { + if !linlog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if llq.path != nil { + prev, err := llq.path(ctx) + if err != nil { + return err + } + llq.sql = prev + } + return nil +} + +func (llq *LinLogQuery) sqlAll(ctx context.Context) ([]*LinLog, error) { + var ( + nodes = []*LinLog{} + _spec = llq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinLog{config: llq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, llq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (llq *LinLogQuery) sqlCount(ctx context.Context) (int, error) { + _spec := llq.querySpec() + return sqlgraph.CountNodes(ctx, llq.driver, _spec) +} + +func (llq *LinLogQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := llq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (llq *LinLogQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + Columns: linlog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + From: llq.sql, + Unique: true, + } + if unique := llq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := llq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linlog.FieldID) + for i := range fields { + if fields[i] != linlog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := llq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := llq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := llq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := llq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (llq *LinLogQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(llq.driver.Dialect()) + t1 := builder.Table(linlog.Table) + columns := llq.fields + if len(columns) == 0 { + columns = linlog.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if llq.sql != nil { + selector = llq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range llq.predicates { + p(selector) + } + for _, p := range llq.order { + p(selector) + } + if offset := llq.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 := llq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinLogGroupBy is the group-by builder for LinLog entities. +type LinLogGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (llgb *LinLogGroupBy) Aggregate(fns ...AggregateFunc) *LinLogGroupBy { + llgb.fns = append(llgb.fns, fns...) + return llgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (llgb *LinLogGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := llgb.path(ctx) + if err != nil { + return err + } + llgb.sql = query + return llgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (llgb *LinLogGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := llgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (llgb *LinLogGroupBy) StringsX(ctx context.Context) []string { + v, err := llgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = llgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (llgb *LinLogGroupBy) StringX(ctx context.Context) string { + v, err := llgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (llgb *LinLogGroupBy) IntsX(ctx context.Context) []int { + v, err := llgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = llgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (llgb *LinLogGroupBy) IntX(ctx context.Context) int { + v, err := llgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (llgb *LinLogGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := llgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = llgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (llgb *LinLogGroupBy) Float64X(ctx context.Context) float64 { + v, err := llgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(llgb.fields) > 1 { + return nil, errors.New("model: LinLogGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := llgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (llgb *LinLogGroupBy) BoolsX(ctx context.Context) []bool { + v, err := llgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (llgb *LinLogGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = llgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (llgb *LinLogGroupBy) BoolX(ctx context.Context) bool { + v, err := llgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (llgb *LinLogGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range llgb.fields { + if !linlog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := llgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := llgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (llgb *LinLogGroupBy) sqlQuery() *sql.Selector { + selector := llgb.sql.Select() + aggregation := make([]string, 0, len(llgb.fns)) + for _, fn := range llgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(llgb.fields)+len(llgb.fns)) + for _, f := range llgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(llgb.fields...)...) +} + +// LinLogSelect is the builder for selecting fields of LinLog entities. +type LinLogSelect struct { + *LinLogQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lls *LinLogSelect) Scan(ctx context.Context, v interface{}) error { + if err := lls.prepareQuery(ctx); err != nil { + return err + } + lls.sql = lls.LinLogQuery.sqlQuery(ctx) + return lls.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lls *LinLogSelect) ScanX(ctx context.Context, v interface{}) { + if err := lls.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Strings(ctx context.Context) ([]string, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lls *LinLogSelect) StringsX(ctx context.Context) []string { + v, err := lls.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lls.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lls *LinLogSelect) StringX(ctx context.Context) string { + v, err := lls.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Ints(ctx context.Context) ([]int, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lls *LinLogSelect) IntsX(ctx context.Context) []int { + v, err := lls.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lls.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lls *LinLogSelect) IntX(ctx context.Context) int { + v, err := lls.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lls *LinLogSelect) Float64sX(ctx context.Context) []float64 { + v, err := lls.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lls.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lls *LinLogSelect) Float64X(ctx context.Context) float64 { + v, err := lls.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lls.fields) > 1 { + return nil, errors.New("model: LinLogSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lls.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lls *LinLogSelect) BoolsX(ctx context.Context) []bool { + v, err := lls.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lls *LinLogSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lls.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linlog.Label} + default: + err = fmt.Errorf("model: LinLogSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lls *LinLogSelect) BoolX(ctx context.Context) bool { + v, err := lls.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lls *LinLogSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lls.sql.Query() + if err := lls.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linlog_update.go b/internal/data/model/linlog_update.go new file mode 100644 index 0000000..7b53bc4 --- /dev/null +++ b/internal/data/model/linlog_update.go @@ -0,0 +1,563 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinLogUpdate is the builder for updating LinLog entities. +type LinLogUpdate struct { + config + hooks []Hook + mutation *LinLogMutation +} + +// Where appends a list predicates to the LinLogUpdate builder. +func (llu *LinLogUpdate) Where(ps ...predicate.LinLog) *LinLogUpdate { + llu.mutation.Where(ps...) + return llu +} + +// SetUpdateTime sets the "update_time" field. +func (llu *LinLogUpdate) SetUpdateTime(t time.Time) *LinLogUpdate { + llu.mutation.SetUpdateTime(t) + return llu +} + +// SetDeleteTime sets the "delete_time" field. +func (llu *LinLogUpdate) SetDeleteTime(t time.Time) *LinLogUpdate { + llu.mutation.SetDeleteTime(t) + return llu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (llu *LinLogUpdate) SetNillableDeleteTime(t *time.Time) *LinLogUpdate { + if t != nil { + llu.SetDeleteTime(*t) + } + return llu +} + +// SetMessage sets the "message" field. +func (llu *LinLogUpdate) SetMessage(s string) *LinLogUpdate { + llu.mutation.SetMessage(s) + return llu +} + +// SetUserID sets the "user_id" field. +func (llu *LinLogUpdate) SetUserID(i int) *LinLogUpdate { + llu.mutation.ResetUserID() + llu.mutation.SetUserID(i) + return llu +} + +// AddUserID adds i to the "user_id" field. +func (llu *LinLogUpdate) AddUserID(i int) *LinLogUpdate { + llu.mutation.AddUserID(i) + return llu +} + +// SetUsername sets the "username" field. +func (llu *LinLogUpdate) SetUsername(s string) *LinLogUpdate { + llu.mutation.SetUsername(s) + return llu +} + +// SetStatusCode sets the "status_code" field. +func (llu *LinLogUpdate) SetStatusCode(i int) *LinLogUpdate { + llu.mutation.ResetStatusCode() + llu.mutation.SetStatusCode(i) + return llu +} + +// AddStatusCode adds i to the "status_code" field. +func (llu *LinLogUpdate) AddStatusCode(i int) *LinLogUpdate { + llu.mutation.AddStatusCode(i) + return llu +} + +// SetMethod sets the "method" field. +func (llu *LinLogUpdate) SetMethod(s string) *LinLogUpdate { + llu.mutation.SetMethod(s) + return llu +} + +// SetPath sets the "path" field. +func (llu *LinLogUpdate) SetPath(s string) *LinLogUpdate { + llu.mutation.SetPath(s) + return llu +} + +// SetPermission sets the "permission" field. +func (llu *LinLogUpdate) SetPermission(s string) *LinLogUpdate { + llu.mutation.SetPermission(s) + return llu +} + +// Mutation returns the LinLogMutation object of the builder. +func (llu *LinLogUpdate) Mutation() *LinLogMutation { + return llu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (llu *LinLogUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + llu.defaults() + if len(llu.hooks) == 0 { + affected, err = llu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + llu.mutation = mutation + affected, err = llu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(llu.hooks) - 1; i >= 0; i-- { + if llu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = llu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, llu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (llu *LinLogUpdate) SaveX(ctx context.Context) int { + affected, err := llu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (llu *LinLogUpdate) Exec(ctx context.Context) error { + _, err := llu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (llu *LinLogUpdate) ExecX(ctx context.Context) { + if err := llu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (llu *LinLogUpdate) defaults() { + if _, ok := llu.mutation.UpdateTime(); !ok { + v := linlog.UpdateDefaultUpdateTime() + llu.mutation.SetUpdateTime(v) + } +} + +func (llu *LinLogUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + Columns: linlog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + } + if ps := llu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := llu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldUpdateTime, + }) + } + if value, ok := llu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldDeleteTime, + }) + } + if value, ok := llu.mutation.Message(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMessage, + }) + } + if value, ok := llu.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := llu.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := llu.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldUsername, + }) + } + if value, ok := llu.mutation.StatusCode(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := llu.mutation.AddedStatusCode(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := llu.mutation.Method(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMethod, + }) + } + if value, ok := llu.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPath, + }) + } + if value, ok := llu.mutation.Permission(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPermission, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, llu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linlog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinLogUpdateOne is the builder for updating a single LinLog entity. +type LinLogUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinLogMutation +} + +// SetUpdateTime sets the "update_time" field. +func (lluo *LinLogUpdateOne) SetUpdateTime(t time.Time) *LinLogUpdateOne { + lluo.mutation.SetUpdateTime(t) + return lluo +} + +// SetDeleteTime sets the "delete_time" field. +func (lluo *LinLogUpdateOne) SetDeleteTime(t time.Time) *LinLogUpdateOne { + lluo.mutation.SetDeleteTime(t) + return lluo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (lluo *LinLogUpdateOne) SetNillableDeleteTime(t *time.Time) *LinLogUpdateOne { + if t != nil { + lluo.SetDeleteTime(*t) + } + return lluo +} + +// SetMessage sets the "message" field. +func (lluo *LinLogUpdateOne) SetMessage(s string) *LinLogUpdateOne { + lluo.mutation.SetMessage(s) + return lluo +} + +// SetUserID sets the "user_id" field. +func (lluo *LinLogUpdateOne) SetUserID(i int) *LinLogUpdateOne { + lluo.mutation.ResetUserID() + lluo.mutation.SetUserID(i) + return lluo +} + +// AddUserID adds i to the "user_id" field. +func (lluo *LinLogUpdateOne) AddUserID(i int) *LinLogUpdateOne { + lluo.mutation.AddUserID(i) + return lluo +} + +// SetUsername sets the "username" field. +func (lluo *LinLogUpdateOne) SetUsername(s string) *LinLogUpdateOne { + lluo.mutation.SetUsername(s) + return lluo +} + +// SetStatusCode sets the "status_code" field. +func (lluo *LinLogUpdateOne) SetStatusCode(i int) *LinLogUpdateOne { + lluo.mutation.ResetStatusCode() + lluo.mutation.SetStatusCode(i) + return lluo +} + +// AddStatusCode adds i to the "status_code" field. +func (lluo *LinLogUpdateOne) AddStatusCode(i int) *LinLogUpdateOne { + lluo.mutation.AddStatusCode(i) + return lluo +} + +// SetMethod sets the "method" field. +func (lluo *LinLogUpdateOne) SetMethod(s string) *LinLogUpdateOne { + lluo.mutation.SetMethod(s) + return lluo +} + +// SetPath sets the "path" field. +func (lluo *LinLogUpdateOne) SetPath(s string) *LinLogUpdateOne { + lluo.mutation.SetPath(s) + return lluo +} + +// SetPermission sets the "permission" field. +func (lluo *LinLogUpdateOne) SetPermission(s string) *LinLogUpdateOne { + lluo.mutation.SetPermission(s) + return lluo +} + +// Mutation returns the LinLogMutation object of the builder. +func (lluo *LinLogUpdateOne) Mutation() *LinLogMutation { + return lluo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lluo *LinLogUpdateOne) Select(field string, fields ...string) *LinLogUpdateOne { + lluo.fields = append([]string{field}, fields...) + return lluo +} + +// Save executes the query and returns the updated LinLog entity. +func (lluo *LinLogUpdateOne) Save(ctx context.Context) (*LinLog, error) { + var ( + err error + node *LinLog + ) + lluo.defaults() + if len(lluo.hooks) == 0 { + node, err = lluo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinLogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lluo.mutation = mutation + node, err = lluo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lluo.hooks) - 1; i >= 0; i-- { + if lluo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lluo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lluo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lluo *LinLogUpdateOne) SaveX(ctx context.Context) *LinLog { + node, err := lluo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lluo *LinLogUpdateOne) Exec(ctx context.Context) error { + _, err := lluo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lluo *LinLogUpdateOne) ExecX(ctx context.Context) { + if err := lluo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (lluo *LinLogUpdateOne) defaults() { + if _, ok := lluo.mutation.UpdateTime(); !ok { + v := linlog.UpdateDefaultUpdateTime() + lluo.mutation.SetUpdateTime(v) + } +} + +func (lluo *LinLogUpdateOne) sqlSave(ctx context.Context) (_node *LinLog, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linlog.Table, + Columns: linlog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linlog.FieldID, + }, + }, + } + id, ok := lluo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinLog.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lluo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linlog.FieldID) + for _, f := range fields { + if !linlog.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linlog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lluo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lluo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldUpdateTime, + }) + } + if value, ok := lluo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linlog.FieldDeleteTime, + }) + } + if value, ok := lluo.mutation.Message(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMessage, + }) + } + if value, ok := lluo.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := lluo.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldUserID, + }) + } + if value, ok := lluo.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldUsername, + }) + } + if value, ok := lluo.mutation.StatusCode(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := lluo.mutation.AddedStatusCode(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linlog.FieldStatusCode, + }) + } + if value, ok := lluo.mutation.Method(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldMethod, + }) + } + if value, ok := lluo.mutation.Path(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPath, + }) + } + if value, ok := lluo.mutation.Permission(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linlog.FieldPermission, + }) + } + _node = &LinLog{config: lluo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lluo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linlog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linpermission.go b/internal/data/model/linpermission.go new file mode 100644 index 0000000..f2acd85 --- /dev/null +++ b/internal/data/model/linpermission.go @@ -0,0 +1,148 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linpermission" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinPermission is the model entity for the LinPermission schema. +type LinPermission struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + // 权限名称,例如:访问首页 + Name string `json:"name,omitempty"` + // Module holds the value of the "module" field. + // 权限所属模块,例如:人员管理 + Module string `json:"module,omitempty"` + // Mount holds the value of the "mount" field. + // 0:关闭 1:开启 + Mount int8 `json:"mount,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinPermissionQuery when eager-loading is set. + Edges LinPermissionEdges `json:"edges"` +} + +// LinPermissionEdges holds the relations/edges for other nodes in the graph. +type LinPermissionEdges struct { + // LinGroup holds the value of the lin_group edge. + LinGroup []*LinGroup `json:"lin_group,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// LinGroupOrErr returns the LinGroup value or an error if the edge +// was not loaded in eager-loading. +func (e LinPermissionEdges) LinGroupOrErr() ([]*LinGroup, error) { + if e.loadedTypes[0] { + return e.LinGroup, nil + } + return nil, &NotLoadedError{edge: "lin_group"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinPermission) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linpermission.FieldID, linpermission.FieldMount: + values[i] = new(sql.NullInt64) + case linpermission.FieldName, linpermission.FieldModule: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type LinPermission", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinPermission fields. +func (lp *LinPermission) assignValues(columns []string, values []interface{}) 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 linpermission.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lp.ID = int(value.Int64) + case linpermission.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + lp.Name = value.String + } + case linpermission.FieldModule: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field module", values[i]) + } else if value.Valid { + lp.Module = value.String + } + case linpermission.FieldMount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field mount", values[i]) + } else if value.Valid { + lp.Mount = int8(value.Int64) + } + } + } + return nil +} + +// QueryLinGroup queries the "lin_group" edge of the LinPermission entity. +func (lp *LinPermission) QueryLinGroup() *LinGroupQuery { + return (&LinPermissionClient{config: lp.config}).QueryLinGroup(lp) +} + +// Update returns a builder for updating this LinPermission. +// Note that you need to call LinPermission.Unwrap() before calling this method if this LinPermission +// was returned from a transaction, and the transaction was committed or rolled back. +func (lp *LinPermission) Update() *LinPermissionUpdateOne { + return (&LinPermissionClient{config: lp.config}).UpdateOne(lp) +} + +// Unwrap unwraps the LinPermission 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 (lp *LinPermission) Unwrap() *LinPermission { + tx, ok := lp.config.driver.(*txDriver) + if !ok { + panic("model: LinPermission is not a transactional entity") + } + lp.config.driver = tx.drv + return lp +} + +// String implements the fmt.Stringer. +func (lp *LinPermission) String() string { + var builder strings.Builder + builder.WriteString("LinPermission(") + builder.WriteString(fmt.Sprintf("id=%v", lp.ID)) + builder.WriteString(", name=") + builder.WriteString(lp.Name) + builder.WriteString(", module=") + builder.WriteString(lp.Module) + builder.WriteString(", mount=") + builder.WriteString(fmt.Sprintf("%v", lp.Mount)) + builder.WriteByte(')') + return builder.String() +} + +// LinPermissions is a parsable slice of LinPermission. +type LinPermissions []*LinPermission + +func (lp LinPermissions) config(cfg config) { + for _i := range lp { + lp[_i].config = cfg + } +} diff --git a/internal/data/model/linpermission/linpermission.go b/internal/data/model/linpermission/linpermission.go new file mode 100644 index 0000000..22ae0a7 --- /dev/null +++ b/internal/data/model/linpermission/linpermission.go @@ -0,0 +1,49 @@ +// Code generated by entc, DO NOT EDIT. + +package linpermission + +const ( + // Label holds the string label denoting the linpermission type in the database. + Label = "lin_permission" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldModule holds the string denoting the module field in the database. + FieldModule = "module" + // FieldMount holds the string denoting the mount field in the database. + FieldMount = "mount" + // EdgeLinGroup holds the string denoting the lin_group edge name in mutations. + EdgeLinGroup = "lin_group" + // Table holds the table name of the linpermission in the database. + Table = "lin_permission" + // LinGroupTable is the table that holds the lin_group relation/edge. The primary key declared below. + LinGroupTable = "lin_group_permission" + // LinGroupInverseTable is the table name for the LinGroup entity. + // It exists in this package in order to avoid circular dependency with the "lingroup" package. + LinGroupInverseTable = "lin_group" +) + +// Columns holds all SQL columns for linpermission fields. +var Columns = []string{ + FieldID, + FieldName, + FieldModule, + FieldMount, +} + +var ( + // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the + // primary key for the lin_group relation (M2M). + LinGroupPrimaryKey = []string{"permission_id", "group_id"} +) + +// 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 +} diff --git a/internal/data/model/linpermission/where.go b/internal/data/model/linpermission/where.go new file mode 100644 index 0000000..a28e920 --- /dev/null +++ b/internal/data/model/linpermission/where.go @@ -0,0 +1,472 @@ +// Code generated by entc, DO NOT EDIT. + +package linpermission + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Module applies equality check predicate on the "module" field. It's identical to ModuleEQ. +func Module(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldModule), v)) + }) +} + +// Mount applies equality check predicate on the "mount" field. It's identical to MountEQ. +func Mount(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMount), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// ModuleEQ applies the EQ predicate on the "module" field. +func ModuleEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldModule), v)) + }) +} + +// ModuleNEQ applies the NEQ predicate on the "module" field. +func ModuleNEQ(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldModule), v)) + }) +} + +// ModuleIn applies the In predicate on the "module" field. +func ModuleIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldModule), v...)) + }) +} + +// ModuleNotIn applies the NotIn predicate on the "module" field. +func ModuleNotIn(vs ...string) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldModule), v...)) + }) +} + +// ModuleGT applies the GT predicate on the "module" field. +func ModuleGT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldModule), v)) + }) +} + +// ModuleGTE applies the GTE predicate on the "module" field. +func ModuleGTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldModule), v)) + }) +} + +// ModuleLT applies the LT predicate on the "module" field. +func ModuleLT(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldModule), v)) + }) +} + +// ModuleLTE applies the LTE predicate on the "module" field. +func ModuleLTE(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldModule), v)) + }) +} + +// ModuleContains applies the Contains predicate on the "module" field. +func ModuleContains(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldModule), v)) + }) +} + +// ModuleHasPrefix applies the HasPrefix predicate on the "module" field. +func ModuleHasPrefix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldModule), v)) + }) +} + +// ModuleHasSuffix applies the HasSuffix predicate on the "module" field. +func ModuleHasSuffix(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldModule), v)) + }) +} + +// ModuleEqualFold applies the EqualFold predicate on the "module" field. +func ModuleEqualFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldModule), v)) + }) +} + +// ModuleContainsFold applies the ContainsFold predicate on the "module" field. +func ModuleContainsFold(v string) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldModule), v)) + }) +} + +// MountEQ applies the EQ predicate on the "mount" field. +func MountEQ(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldMount), v)) + }) +} + +// MountNEQ applies the NEQ predicate on the "mount" field. +func MountNEQ(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldMount), v)) + }) +} + +// MountIn applies the In predicate on the "mount" field. +func MountIn(vs ...int8) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldMount), v...)) + }) +} + +// MountNotIn applies the NotIn predicate on the "mount" field. +func MountNotIn(vs ...int8) predicate.LinPermission { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinPermission(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldMount), v...)) + }) +} + +// MountGT applies the GT predicate on the "mount" field. +func MountGT(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldMount), v)) + }) +} + +// MountGTE applies the GTE predicate on the "mount" field. +func MountGTE(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldMount), v)) + }) +} + +// MountLT applies the LT predicate on the "mount" field. +func MountLT(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldMount), v)) + }) +} + +// MountLTE applies the LTE predicate on the "mount" field. +func MountLTE(v int8) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldMount), v)) + }) +} + +// HasLinGroup applies the HasEdge predicate on the "lin_group" edge. +func HasLinGroup() predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinGroupTable, LinGroupPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinGroupWith applies the HasEdge predicate on the "lin_group" edge with a given conditions (other predicates). +func HasLinGroupWith(preds ...predicate.LinGroup) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinGroupTable, LinGroupPrimaryKey...), + ) + 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.LinPermission) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinPermission) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinPermission) predicate.LinPermission { + return predicate.LinPermission(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linpermission_create.go b/internal/data/model/linpermission_create.go new file mode 100644 index 0000000..01e3d9b --- /dev/null +++ b/internal/data/model/linpermission_create.go @@ -0,0 +1,289 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionCreate is the builder for creating a LinPermission entity. +type LinPermissionCreate struct { + config + mutation *LinPermissionMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (lpc *LinPermissionCreate) SetName(s string) *LinPermissionCreate { + lpc.mutation.SetName(s) + return lpc +} + +// SetModule sets the "module" field. +func (lpc *LinPermissionCreate) SetModule(s string) *LinPermissionCreate { + lpc.mutation.SetModule(s) + return lpc +} + +// SetMount sets the "mount" field. +func (lpc *LinPermissionCreate) SetMount(i int8) *LinPermissionCreate { + lpc.mutation.SetMount(i) + return lpc +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (lpc *LinPermissionCreate) AddLinGroupIDs(ids ...int) *LinPermissionCreate { + lpc.mutation.AddLinGroupIDs(ids...) + return lpc +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (lpc *LinPermissionCreate) AddLinGroup(l ...*LinGroup) *LinPermissionCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpc.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinPermissionMutation object of the builder. +func (lpc *LinPermissionCreate) Mutation() *LinPermissionMutation { + return lpc.mutation +} + +// Save creates the LinPermission in the database. +func (lpc *LinPermissionCreate) Save(ctx context.Context) (*LinPermission, error) { + var ( + err error + node *LinPermission + ) + if len(lpc.hooks) == 0 { + if err = lpc.check(); err != nil { + return nil, err + } + node, err = lpc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = lpc.check(); err != nil { + return nil, err + } + lpc.mutation = mutation + if node, err = lpc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(lpc.hooks) - 1; i >= 0; i-- { + if lpc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (lpc *LinPermissionCreate) SaveX(ctx context.Context) *LinPermission { + v, err := lpc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lpc *LinPermissionCreate) Exec(ctx context.Context) error { + _, err := lpc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpc *LinPermissionCreate) ExecX(ctx context.Context) { + if err := lpc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lpc *LinPermissionCreate) check() error { + if _, ok := lpc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} + } + if _, ok := lpc.mutation.Module(); !ok { + return &ValidationError{Name: "module", err: errors.New(`model: missing required field "module"`)} + } + if _, ok := lpc.mutation.Mount(); !ok { + return &ValidationError{Name: "mount", err: errors.New(`model: missing required field "mount"`)} + } + return nil +} + +func (lpc *LinPermissionCreate) sqlSave(ctx context.Context) (*LinPermission, error) { + _node, _spec := lpc.createSpec() + if err := sqlgraph.CreateNode(ctx, lpc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (lpc *LinPermissionCreate) createSpec() (*LinPermission, *sqlgraph.CreateSpec) { + var ( + _node = &LinPermission{config: lpc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linpermission.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + } + ) + if value, ok := lpc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldName, + }) + _node.Name = value + } + if value, ok := lpc.mutation.Module(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldModule, + }) + _node.Module = value + } + if value, ok := lpc.mutation.Mount(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + _node.Mount = value + } + if nodes := lpc.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinPermissionCreateBulk is the builder for creating many LinPermission entities in bulk. +type LinPermissionCreateBulk struct { + config + builders []*LinPermissionCreate +} + +// Save creates the LinPermission entities in the database. +func (lpcb *LinPermissionCreateBulk) Save(ctx context.Context) ([]*LinPermission, error) { + specs := make([]*sqlgraph.CreateSpec, len(lpcb.builders)) + nodes := make([]*LinPermission, len(lpcb.builders)) + mutators := make([]Mutator, len(lpcb.builders)) + for i := range lpcb.builders { + func(i int, root context.Context) { + builder := lpcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lpcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lpcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lpcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lpcb *LinPermissionCreateBulk) SaveX(ctx context.Context) []*LinPermission { + v, err := lpcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lpcb *LinPermissionCreateBulk) Exec(ctx context.Context) error { + _, err := lpcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpcb *LinPermissionCreateBulk) ExecX(ctx context.Context) { + if err := lpcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linpermission_delete.go b/internal/data/model/linpermission_delete.go new file mode 100644 index 0000000..46660ba --- /dev/null +++ b/internal/data/model/linpermission_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionDelete is the builder for deleting a LinPermission entity. +type LinPermissionDelete struct { + config + hooks []Hook + mutation *LinPermissionMutation +} + +// Where appends a list predicates to the LinPermissionDelete builder. +func (lpd *LinPermissionDelete) Where(ps ...predicate.LinPermission) *LinPermissionDelete { + lpd.mutation.Where(ps...) + return lpd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lpd *LinPermissionDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lpd.hooks) == 0 { + affected, err = lpd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lpd.mutation = mutation + affected, err = lpd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lpd.hooks) - 1; i >= 0; i-- { + if lpd.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpd *LinPermissionDelete) ExecX(ctx context.Context) int { + n, err := lpd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lpd *LinPermissionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + if ps := lpd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lpd.driver, _spec) +} + +// LinPermissionDeleteOne is the builder for deleting a single LinPermission entity. +type LinPermissionDeleteOne struct { + lpd *LinPermissionDelete +} + +// Exec executes the deletion query. +func (lpdo *LinPermissionDeleteOne) Exec(ctx context.Context) error { + n, err := lpdo.lpd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linpermission.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpdo *LinPermissionDeleteOne) ExecX(ctx context.Context) { + lpdo.lpd.ExecX(ctx) +} diff --git a/internal/data/model/linpermission_query.go b/internal/data/model/linpermission_query.go new file mode 100644 index 0000000..9ae25bc --- /dev/null +++ b/internal/data/model/linpermission_query.go @@ -0,0 +1,1068 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionQuery is the builder for querying LinPermission entities. +type LinPermissionQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinPermission + // eager-loading edges. + withLinGroup *LinGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinPermissionQuery builder. +func (lpq *LinPermissionQuery) Where(ps ...predicate.LinPermission) *LinPermissionQuery { + lpq.predicates = append(lpq.predicates, ps...) + return lpq +} + +// Limit adds a limit step to the query. +func (lpq *LinPermissionQuery) Limit(limit int) *LinPermissionQuery { + lpq.limit = &limit + return lpq +} + +// Offset adds an offset step to the query. +func (lpq *LinPermissionQuery) Offset(offset int) *LinPermissionQuery { + lpq.offset = &offset + return lpq +} + +// 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 (lpq *LinPermissionQuery) Unique(unique bool) *LinPermissionQuery { + lpq.unique = &unique + return lpq +} + +// Order adds an order step to the query. +func (lpq *LinPermissionQuery) Order(o ...OrderFunc) *LinPermissionQuery { + lpq.order = append(lpq.order, o...) + return lpq +} + +// QueryLinGroup chains the current query on the "lin_group" edge. +func (lpq *LinPermissionQuery) QueryLinGroup() *LinGroupQuery { + query := &LinGroupQuery{config: lpq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lpq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lpq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(linpermission.Table, linpermission.FieldID, selector), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, linpermission.LinGroupTable, linpermission.LinGroupPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lpq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LinPermission entity from the query. +// Returns a *NotFoundError when no LinPermission was found. +func (lpq *LinPermissionQuery) First(ctx context.Context) (*LinPermission, error) { + nodes, err := lpq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linpermission.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lpq *LinPermissionQuery) FirstX(ctx context.Context) *LinPermission { + node, err := lpq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinPermission ID from the query. +// Returns a *NotFoundError when no LinPermission ID was found. +func (lpq *LinPermissionQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lpq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linpermission.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lpq *LinPermissionQuery) FirstIDX(ctx context.Context) int { + id, err := lpq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinPermission entity from the query. +// Returns a *NotFoundError when no LinPermission was found. +func (lpq *LinPermissionQuery) Last(ctx context.Context) (*LinPermission, error) { + nodes, err := lpq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linpermission.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (lpq *LinPermissionQuery) LastX(ctx context.Context) *LinPermission { + node, err := lpq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinPermission ID from the query. +// Returns a *NotFoundError when no LinPermission ID was found. +func (lpq *LinPermissionQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lpq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linpermission.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (lpq *LinPermissionQuery) LastIDX(ctx context.Context) int { + id, err := lpq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinPermission entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinPermission entity is not found. +// Returns a *NotFoundError when no LinPermission entities are found. +func (lpq *LinPermissionQuery) Only(ctx context.Context) (*LinPermission, error) { + nodes, err := lpq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linpermission.Label} + default: + return nil, &NotSingularError{linpermission.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lpq *LinPermissionQuery) OnlyX(ctx context.Context) *LinPermission { + node, err := lpq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinPermission ID in the query. +// Returns a *NotSingularError when exactly one LinPermission ID is not found. +// Returns a *NotFoundError when no entities are found. +func (lpq *LinPermissionQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = lpq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = &NotSingularError{linpermission.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lpq *LinPermissionQuery) OnlyIDX(ctx context.Context) int { + id, err := lpq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinPermissions. +func (lpq *LinPermissionQuery) All(ctx context.Context) ([]*LinPermission, error) { + if err := lpq.prepareQuery(ctx); err != nil { + return nil, err + } + return lpq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (lpq *LinPermissionQuery) AllX(ctx context.Context) []*LinPermission { + nodes, err := lpq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinPermission IDs. +func (lpq *LinPermissionQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := lpq.Select(linpermission.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lpq *LinPermissionQuery) IDsX(ctx context.Context) []int { + ids, err := lpq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lpq *LinPermissionQuery) Count(ctx context.Context) (int, error) { + if err := lpq.prepareQuery(ctx); err != nil { + return 0, err + } + return lpq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (lpq *LinPermissionQuery) CountX(ctx context.Context) int { + count, err := lpq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lpq *LinPermissionQuery) Exist(ctx context.Context) (bool, error) { + if err := lpq.prepareQuery(ctx); err != nil { + return false, err + } + return lpq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (lpq *LinPermissionQuery) ExistX(ctx context.Context) bool { + exist, err := lpq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinPermissionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lpq *LinPermissionQuery) Clone() *LinPermissionQuery { + if lpq == nil { + return nil + } + return &LinPermissionQuery{ + config: lpq.config, + limit: lpq.limit, + offset: lpq.offset, + order: append([]OrderFunc{}, lpq.order...), + predicates: append([]predicate.LinPermission{}, lpq.predicates...), + withLinGroup: lpq.withLinGroup.Clone(), + // clone intermediate query. + sql: lpq.sql.Clone(), + path: lpq.path, + } +} + +// WithLinGroup tells the query-builder to eager-load the nodes that are connected to +// the "lin_group" edge. The optional arguments are used to configure the query builder of the edge. +func (lpq *LinPermissionQuery) WithLinGroup(opts ...func(*LinGroupQuery)) *LinPermissionQuery { + query := &LinGroupQuery{config: lpq.config} + for _, opt := range opts { + opt(query) + } + lpq.withLinGroup = query + return lpq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinPermission.Query(). +// GroupBy(linpermission.FieldName). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (lpq *LinPermissionQuery) GroupBy(field string, fields ...string) *LinPermissionGroupBy { + group := &LinPermissionGroupBy{config: lpq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := lpq.prepareQuery(ctx); err != nil { + return nil, err + } + return lpq.sqlQuery(ctx), nil + } + return group +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.LinPermission.Query(). +// Select(linpermission.FieldName). +// Scan(ctx, &v) +// +func (lpq *LinPermissionQuery) Select(fields ...string) *LinPermissionSelect { + lpq.fields = append(lpq.fields, fields...) + return &LinPermissionSelect{LinPermissionQuery: lpq} +} + +func (lpq *LinPermissionQuery) prepareQuery(ctx context.Context) error { + for _, f := range lpq.fields { + if !linpermission.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if lpq.path != nil { + prev, err := lpq.path(ctx) + if err != nil { + return err + } + lpq.sql = prev + } + return nil +} + +func (lpq *LinPermissionQuery) sqlAll(ctx context.Context) ([]*LinPermission, error) { + var ( + nodes = []*LinPermission{} + _spec = lpq.querySpec() + loadedTypes = [1]bool{ + lpq.withLinGroup != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinPermission{config: lpq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, lpq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := lpq.withLinGroup; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinPermission, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinGroup = []*LinGroup{} + } + var ( + edgeids []int + edges = make(map[int][]*LinPermission) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(linpermission.LinGroupPrimaryKey[0], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, lpq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_group": %w`, err) + } + query.Where(lingroup.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_group" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinGroup = append(nodes[i].Edges.LinGroup, n) + } + } + } + + return nodes, nil +} + +func (lpq *LinPermissionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lpq.querySpec() + return sqlgraph.CountNodes(ctx, lpq.driver, _spec) +} + +func (lpq *LinPermissionQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := lpq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (lpq *LinPermissionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + Columns: linpermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + From: lpq.sql, + Unique: true, + } + if unique := lpq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := lpq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linpermission.FieldID) + for i := range fields { + if fields[i] != linpermission.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lpq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lpq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := lpq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := lpq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lpq *LinPermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lpq.driver.Dialect()) + t1 := builder.Table(linpermission.Table) + columns := lpq.fields + if len(columns) == 0 { + columns = linpermission.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lpq.sql != nil { + selector = lpq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range lpq.predicates { + p(selector) + } + for _, p := range lpq.order { + p(selector) + } + if offset := lpq.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 := lpq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinPermissionGroupBy is the group-by builder for LinPermission entities. +type LinPermissionGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lpgb *LinPermissionGroupBy) Aggregate(fns ...AggregateFunc) *LinPermissionGroupBy { + lpgb.fns = append(lpgb.fns, fns...) + return lpgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lpgb *LinPermissionGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lpgb.path(ctx) + if err != nil { + return err + } + lpgb.sql = query + return lpgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lpgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) StringsX(ctx context.Context) []string { + v, err := lpgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lpgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) StringX(ctx context.Context) string { + v, err := lpgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) IntsX(ctx context.Context) []int { + v, err := lpgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lpgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) IntX(ctx context.Context) int { + v, err := lpgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lpgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lpgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) Float64X(ctx context.Context) float64 { + v, err := lpgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lpgb.fields) > 1 { + return nil, errors.New("model: LinPermissionGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lpgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lpgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lpgb *LinPermissionGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lpgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lpgb *LinPermissionGroupBy) BoolX(ctx context.Context) bool { + v, err := lpgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lpgb *LinPermissionGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lpgb.fields { + if !linpermission.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lpgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lpgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lpgb *LinPermissionGroupBy) sqlQuery() *sql.Selector { + selector := lpgb.sql.Select() + aggregation := make([]string, 0, len(lpgb.fns)) + for _, fn := range lpgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lpgb.fields)+len(lpgb.fns)) + for _, f := range lpgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lpgb.fields...)...) +} + +// LinPermissionSelect is the builder for selecting fields of LinPermission entities. +type LinPermissionSelect struct { + *LinPermissionQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lps *LinPermissionSelect) Scan(ctx context.Context, v interface{}) error { + if err := lps.prepareQuery(ctx); err != nil { + return err + } + lps.sql = lps.LinPermissionQuery.sqlQuery(ctx) + return lps.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lps *LinPermissionSelect) ScanX(ctx context.Context, v interface{}) { + if err := lps.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Strings(ctx context.Context) ([]string, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lps *LinPermissionSelect) StringsX(ctx context.Context) []string { + v, err := lps.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lps.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lps *LinPermissionSelect) StringX(ctx context.Context) string { + v, err := lps.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Ints(ctx context.Context) ([]int, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lps *LinPermissionSelect) IntsX(ctx context.Context) []int { + v, err := lps.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lps.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lps *LinPermissionSelect) IntX(ctx context.Context) int { + v, err := lps.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lps *LinPermissionSelect) Float64sX(ctx context.Context) []float64 { + v, err := lps.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lps.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lps *LinPermissionSelect) Float64X(ctx context.Context) float64 { + v, err := lps.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lps.fields) > 1 { + return nil, errors.New("model: LinPermissionSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lps.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lps *LinPermissionSelect) BoolsX(ctx context.Context) []bool { + v, err := lps.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lps *LinPermissionSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lps.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linpermission.Label} + default: + err = fmt.Errorf("model: LinPermissionSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lps *LinPermissionSelect) BoolX(ctx context.Context) bool { + v, err := lps.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lps *LinPermissionSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lps.sql.Query() + if err := lps.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linpermission_update.go b/internal/data/model/linpermission_update.go new file mode 100644 index 0000000..cbc1e37 --- /dev/null +++ b/internal/data/model/linpermission_update.go @@ -0,0 +1,525 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinPermissionUpdate is the builder for updating LinPermission entities. +type LinPermissionUpdate struct { + config + hooks []Hook + mutation *LinPermissionMutation +} + +// Where appends a list predicates to the LinPermissionUpdate builder. +func (lpu *LinPermissionUpdate) Where(ps ...predicate.LinPermission) *LinPermissionUpdate { + lpu.mutation.Where(ps...) + return lpu +} + +// SetName sets the "name" field. +func (lpu *LinPermissionUpdate) SetName(s string) *LinPermissionUpdate { + lpu.mutation.SetName(s) + return lpu +} + +// SetModule sets the "module" field. +func (lpu *LinPermissionUpdate) SetModule(s string) *LinPermissionUpdate { + lpu.mutation.SetModule(s) + return lpu +} + +// SetMount sets the "mount" field. +func (lpu *LinPermissionUpdate) SetMount(i int8) *LinPermissionUpdate { + lpu.mutation.ResetMount() + lpu.mutation.SetMount(i) + return lpu +} + +// AddMount adds i to the "mount" field. +func (lpu *LinPermissionUpdate) AddMount(i int8) *LinPermissionUpdate { + lpu.mutation.AddMount(i) + return lpu +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (lpu *LinPermissionUpdate) AddLinGroupIDs(ids ...int) *LinPermissionUpdate { + lpu.mutation.AddLinGroupIDs(ids...) + return lpu +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (lpu *LinPermissionUpdate) AddLinGroup(l ...*LinGroup) *LinPermissionUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpu.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinPermissionMutation object of the builder. +func (lpu *LinPermissionUpdate) Mutation() *LinPermissionMutation { + return lpu.mutation +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (lpu *LinPermissionUpdate) ClearLinGroup() *LinPermissionUpdate { + lpu.mutation.ClearLinGroup() + return lpu +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (lpu *LinPermissionUpdate) RemoveLinGroupIDs(ids ...int) *LinPermissionUpdate { + lpu.mutation.RemoveLinGroupIDs(ids...) + return lpu +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (lpu *LinPermissionUpdate) RemoveLinGroup(l ...*LinGroup) *LinPermissionUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpu.RemoveLinGroupIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lpu *LinPermissionUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lpu.hooks) == 0 { + affected, err = lpu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lpu.mutation = mutation + affected, err = lpu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(lpu.hooks) - 1; i >= 0; i-- { + if lpu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lpu *LinPermissionUpdate) SaveX(ctx context.Context) int { + affected, err := lpu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lpu *LinPermissionUpdate) Exec(ctx context.Context) error { + _, err := lpu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpu *LinPermissionUpdate) ExecX(ctx context.Context) { + if err := lpu.Exec(ctx); err != nil { + panic(err) + } +} + +func (lpu *LinPermissionUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + Columns: linpermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + if ps := lpu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lpu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldName, + }) + } + if value, ok := lpu.mutation.Module(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldModule, + }) + } + if value, ok := lpu.mutation.Mount(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if value, ok := lpu.mutation.AddedMount(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if lpu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpu.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !lpu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpu.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, lpu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linpermission.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinPermissionUpdateOne is the builder for updating a single LinPermission entity. +type LinPermissionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinPermissionMutation +} + +// SetName sets the "name" field. +func (lpuo *LinPermissionUpdateOne) SetName(s string) *LinPermissionUpdateOne { + lpuo.mutation.SetName(s) + return lpuo +} + +// SetModule sets the "module" field. +func (lpuo *LinPermissionUpdateOne) SetModule(s string) *LinPermissionUpdateOne { + lpuo.mutation.SetModule(s) + return lpuo +} + +// SetMount sets the "mount" field. +func (lpuo *LinPermissionUpdateOne) SetMount(i int8) *LinPermissionUpdateOne { + lpuo.mutation.ResetMount() + lpuo.mutation.SetMount(i) + return lpuo +} + +// AddMount adds i to the "mount" field. +func (lpuo *LinPermissionUpdateOne) AddMount(i int8) *LinPermissionUpdateOne { + lpuo.mutation.AddMount(i) + return lpuo +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (lpuo *LinPermissionUpdateOne) AddLinGroupIDs(ids ...int) *LinPermissionUpdateOne { + lpuo.mutation.AddLinGroupIDs(ids...) + return lpuo +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (lpuo *LinPermissionUpdateOne) AddLinGroup(l ...*LinGroup) *LinPermissionUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpuo.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinPermissionMutation object of the builder. +func (lpuo *LinPermissionUpdateOne) Mutation() *LinPermissionMutation { + return lpuo.mutation +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (lpuo *LinPermissionUpdateOne) ClearLinGroup() *LinPermissionUpdateOne { + lpuo.mutation.ClearLinGroup() + return lpuo +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (lpuo *LinPermissionUpdateOne) RemoveLinGroupIDs(ids ...int) *LinPermissionUpdateOne { + lpuo.mutation.RemoveLinGroupIDs(ids...) + return lpuo +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (lpuo *LinPermissionUpdateOne) RemoveLinGroup(l ...*LinGroup) *LinPermissionUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return lpuo.RemoveLinGroupIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (lpuo *LinPermissionUpdateOne) Select(field string, fields ...string) *LinPermissionUpdateOne { + lpuo.fields = append([]string{field}, fields...) + return lpuo +} + +// Save executes the query and returns the updated LinPermission entity. +func (lpuo *LinPermissionUpdateOne) Save(ctx context.Context) (*LinPermission, error) { + var ( + err error + node *LinPermission + ) + if len(lpuo.hooks) == 0 { + node, err = lpuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinPermissionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lpuo.mutation = mutation + node, err = lpuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(lpuo.hooks) - 1; i >= 0; i-- { + if lpuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lpuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lpuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (lpuo *LinPermissionUpdateOne) SaveX(ctx context.Context) *LinPermission { + node, err := lpuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (lpuo *LinPermissionUpdateOne) Exec(ctx context.Context) error { + _, err := lpuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lpuo *LinPermissionUpdateOne) ExecX(ctx context.Context) { + if err := lpuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (lpuo *LinPermissionUpdateOne) sqlSave(ctx context.Context) (_node *LinPermission, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linpermission.Table, + Columns: linpermission.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linpermission.FieldID, + }, + }, + } + id, ok := lpuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinPermission.ID for update")} + } + _spec.Node.ID.Value = id + if fields := lpuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linpermission.FieldID) + for _, f := range fields { + if !linpermission.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linpermission.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := lpuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lpuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldName, + }) + } + if value, ok := lpuo.mutation.Module(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linpermission.FieldModule, + }) + } + if value, ok := lpuo.mutation.Mount(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if value, ok := lpuo.mutation.AddedMount(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt8, + Value: value, + Column: linpermission.FieldMount, + }) + } + if lpuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpuo.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !lpuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lpuo.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: linpermission.LinGroupTable, + Columns: linpermission.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LinPermission{config: lpuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, lpuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linpermission.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linuser.go b/internal/data/model/linuser.go new file mode 100644 index 0000000..1a587e7 --- /dev/null +++ b/internal/data/model/linuser.go @@ -0,0 +1,208 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linuser" + "strings" + "time" + + "entgo.io/ent/dialect/sql" +) + +// LinUser is the model entity for the LinUser schema. +type LinUser struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` + // Username holds the value of the "username" field. + // 用户名,唯一 + Username string `json:"username,omitempty"` + // Nickname holds the value of the "nickname" field. + // 用户昵称 + Nickname string `json:"nickname,omitempty"` + // Avatar holds the value of the "avatar" field. + // 头像url + Avatar string `json:"avatar,omitempty"` + // Email holds the value of the "email" field. + // 邮箱 + Email string `json:"email,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinUserQuery when eager-loading is set. + Edges LinUserEdges `json:"edges"` +} + +// LinUserEdges holds the relations/edges for other nodes in the graph. +type LinUserEdges struct { + // LinUserIdentiy holds the value of the lin_user_identiy edge. + LinUserIdentiy []*LinUserIdentiy `json:"lin_user_identiy,omitempty"` + // LinGroup holds the value of the lin_group edge. + LinGroup []*LinGroup `json:"lin_group,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// LinUserIdentiyOrErr returns the LinUserIdentiy value or an error if the edge +// was not loaded in eager-loading. +func (e LinUserEdges) LinUserIdentiyOrErr() ([]*LinUserIdentiy, error) { + if e.loadedTypes[0] { + return e.LinUserIdentiy, nil + } + return nil, &NotLoadedError{edge: "lin_user_identiy"} +} + +// LinGroupOrErr returns the LinGroup value or an error if the edge +// was not loaded in eager-loading. +func (e LinUserEdges) LinGroupOrErr() ([]*LinGroup, error) { + if e.loadedTypes[1] { + return e.LinGroup, nil + } + return nil, &NotLoadedError{edge: "lin_group"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinUser) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linuser.FieldID: + values[i] = new(sql.NullInt64) + case linuser.FieldUsername, linuser.FieldNickname, linuser.FieldAvatar, linuser.FieldEmail: + values[i] = new(sql.NullString) + case linuser.FieldCreateTime, linuser.FieldUpdateTime, linuser.FieldDeleteTime: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type LinUser", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinUser fields. +func (lu *LinUser) assignValues(columns []string, values []interface{}) 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 linuser.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lu.ID = int(value.Int64) + case linuser.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + lu.CreateTime = value.Time + } + case linuser.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + lu.UpdateTime = value.Time + } + case linuser.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + lu.DeleteTime = value.Time + } + case linuser.FieldUsername: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value.Valid { + lu.Username = value.String + } + case linuser.FieldNickname: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field nickname", values[i]) + } else if value.Valid { + lu.Nickname = value.String + } + case linuser.FieldAvatar: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field avatar", values[i]) + } else if value.Valid { + lu.Avatar = value.String + } + case linuser.FieldEmail: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field email", values[i]) + } else if value.Valid { + lu.Email = value.String + } + } + } + return nil +} + +// QueryLinUserIdentiy queries the "lin_user_identiy" edge of the LinUser entity. +func (lu *LinUser) QueryLinUserIdentiy() *LinUserIdentiyQuery { + return (&LinUserClient{config: lu.config}).QueryLinUserIdentiy(lu) +} + +// QueryLinGroup queries the "lin_group" edge of the LinUser entity. +func (lu *LinUser) QueryLinGroup() *LinGroupQuery { + return (&LinUserClient{config: lu.config}).QueryLinGroup(lu) +} + +// Update returns a builder for updating this LinUser. +// Note that you need to call LinUser.Unwrap() before calling this method if this LinUser +// was returned from a transaction, and the transaction was committed or rolled back. +func (lu *LinUser) Update() *LinUserUpdateOne { + return (&LinUserClient{config: lu.config}).UpdateOne(lu) +} + +// Unwrap unwraps the LinUser 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 (lu *LinUser) Unwrap() *LinUser { + tx, ok := lu.config.driver.(*txDriver) + if !ok { + panic("model: LinUser is not a transactional entity") + } + lu.config.driver = tx.drv + return lu +} + +// String implements the fmt.Stringer. +func (lu *LinUser) String() string { + var builder strings.Builder + builder.WriteString("LinUser(") + builder.WriteString(fmt.Sprintf("id=%v", lu.ID)) + builder.WriteString(", create_time=") + builder.WriteString(lu.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(lu.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(lu.DeleteTime.Format(time.ANSIC)) + builder.WriteString(", username=") + builder.WriteString(lu.Username) + builder.WriteString(", nickname=") + builder.WriteString(lu.Nickname) + builder.WriteString(", avatar=") + builder.WriteString(lu.Avatar) + builder.WriteString(", email=") + builder.WriteString(lu.Email) + builder.WriteByte(')') + return builder.String() +} + +// LinUsers is a parsable slice of LinUser. +type LinUsers []*LinUser + +func (lu LinUsers) config(cfg config) { + for _i := range lu { + lu[_i].config = cfg + } +} diff --git a/internal/data/model/linuser/linuser.go b/internal/data/model/linuser/linuser.go new file mode 100644 index 0000000..8943e07 --- /dev/null +++ b/internal/data/model/linuser/linuser.go @@ -0,0 +1,87 @@ +// Code generated by entc, DO NOT EDIT. + +package linuser + +import ( + "time" +) + +const ( + // Label holds the string label denoting the linuser type in the database. + Label = "lin_user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldNickname holds the string denoting the nickname field in the database. + FieldNickname = "nickname" + // FieldAvatar holds the string denoting the avatar field in the database. + FieldAvatar = "avatar" + // FieldEmail holds the string denoting the email field in the database. + FieldEmail = "email" + // EdgeLinUserIdentiy holds the string denoting the lin_user_identiy edge name in mutations. + EdgeLinUserIdentiy = "lin_user_identiy" + // EdgeLinGroup holds the string denoting the lin_group edge name in mutations. + EdgeLinGroup = "lin_group" + // Table holds the table name of the linuser in the database. + Table = "lin_user" + // LinUserIdentiyTable is the table that holds the lin_user_identiy relation/edge. + LinUserIdentiyTable = "lin_user_identiy" + // LinUserIdentiyInverseTable is the table name for the LinUserIdentiy entity. + // It exists in this package in order to avoid circular dependency with the "linuseridentiy" package. + LinUserIdentiyInverseTable = "lin_user_identiy" + // LinUserIdentiyColumn is the table column denoting the lin_user_identiy relation/edge. + LinUserIdentiyColumn = "lin_user_lin_user_identiy" + // LinGroupTable is the table that holds the lin_group relation/edge. The primary key declared below. + LinGroupTable = "lin_user_group" + // LinGroupInverseTable is the table name for the LinGroup entity. + // It exists in this package in order to avoid circular dependency with the "lingroup" package. + LinGroupInverseTable = "lin_group" +) + +// Columns holds all SQL columns for linuser fields. +var Columns = []string{ + FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldUsername, + FieldNickname, + FieldAvatar, + FieldEmail, +} + +var ( + // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the + // primary key for the lin_group relation (M2M). + LinGroupPrimaryKey = []string{"user_id", "group_id"} +) + +// 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 ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // DefaultDeleteTime holds the default value on creation for the "delete_time" field. + DefaultDeleteTime func() time.Time + // DefaultAvatar holds the default value on creation for the "avatar" field. + DefaultAvatar string +) diff --git a/internal/data/model/linuser/where.go b/internal/data/model/linuser/where.go new file mode 100644 index 0000000..2b13f11 --- /dev/null +++ b/internal/data/model/linuser/where.go @@ -0,0 +1,903 @@ +// Code generated by entc, DO NOT EDIT. + +package linuser + +import ( + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ. +func Nickname(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNickname), v)) + }) +} + +// Avatar applies equality check predicate on the "avatar" field. It's identical to AvatarEQ. +func Avatar(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAvatar), v)) + }) +} + +// Email applies equality check predicate on the "email" field. It's identical to EmailEQ. +func Email(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEmail), v)) + }) +} + +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUsername), v)) + }) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUsername), v)) + }) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUsername), v...)) + }) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUsername), v...)) + }) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUsername), v)) + }) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUsername), v)) + }) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUsername), v)) + }) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUsername), v)) + }) +} + +// UsernameContains applies the Contains predicate on the "username" field. +func UsernameContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldUsername), v)) + }) +} + +// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. +func UsernameHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldUsername), v)) + }) +} + +// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. +func UsernameHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldUsername), v)) + }) +} + +// UsernameEqualFold applies the EqualFold predicate on the "username" field. +func UsernameEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldUsername), v)) + }) +} + +// UsernameContainsFold applies the ContainsFold predicate on the "username" field. +func UsernameContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldUsername), v)) + }) +} + +// NicknameEQ applies the EQ predicate on the "nickname" field. +func NicknameEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNickname), v)) + }) +} + +// NicknameNEQ applies the NEQ predicate on the "nickname" field. +func NicknameNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldNickname), v)) + }) +} + +// NicknameIn applies the In predicate on the "nickname" field. +func NicknameIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldNickname), v...)) + }) +} + +// NicknameNotIn applies the NotIn predicate on the "nickname" field. +func NicknameNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldNickname), v...)) + }) +} + +// NicknameGT applies the GT predicate on the "nickname" field. +func NicknameGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldNickname), v)) + }) +} + +// NicknameGTE applies the GTE predicate on the "nickname" field. +func NicknameGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldNickname), v)) + }) +} + +// NicknameLT applies the LT predicate on the "nickname" field. +func NicknameLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldNickname), v)) + }) +} + +// NicknameLTE applies the LTE predicate on the "nickname" field. +func NicknameLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldNickname), v)) + }) +} + +// NicknameContains applies the Contains predicate on the "nickname" field. +func NicknameContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldNickname), v)) + }) +} + +// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field. +func NicknameHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldNickname), v)) + }) +} + +// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field. +func NicknameHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldNickname), v)) + }) +} + +// NicknameEqualFold applies the EqualFold predicate on the "nickname" field. +func NicknameEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldNickname), v)) + }) +} + +// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field. +func NicknameContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldNickname), v)) + }) +} + +// AvatarEQ applies the EQ predicate on the "avatar" field. +func AvatarEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAvatar), v)) + }) +} + +// AvatarNEQ applies the NEQ predicate on the "avatar" field. +func AvatarNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAvatar), v)) + }) +} + +// AvatarIn applies the In predicate on the "avatar" field. +func AvatarIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAvatar), v...)) + }) +} + +// AvatarNotIn applies the NotIn predicate on the "avatar" field. +func AvatarNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAvatar), v...)) + }) +} + +// AvatarGT applies the GT predicate on the "avatar" field. +func AvatarGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAvatar), v)) + }) +} + +// AvatarGTE applies the GTE predicate on the "avatar" field. +func AvatarGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAvatar), v)) + }) +} + +// AvatarLT applies the LT predicate on the "avatar" field. +func AvatarLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAvatar), v)) + }) +} + +// AvatarLTE applies the LTE predicate on the "avatar" field. +func AvatarLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAvatar), v)) + }) +} + +// AvatarContains applies the Contains predicate on the "avatar" field. +func AvatarContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldAvatar), v)) + }) +} + +// AvatarHasPrefix applies the HasPrefix predicate on the "avatar" field. +func AvatarHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldAvatar), v)) + }) +} + +// AvatarHasSuffix applies the HasSuffix predicate on the "avatar" field. +func AvatarHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldAvatar), v)) + }) +} + +// AvatarEqualFold applies the EqualFold predicate on the "avatar" field. +func AvatarEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldAvatar), v)) + }) +} + +// AvatarContainsFold applies the ContainsFold predicate on the "avatar" field. +func AvatarContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldAvatar), v)) + }) +} + +// EmailEQ applies the EQ predicate on the "email" field. +func EmailEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEmail), v)) + }) +} + +// EmailNEQ applies the NEQ predicate on the "email" field. +func EmailNEQ(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldEmail), v)) + }) +} + +// EmailIn applies the In predicate on the "email" field. +func EmailIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldEmail), v...)) + }) +} + +// EmailNotIn applies the NotIn predicate on the "email" field. +func EmailNotIn(vs ...string) predicate.LinUser { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUser(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldEmail), v...)) + }) +} + +// EmailGT applies the GT predicate on the "email" field. +func EmailGT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldEmail), v)) + }) +} + +// EmailGTE applies the GTE predicate on the "email" field. +func EmailGTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldEmail), v)) + }) +} + +// EmailLT applies the LT predicate on the "email" field. +func EmailLT(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldEmail), v)) + }) +} + +// EmailLTE applies the LTE predicate on the "email" field. +func EmailLTE(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldEmail), v)) + }) +} + +// EmailContains applies the Contains predicate on the "email" field. +func EmailContains(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldEmail), v)) + }) +} + +// EmailHasPrefix applies the HasPrefix predicate on the "email" field. +func EmailHasPrefix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldEmail), v)) + }) +} + +// EmailHasSuffix applies the HasSuffix predicate on the "email" field. +func EmailHasSuffix(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldEmail), v)) + }) +} + +// EmailEqualFold applies the EqualFold predicate on the "email" field. +func EmailEqualFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldEmail), v)) + }) +} + +// EmailContainsFold applies the ContainsFold predicate on the "email" field. +func EmailContainsFold(v string) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldEmail), v)) + }) +} + +// HasLinUserIdentiy applies the HasEdge predicate on the "lin_user_identiy" edge. +func HasLinUserIdentiy() predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserIdentiyTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, LinUserIdentiyTable, LinUserIdentiyColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinUserIdentiyWith applies the HasEdge predicate on the "lin_user_identiy" edge with a given conditions (other predicates). +func HasLinUserIdentiyWith(preds ...predicate.LinUserIdentiy) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinUserIdentiyInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, LinUserIdentiyTable, LinUserIdentiyColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasLinGroup applies the HasEdge predicate on the "lin_group" edge. +func HasLinGroup() predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinGroupTable, LinGroupPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinGroupWith applies the HasEdge predicate on the "lin_group" edge with a given conditions (other predicates). +func HasLinGroupWith(preds ...predicate.LinGroup) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LinGroupTable, LinGroupPrimaryKey...), + ) + 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.LinUser) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinUser) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinUser) predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linuser_create.go b/internal/data/model/linuser_create.go new file mode 100644 index 0000000..60825f5 --- /dev/null +++ b/internal/data/model/linuser_create.go @@ -0,0 +1,447 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserCreate is the builder for creating a LinUser entity. +type LinUserCreate struct { + config + mutation *LinUserMutation + hooks []Hook +} + +// SetCreateTime sets the "create_time" field. +func (luc *LinUserCreate) SetCreateTime(t time.Time) *LinUserCreate { + luc.mutation.SetCreateTime(t) + return luc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableCreateTime(t *time.Time) *LinUserCreate { + if t != nil { + luc.SetCreateTime(*t) + } + return luc +} + +// SetUpdateTime sets the "update_time" field. +func (luc *LinUserCreate) SetUpdateTime(t time.Time) *LinUserCreate { + luc.mutation.SetUpdateTime(t) + return luc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableUpdateTime(t *time.Time) *LinUserCreate { + if t != nil { + luc.SetUpdateTime(*t) + } + return luc +} + +// SetDeleteTime sets the "delete_time" field. +func (luc *LinUserCreate) SetDeleteTime(t time.Time) *LinUserCreate { + luc.mutation.SetDeleteTime(t) + return luc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableDeleteTime(t *time.Time) *LinUserCreate { + if t != nil { + luc.SetDeleteTime(*t) + } + return luc +} + +// SetUsername sets the "username" field. +func (luc *LinUserCreate) SetUsername(s string) *LinUserCreate { + luc.mutation.SetUsername(s) + return luc +} + +// SetNickname sets the "nickname" field. +func (luc *LinUserCreate) SetNickname(s string) *LinUserCreate { + luc.mutation.SetNickname(s) + return luc +} + +// SetAvatar sets the "avatar" field. +func (luc *LinUserCreate) SetAvatar(s string) *LinUserCreate { + luc.mutation.SetAvatar(s) + return luc +} + +// SetNillableAvatar sets the "avatar" field if the given value is not nil. +func (luc *LinUserCreate) SetNillableAvatar(s *string) *LinUserCreate { + if s != nil { + luc.SetAvatar(*s) + } + return luc +} + +// SetEmail sets the "email" field. +func (luc *LinUserCreate) SetEmail(s string) *LinUserCreate { + luc.mutation.SetEmail(s) + return luc +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (luc *LinUserCreate) AddLinUserIdentiyIDs(ids ...int) *LinUserCreate { + luc.mutation.AddLinUserIdentiyIDs(ids...) + return luc +} + +// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luc *LinUserCreate) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luc.AddLinUserIdentiyIDs(ids...) +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (luc *LinUserCreate) AddLinGroupIDs(ids ...int) *LinUserCreate { + luc.mutation.AddLinGroupIDs(ids...) + return luc +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (luc *LinUserCreate) AddLinGroup(l ...*LinGroup) *LinUserCreate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luc.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinUserMutation object of the builder. +func (luc *LinUserCreate) Mutation() *LinUserMutation { + return luc.mutation +} + +// Save creates the LinUser in the database. +func (luc *LinUserCreate) Save(ctx context.Context) (*LinUser, error) { + var ( + err error + node *LinUser + ) + luc.defaults() + if len(luc.hooks) == 0 { + if err = luc.check(); err != nil { + return nil, err + } + node, err = luc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = luc.check(); err != nil { + return nil, err + } + luc.mutation = mutation + if node, err = luc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(luc.hooks) - 1; i >= 0; i-- { + if luc.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (luc *LinUserCreate) SaveX(ctx context.Context) *LinUser { + v, err := luc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (luc *LinUserCreate) Exec(ctx context.Context) error { + _, err := luc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luc *LinUserCreate) ExecX(ctx context.Context) { + if err := luc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (luc *LinUserCreate) defaults() { + if _, ok := luc.mutation.CreateTime(); !ok { + v := linuser.DefaultCreateTime() + luc.mutation.SetCreateTime(v) + } + if _, ok := luc.mutation.UpdateTime(); !ok { + v := linuser.DefaultUpdateTime() + luc.mutation.SetUpdateTime(v) + } + if _, ok := luc.mutation.DeleteTime(); !ok { + v := linuser.DefaultDeleteTime() + luc.mutation.SetDeleteTime(v) + } + if _, ok := luc.mutation.Avatar(); !ok { + v := linuser.DefaultAvatar + luc.mutation.SetAvatar(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (luc *LinUserCreate) check() error { + if _, ok := luc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := luc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } + if _, ok := luc.mutation.DeleteTime(); !ok { + return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} + } + if _, ok := luc.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} + } + if _, ok := luc.mutation.Nickname(); !ok { + return &ValidationError{Name: "nickname", err: errors.New(`model: missing required field "nickname"`)} + } + if _, ok := luc.mutation.Avatar(); !ok { + return &ValidationError{Name: "avatar", err: errors.New(`model: missing required field "avatar"`)} + } + if _, ok := luc.mutation.Email(); !ok { + return &ValidationError{Name: "email", err: errors.New(`model: missing required field "email"`)} + } + return nil +} + +func (luc *LinUserCreate) sqlSave(ctx context.Context) (*LinUser, error) { + _node, _spec := luc.createSpec() + if err := sqlgraph.CreateNode(ctx, luc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (luc *LinUserCreate) createSpec() (*LinUser, *sqlgraph.CreateSpec) { + var ( + _node = &LinUser{config: luc.config} + _spec = &sqlgraph.CreateSpec{ + Table: linuser.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + } + ) + if value, ok := luc.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := luc.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := luc.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldDeleteTime, + }) + _node.DeleteTime = value + } + if value, ok := luc.mutation.Username(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldUsername, + }) + _node.Username = value + } + if value, ok := luc.mutation.Nickname(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldNickname, + }) + _node.Nickname = value + } + if value, ok := luc.mutation.Avatar(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldAvatar, + }) + _node.Avatar = value + } + if value, ok := luc.mutation.Email(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldEmail, + }) + _node.Email = value + } + if nodes := luc.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := luc.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinUserCreateBulk is the builder for creating many LinUser entities in bulk. +type LinUserCreateBulk struct { + config + builders []*LinUserCreate +} + +// Save creates the LinUser entities in the database. +func (lucb *LinUserCreateBulk) Save(ctx context.Context) ([]*LinUser, error) { + specs := make([]*sqlgraph.CreateSpec, len(lucb.builders)) + nodes := make([]*LinUser, len(lucb.builders)) + mutators := make([]Mutator, len(lucb.builders)) + for i := range lucb.builders { + func(i int, root context.Context) { + builder := lucb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, lucb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, lucb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, lucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lucb *LinUserCreateBulk) SaveX(ctx context.Context) []*LinUser { + v, err := lucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lucb *LinUserCreateBulk) Exec(ctx context.Context) error { + _, err := lucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lucb *LinUserCreateBulk) ExecX(ctx context.Context) { + if err := lucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linuser_delete.go b/internal/data/model/linuser_delete.go new file mode 100644 index 0000000..13c22cd --- /dev/null +++ b/internal/data/model/linuser_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserDelete is the builder for deleting a LinUser entity. +type LinUserDelete struct { + config + hooks []Hook + mutation *LinUserMutation +} + +// Where appends a list predicates to the LinUserDelete builder. +func (lud *LinUserDelete) Where(ps ...predicate.LinUser) *LinUserDelete { + lud.mutation.Where(ps...) + return lud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (lud *LinUserDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(lud.hooks) == 0 { + affected, err = lud.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + lud.mutation = mutation + affected, err = lud.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(lud.hooks) - 1; i >= 0; i-- { + if lud.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = lud.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, lud.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lud *LinUserDelete) ExecX(ctx context.Context) int { + n, err := lud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (lud *LinUserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + if ps := lud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, lud.driver, _spec) +} + +// LinUserDeleteOne is the builder for deleting a single LinUser entity. +type LinUserDeleteOne struct { + lud *LinUserDelete +} + +// Exec executes the deletion query. +func (ludo *LinUserDeleteOne) Exec(ctx context.Context) error { + n, err := ludo.lud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linuser.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ludo *LinUserDeleteOne) ExecX(ctx context.Context) { + ludo.lud.ExecX(ctx) +} diff --git a/internal/data/model/linuser_query.go b/internal/data/model/linuser_query.go new file mode 100644 index 0000000..fb1ddf2 --- /dev/null +++ b/internal/data/model/linuser_query.go @@ -0,0 +1,1134 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserQuery is the builder for querying LinUser entities. +type LinUserQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinUser + // eager-loading edges. + withLinUserIdentiy *LinUserIdentiyQuery + withLinGroup *LinGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinUserQuery builder. +func (luq *LinUserQuery) Where(ps ...predicate.LinUser) *LinUserQuery { + luq.predicates = append(luq.predicates, ps...) + return luq +} + +// Limit adds a limit step to the query. +func (luq *LinUserQuery) Limit(limit int) *LinUserQuery { + luq.limit = &limit + return luq +} + +// Offset adds an offset step to the query. +func (luq *LinUserQuery) Offset(offset int) *LinUserQuery { + luq.offset = &offset + return luq +} + +// 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 (luq *LinUserQuery) Unique(unique bool) *LinUserQuery { + luq.unique = &unique + return luq +} + +// Order adds an order step to the query. +func (luq *LinUserQuery) Order(o ...OrderFunc) *LinUserQuery { + luq.order = append(luq.order, o...) + return luq +} + +// QueryLinUserIdentiy chains the current query on the "lin_user_identiy" edge. +func (luq *LinUserQuery) QueryLinUserIdentiy() *LinUserIdentiyQuery { + query := &LinUserIdentiyQuery{config: luq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := luq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, selector), + sqlgraph.To(linuseridentiy.Table, linuseridentiy.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, linuser.LinUserIdentiyTable, linuser.LinUserIdentiyColumn), + ) + fromU = sqlgraph.SetNeighbors(luq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryLinGroup chains the current query on the "lin_group" edge. +func (luq *LinUserQuery) QueryLinGroup() *LinGroupQuery { + query := &LinGroupQuery{config: luq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := luq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(linuser.Table, linuser.FieldID, selector), + sqlgraph.To(lingroup.Table, lingroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, linuser.LinGroupTable, linuser.LinGroupPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(luq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first LinUser entity from the query. +// Returns a *NotFoundError when no LinUser was found. +func (luq *LinUserQuery) First(ctx context.Context) (*LinUser, error) { + nodes, err := luq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuser.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (luq *LinUserQuery) FirstX(ctx context.Context) *LinUser { + node, err := luq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinUser ID from the query. +// Returns a *NotFoundError when no LinUser ID was found. +func (luq *LinUserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuser.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (luq *LinUserQuery) FirstIDX(ctx context.Context) int { + id, err := luq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinUser entity from the query. +// Returns a *NotFoundError when no LinUser was found. +func (luq *LinUserQuery) Last(ctx context.Context) (*LinUser, error) { + nodes, err := luq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuser.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (luq *LinUserQuery) LastX(ctx context.Context) *LinUser { + node, err := luq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinUser ID from the query. +// Returns a *NotFoundError when no LinUser ID was found. +func (luq *LinUserQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuser.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (luq *LinUserQuery) LastIDX(ctx context.Context) int { + id, err := luq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinUser entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinUser entity is not found. +// Returns a *NotFoundError when no LinUser entities are found. +func (luq *LinUserQuery) Only(ctx context.Context) (*LinUser, error) { + nodes, err := luq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linuser.Label} + default: + return nil, &NotSingularError{linuser.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (luq *LinUserQuery) OnlyX(ctx context.Context) *LinUser { + node, err := luq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinUser ID in the query. +// Returns a *NotSingularError when exactly one LinUser ID is not found. +// Returns a *NotFoundError when no entities are found. +func (luq *LinUserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linuser.Label} + default: + err = &NotSingularError{linuser.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (luq *LinUserQuery) OnlyIDX(ctx context.Context) int { + id, err := luq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinUsers. +func (luq *LinUserQuery) All(ctx context.Context) ([]*LinUser, error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + return luq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (luq *LinUserQuery) AllX(ctx context.Context) []*LinUser { + nodes, err := luq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinUser IDs. +func (luq *LinUserQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := luq.Select(linuser.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (luq *LinUserQuery) IDsX(ctx context.Context) []int { + ids, err := luq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (luq *LinUserQuery) Count(ctx context.Context) (int, error) { + if err := luq.prepareQuery(ctx); err != nil { + return 0, err + } + return luq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (luq *LinUserQuery) CountX(ctx context.Context) int { + count, err := luq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (luq *LinUserQuery) Exist(ctx context.Context) (bool, error) { + if err := luq.prepareQuery(ctx); err != nil { + return false, err + } + return luq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (luq *LinUserQuery) ExistX(ctx context.Context) bool { + exist, err := luq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinUserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (luq *LinUserQuery) Clone() *LinUserQuery { + if luq == nil { + return nil + } + return &LinUserQuery{ + config: luq.config, + limit: luq.limit, + offset: luq.offset, + order: append([]OrderFunc{}, luq.order...), + predicates: append([]predicate.LinUser{}, luq.predicates...), + withLinUserIdentiy: luq.withLinUserIdentiy.Clone(), + withLinGroup: luq.withLinGroup.Clone(), + // clone intermediate query. + sql: luq.sql.Clone(), + path: luq.path, + } +} + +// WithLinUserIdentiy tells the query-builder to eager-load the nodes that are connected to +// the "lin_user_identiy" edge. The optional arguments are used to configure the query builder of the edge. +func (luq *LinUserQuery) WithLinUserIdentiy(opts ...func(*LinUserIdentiyQuery)) *LinUserQuery { + query := &LinUserIdentiyQuery{config: luq.config} + for _, opt := range opts { + opt(query) + } + luq.withLinUserIdentiy = query + return luq +} + +// WithLinGroup tells the query-builder to eager-load the nodes that are connected to +// the "lin_group" edge. The optional arguments are used to configure the query builder of the edge. +func (luq *LinUserQuery) WithLinGroup(opts ...func(*LinGroupQuery)) *LinUserQuery { + query := &LinGroupQuery{config: luq.config} + for _, opt := range opts { + opt(query) + } + luq.withLinGroup = query + return luq +} + +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinUser.Query(). +// GroupBy(linuser.FieldCreateTime). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (luq *LinUserQuery) GroupBy(field string, fields ...string) *LinUserGroupBy { + group := &LinUserGroupBy{config: luq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := luq.prepareQuery(ctx); err != nil { + return nil, err + } + return luq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.LinUser.Query(). +// Select(linuser.FieldCreateTime). +// Scan(ctx, &v) +// +func (luq *LinUserQuery) Select(fields ...string) *LinUserSelect { + luq.fields = append(luq.fields, fields...) + return &LinUserSelect{LinUserQuery: luq} +} + +func (luq *LinUserQuery) prepareQuery(ctx context.Context) error { + for _, f := range luq.fields { + if !linuser.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if luq.path != nil { + prev, err := luq.path(ctx) + if err != nil { + return err + } + luq.sql = prev + } + return nil +} + +func (luq *LinUserQuery) sqlAll(ctx context.Context) ([]*LinUser, error) { + var ( + nodes = []*LinUser{} + _spec = luq.querySpec() + loadedTypes = [2]bool{ + luq.withLinUserIdentiy != nil, + luq.withLinGroup != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinUser{config: luq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, luq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := luq.withLinUserIdentiy; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*LinUser) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.LinUserIdentiy = []*LinUserIdentiy{} + } + query.withFKs = true + query.Where(predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.InValues(linuser.LinUserIdentiyColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.lin_user_lin_user_identiy + if fk == nil { + return nil, fmt.Errorf(`foreign-key "lin_user_lin_user_identiy" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "lin_user_lin_user_identiy" returned %v for node %v`, *fk, n.ID) + } + node.Edges.LinUserIdentiy = append(node.Edges.LinUserIdentiy, n) + } + } + + if query := luq.withLinGroup; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + ids := make(map[int]*LinUser, len(nodes)) + for _, node := range nodes { + ids[node.ID] = node + fks = append(fks, node.ID) + node.Edges.LinGroup = []*LinGroup{} + } + var ( + edgeids []int + edges = make(map[int][]*LinUser) + ) + _spec := &sqlgraph.EdgeQuerySpec{ + Edge: &sqlgraph.EdgeSpec{ + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + }, + Predicate: func(s *sql.Selector) { + s.Where(sql.InValues(linuser.LinGroupPrimaryKey[1], fks...)) + }, + ScanValues: func() [2]interface{} { + return [2]interface{}{new(sql.NullInt64), new(sql.NullInt64)} + }, + Assign: func(out, in interface{}) error { + eout, ok := out.(*sql.NullInt64) + if !ok || eout == nil { + return fmt.Errorf("unexpected id value for edge-out") + } + ein, ok := in.(*sql.NullInt64) + if !ok || ein == nil { + return fmt.Errorf("unexpected id value for edge-in") + } + outValue := int(eout.Int64) + inValue := int(ein.Int64) + node, ok := ids[outValue] + if !ok { + return fmt.Errorf("unexpected node id in edges: %v", outValue) + } + if _, ok := edges[inValue]; !ok { + edgeids = append(edgeids, inValue) + } + edges[inValue] = append(edges[inValue], node) + return nil + }, + } + if err := sqlgraph.QueryEdges(ctx, luq.driver, _spec); err != nil { + return nil, fmt.Errorf(`query edges "lin_group": %w`, err) + } + query.Where(lingroup.IDIn(edgeids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := edges[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "lin_group" node returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.LinGroup = append(nodes[i].Edges.LinGroup, n) + } + } + } + + return nodes, nil +} + +func (luq *LinUserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := luq.querySpec() + return sqlgraph.CountNodes(ctx, luq.driver, _spec) +} + +func (luq *LinUserQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := luq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (luq *LinUserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + Columns: linuser.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + From: luq.sql, + Unique: true, + } + if unique := luq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := luq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuser.FieldID) + for i := range fields { + if fields[i] != linuser.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := luq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := luq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := luq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := luq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (luq *LinUserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(luq.driver.Dialect()) + t1 := builder.Table(linuser.Table) + columns := luq.fields + if len(columns) == 0 { + columns = linuser.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if luq.sql != nil { + selector = luq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range luq.predicates { + p(selector) + } + for _, p := range luq.order { + p(selector) + } + if offset := luq.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 := luq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinUserGroupBy is the group-by builder for LinUser entities. +type LinUserGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lugb *LinUserGroupBy) Aggregate(fns ...AggregateFunc) *LinUserGroupBy { + lugb.fns = append(lugb.fns, fns...) + return lugb +} + +// Scan applies the group-by query and scans the result into the given value. +func (lugb *LinUserGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := lugb.path(ctx) + if err != nil { + return err + } + lugb.sql = query + return lugb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lugb *LinUserGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := lugb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lugb *LinUserGroupBy) StringsX(ctx context.Context) []string { + v, err := lugb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lugb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lugb *LinUserGroupBy) StringX(ctx context.Context) string { + v, err := lugb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lugb *LinUserGroupBy) IntsX(ctx context.Context) []int { + v, err := lugb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lugb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lugb *LinUserGroupBy) IntX(ctx context.Context) int { + v, err := lugb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lugb *LinUserGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := lugb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lugb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lugb *LinUserGroupBy) Float64X(ctx context.Context) float64 { + v, err := lugb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(lugb.fields) > 1 { + return nil, errors.New("model: LinUserGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := lugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lugb *LinUserGroupBy) BoolsX(ctx context.Context) []bool { + v, err := lugb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (lugb *LinUserGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lugb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lugb *LinUserGroupBy) BoolX(ctx context.Context) bool { + v, err := lugb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lugb *LinUserGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range lugb.fields { + if !linuser.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := lugb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lugb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (lugb *LinUserGroupBy) sqlQuery() *sql.Selector { + selector := lugb.sql.Select() + aggregation := make([]string, 0, len(lugb.fns)) + for _, fn := range lugb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(lugb.fields)+len(lugb.fns)) + for _, f := range lugb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(lugb.fields...)...) +} + +// LinUserSelect is the builder for selecting fields of LinUser entities. +type LinUserSelect struct { + *LinUserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (lus *LinUserSelect) Scan(ctx context.Context, v interface{}) error { + if err := lus.prepareQuery(ctx); err != nil { + return err + } + lus.sql = lus.LinUserQuery.sqlQuery(ctx) + return lus.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (lus *LinUserSelect) ScanX(ctx context.Context, v interface{}) { + if err := lus.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Strings(ctx context.Context) ([]string, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (lus *LinUserSelect) StringsX(ctx context.Context) []string { + v, err := lus.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = lus.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (lus *LinUserSelect) StringX(ctx context.Context) string { + v, err := lus.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Ints(ctx context.Context) ([]int, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (lus *LinUserSelect) IntsX(ctx context.Context) []int { + v, err := lus.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = lus.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (lus *LinUserSelect) IntX(ctx context.Context) int { + v, err := lus.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (lus *LinUserSelect) Float64sX(ctx context.Context) []float64 { + v, err := lus.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = lus.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (lus *LinUserSelect) Float64X(ctx context.Context) float64 { + v, err := lus.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Bools(ctx context.Context) ([]bool, error) { + if len(lus.fields) > 1 { + return nil, errors.New("model: LinUserSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := lus.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (lus *LinUserSelect) BoolsX(ctx context.Context) []bool { + v, err := lus.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (lus *LinUserSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = lus.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuser.Label} + default: + err = fmt.Errorf("model: LinUserSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (lus *LinUserSelect) BoolX(ctx context.Context) bool { + v, err := lus.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (lus *LinUserSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := lus.sql.Query() + if err := lus.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linuser_update.go b/internal/data/model/linuser_update.go new file mode 100644 index 0000000..be3c6fb --- /dev/null +++ b/internal/data/model/linuser_update.go @@ -0,0 +1,807 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserUpdate is the builder for updating LinUser entities. +type LinUserUpdate struct { + config + hooks []Hook + mutation *LinUserMutation +} + +// Where appends a list predicates to the LinUserUpdate builder. +func (luu *LinUserUpdate) Where(ps ...predicate.LinUser) *LinUserUpdate { + luu.mutation.Where(ps...) + return luu +} + +// SetUpdateTime sets the "update_time" field. +func (luu *LinUserUpdate) SetUpdateTime(t time.Time) *LinUserUpdate { + luu.mutation.SetUpdateTime(t) + return luu +} + +// SetDeleteTime sets the "delete_time" field. +func (luu *LinUserUpdate) SetDeleteTime(t time.Time) *LinUserUpdate { + luu.mutation.SetDeleteTime(t) + return luu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luu *LinUserUpdate) SetNillableDeleteTime(t *time.Time) *LinUserUpdate { + if t != nil { + luu.SetDeleteTime(*t) + } + return luu +} + +// SetUsername sets the "username" field. +func (luu *LinUserUpdate) SetUsername(s string) *LinUserUpdate { + luu.mutation.SetUsername(s) + return luu +} + +// SetNickname sets the "nickname" field. +func (luu *LinUserUpdate) SetNickname(s string) *LinUserUpdate { + luu.mutation.SetNickname(s) + return luu +} + +// SetAvatar sets the "avatar" field. +func (luu *LinUserUpdate) SetAvatar(s string) *LinUserUpdate { + luu.mutation.SetAvatar(s) + return luu +} + +// SetNillableAvatar sets the "avatar" field if the given value is not nil. +func (luu *LinUserUpdate) SetNillableAvatar(s *string) *LinUserUpdate { + if s != nil { + luu.SetAvatar(*s) + } + return luu +} + +// SetEmail sets the "email" field. +func (luu *LinUserUpdate) SetEmail(s string) *LinUserUpdate { + luu.mutation.SetEmail(s) + return luu +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (luu *LinUserUpdate) AddLinUserIdentiyIDs(ids ...int) *LinUserUpdate { + luu.mutation.AddLinUserIdentiyIDs(ids...) + return luu +} + +// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luu *LinUserUpdate) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.AddLinUserIdentiyIDs(ids...) +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (luu *LinUserUpdate) AddLinGroupIDs(ids ...int) *LinUserUpdate { + luu.mutation.AddLinGroupIDs(ids...) + return luu +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (luu *LinUserUpdate) AddLinGroup(l ...*LinGroup) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinUserMutation object of the builder. +func (luu *LinUserUpdate) Mutation() *LinUserMutation { + return luu.mutation +} + +// ClearLinUserIdentiy clears all "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luu *LinUserUpdate) ClearLinUserIdentiy() *LinUserUpdate { + luu.mutation.ClearLinUserIdentiy() + return luu +} + +// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to LinUserIdentiy entities by IDs. +func (luu *LinUserUpdate) RemoveLinUserIdentiyIDs(ids ...int) *LinUserUpdate { + luu.mutation.RemoveLinUserIdentiyIDs(ids...) + return luu +} + +// RemoveLinUserIdentiy removes "lin_user_identiy" edges to LinUserIdentiy entities. +func (luu *LinUserUpdate) RemoveLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.RemoveLinUserIdentiyIDs(ids...) +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (luu *LinUserUpdate) ClearLinGroup() *LinUserUpdate { + luu.mutation.ClearLinGroup() + return luu +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (luu *LinUserUpdate) RemoveLinGroupIDs(ids ...int) *LinUserUpdate { + luu.mutation.RemoveLinGroupIDs(ids...) + return luu +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (luu *LinUserUpdate) RemoveLinGroup(l ...*LinGroup) *LinUserUpdate { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luu.RemoveLinGroupIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (luu *LinUserUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + luu.defaults() + if len(luu.hooks) == 0 { + affected, err = luu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luu.mutation = mutation + affected, err = luu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(luu.hooks) - 1; i >= 0; i-- { + if luu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luu *LinUserUpdate) SaveX(ctx context.Context) int { + affected, err := luu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (luu *LinUserUpdate) Exec(ctx context.Context) error { + _, err := luu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luu *LinUserUpdate) ExecX(ctx context.Context) { + if err := luu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (luu *LinUserUpdate) defaults() { + if _, ok := luu.mutation.UpdateTime(); !ok { + v := linuser.UpdateDefaultUpdateTime() + luu.mutation.SetUpdateTime(v) + } +} + +func (luu *LinUserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + Columns: linuser.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + if ps := luu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldUpdateTime, + }) + } + if value, ok := luu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldDeleteTime, + }) + } + if value, ok := luu.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldUsername, + }) + } + if value, ok := luu.mutation.Nickname(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldNickname, + }) + } + if value, ok := luu.mutation.Avatar(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldAvatar, + }) + } + if value, ok := luu.mutation.Email(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldEmail, + }) + } + if luu.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.RemovedLinUserIdentiyIDs(); len(nodes) > 0 && !luu.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if luu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !luu.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luu.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, luu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuser.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinUserUpdateOne is the builder for updating a single LinUser entity. +type LinUserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinUserMutation +} + +// SetUpdateTime sets the "update_time" field. +func (luuo *LinUserUpdateOne) SetUpdateTime(t time.Time) *LinUserUpdateOne { + luuo.mutation.SetUpdateTime(t) + return luuo +} + +// SetDeleteTime sets the "delete_time" field. +func (luuo *LinUserUpdateOne) SetDeleteTime(t time.Time) *LinUserUpdateOne { + luuo.mutation.SetDeleteTime(t) + return luuo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luuo *LinUserUpdateOne) SetNillableDeleteTime(t *time.Time) *LinUserUpdateOne { + if t != nil { + luuo.SetDeleteTime(*t) + } + return luuo +} + +// SetUsername sets the "username" field. +func (luuo *LinUserUpdateOne) SetUsername(s string) *LinUserUpdateOne { + luuo.mutation.SetUsername(s) + return luuo +} + +// SetNickname sets the "nickname" field. +func (luuo *LinUserUpdateOne) SetNickname(s string) *LinUserUpdateOne { + luuo.mutation.SetNickname(s) + return luuo +} + +// SetAvatar sets the "avatar" field. +func (luuo *LinUserUpdateOne) SetAvatar(s string) *LinUserUpdateOne { + luuo.mutation.SetAvatar(s) + return luuo +} + +// SetNillableAvatar sets the "avatar" field if the given value is not nil. +func (luuo *LinUserUpdateOne) SetNillableAvatar(s *string) *LinUserUpdateOne { + if s != nil { + luuo.SetAvatar(*s) + } + return luuo +} + +// SetEmail sets the "email" field. +func (luuo *LinUserUpdateOne) SetEmail(s string) *LinUserUpdateOne { + luuo.mutation.SetEmail(s) + return luuo +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (luuo *LinUserUpdateOne) AddLinUserIdentiyIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.AddLinUserIdentiyIDs(ids...) + return luuo +} + +// AddLinUserIdentiy adds the "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luuo *LinUserUpdateOne) AddLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.AddLinUserIdentiyIDs(ids...) +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by IDs. +func (luuo *LinUserUpdateOne) AddLinGroupIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.AddLinGroupIDs(ids...) + return luuo +} + +// AddLinGroup adds the "lin_group" edges to the LinGroup entity. +func (luuo *LinUserUpdateOne) AddLinGroup(l ...*LinGroup) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.AddLinGroupIDs(ids...) +} + +// Mutation returns the LinUserMutation object of the builder. +func (luuo *LinUserUpdateOne) Mutation() *LinUserMutation { + return luuo.mutation +} + +// ClearLinUserIdentiy clears all "lin_user_identiy" edges to the LinUserIdentiy entity. +func (luuo *LinUserUpdateOne) ClearLinUserIdentiy() *LinUserUpdateOne { + luuo.mutation.ClearLinUserIdentiy() + return luuo +} + +// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to LinUserIdentiy entities by IDs. +func (luuo *LinUserUpdateOne) RemoveLinUserIdentiyIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.RemoveLinUserIdentiyIDs(ids...) + return luuo +} + +// RemoveLinUserIdentiy removes "lin_user_identiy" edges to LinUserIdentiy entities. +func (luuo *LinUserUpdateOne) RemoveLinUserIdentiy(l ...*LinUserIdentiy) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.RemoveLinUserIdentiyIDs(ids...) +} + +// ClearLinGroup clears all "lin_group" edges to the LinGroup entity. +func (luuo *LinUserUpdateOne) ClearLinGroup() *LinUserUpdateOne { + luuo.mutation.ClearLinGroup() + return luuo +} + +// RemoveLinGroupIDs removes the "lin_group" edge to LinGroup entities by IDs. +func (luuo *LinUserUpdateOne) RemoveLinGroupIDs(ids ...int) *LinUserUpdateOne { + luuo.mutation.RemoveLinGroupIDs(ids...) + return luuo +} + +// RemoveLinGroup removes "lin_group" edges to LinGroup entities. +func (luuo *LinUserUpdateOne) RemoveLinGroup(l ...*LinGroup) *LinUserUpdateOne { + ids := make([]int, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return luuo.RemoveLinGroupIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (luuo *LinUserUpdateOne) Select(field string, fields ...string) *LinUserUpdateOne { + luuo.fields = append([]string{field}, fields...) + return luuo +} + +// Save executes the query and returns the updated LinUser entity. +func (luuo *LinUserUpdateOne) Save(ctx context.Context) (*LinUser, error) { + var ( + err error + node *LinUser + ) + luuo.defaults() + if len(luuo.hooks) == 0 { + node, err = luuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luuo.mutation = mutation + node, err = luuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(luuo.hooks) - 1; i >= 0; i-- { + if luuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luuo *LinUserUpdateOne) SaveX(ctx context.Context) *LinUser { + node, err := luuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (luuo *LinUserUpdateOne) Exec(ctx context.Context) error { + _, err := luuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luuo *LinUserUpdateOne) ExecX(ctx context.Context) { + if err := luuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (luuo *LinUserUpdateOne) defaults() { + if _, ok := luuo.mutation.UpdateTime(); !ok { + v := linuser.UpdateDefaultUpdateTime() + luuo.mutation.SetUpdateTime(v) + } +} + +func (luuo *LinUserUpdateOne) sqlSave(ctx context.Context) (_node *LinUser, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuser.Table, + Columns: linuser.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuser.FieldID, + }, + }, + } + id, ok := luuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinUser.ID for update")} + } + _spec.Node.ID.Value = id + if fields := luuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuser.FieldID) + for _, f := range fields { + if !linuser.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linuser.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := luuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luuo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldUpdateTime, + }) + } + if value, ok := luuo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuser.FieldDeleteTime, + }) + } + if value, ok := luuo.mutation.Username(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldUsername, + }) + } + if value, ok := luuo.mutation.Nickname(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldNickname, + }) + } + if value, ok := luuo.mutation.Avatar(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldAvatar, + }) + } + if value, ok := luuo.mutation.Email(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuser.FieldEmail, + }) + } + if luuo.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.RemovedLinUserIdentiyIDs(); len(nodes) > 0 && !luuo.mutation.LinUserIdentiyCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.LinUserIdentiyIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: linuser.LinUserIdentiyTable, + Columns: []string{linuser.LinUserIdentiyColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if luuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.RemovedLinGroupIDs(); len(nodes) > 0 && !luuo.mutation.LinGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luuo.mutation.LinGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: linuser.LinGroupTable, + Columns: linuser.LinGroupPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: lingroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &LinUser{config: luuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, luuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuser.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/linuseridentiy.go b/internal/data/model/linuseridentiy.go new file mode 100644 index 0000000..5834615 --- /dev/null +++ b/internal/data/model/linuseridentiy.go @@ -0,0 +1,140 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "strings" + + "entgo.io/ent/dialect/sql" +) + +// LinUserIdentiy is the model entity for the LinUserIdentiy schema. +type LinUserIdentiy struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + // 用户id + UserID int `json:"user_id,omitempty"` + // IdentityType holds the value of the "identity_type" field. + IdentityType string `json:"identity_type,omitempty"` + // Identifier holds the value of the "identifier" field. + Identifier string `json:"identifier,omitempty"` + // Credential holds the value of the "credential" field. + Credential string `json:"credential,omitempty"` + lin_user_lin_user_identiy *int +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LinUserIdentiy) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case linuseridentiy.FieldID, linuseridentiy.FieldUserID: + values[i] = new(sql.NullInt64) + case linuseridentiy.FieldIdentityType, linuseridentiy.FieldIdentifier, linuseridentiy.FieldCredential: + values[i] = new(sql.NullString) + case linuseridentiy.ForeignKeys[0]: // lin_user_lin_user_identiy + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type LinUserIdentiy", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LinUserIdentiy fields. +func (lui *LinUserIdentiy) assignValues(columns []string, values []interface{}) 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 linuseridentiy.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + lui.ID = int(value.Int64) + case linuseridentiy.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + lui.UserID = int(value.Int64) + } + case linuseridentiy.FieldIdentityType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field identity_type", values[i]) + } else if value.Valid { + lui.IdentityType = value.String + } + case linuseridentiy.FieldIdentifier: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field identifier", values[i]) + } else if value.Valid { + lui.Identifier = value.String + } + case linuseridentiy.FieldCredential: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field credential", values[i]) + } else if value.Valid { + lui.Credential = value.String + } + case linuseridentiy.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field lin_user_lin_user_identiy", value) + } else if value.Valid { + lui.lin_user_lin_user_identiy = new(int) + *lui.lin_user_lin_user_identiy = int(value.Int64) + } + } + } + return nil +} + +// Update returns a builder for updating this LinUserIdentiy. +// Note that you need to call LinUserIdentiy.Unwrap() before calling this method if this LinUserIdentiy +// was returned from a transaction, and the transaction was committed or rolled back. +func (lui *LinUserIdentiy) Update() *LinUserIdentiyUpdateOne { + return (&LinUserIdentiyClient{config: lui.config}).UpdateOne(lui) +} + +// Unwrap unwraps the LinUserIdentiy 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 (lui *LinUserIdentiy) Unwrap() *LinUserIdentiy { + tx, ok := lui.config.driver.(*txDriver) + if !ok { + panic("model: LinUserIdentiy is not a transactional entity") + } + lui.config.driver = tx.drv + return lui +} + +// String implements the fmt.Stringer. +func (lui *LinUserIdentiy) String() string { + var builder strings.Builder + builder.WriteString("LinUserIdentiy(") + builder.WriteString(fmt.Sprintf("id=%v", lui.ID)) + builder.WriteString(", user_id=") + builder.WriteString(fmt.Sprintf("%v", lui.UserID)) + builder.WriteString(", identity_type=") + builder.WriteString(lui.IdentityType) + builder.WriteString(", identifier=") + builder.WriteString(lui.Identifier) + builder.WriteString(", credential=") + builder.WriteString(lui.Credential) + builder.WriteByte(')') + return builder.String() +} + +// LinUserIdentiys is a parsable slice of LinUserIdentiy. +type LinUserIdentiys []*LinUserIdentiy + +func (lui LinUserIdentiys) config(cfg config) { + for _i := range lui { + lui[_i].config = cfg + } +} diff --git a/internal/data/model/linuseridentiy/linuseridentiy.go b/internal/data/model/linuseridentiy/linuseridentiy.go new file mode 100644 index 0000000..7339818 --- /dev/null +++ b/internal/data/model/linuseridentiy/linuseridentiy.go @@ -0,0 +1,50 @@ +// Code generated by entc, DO NOT EDIT. + +package linuseridentiy + +const ( + // Label holds the string label denoting the linuseridentiy type in the database. + Label = "lin_user_identiy" + // 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" + // FieldIdentityType holds the string denoting the identity_type field in the database. + FieldIdentityType = "identity_type" + // FieldIdentifier holds the string denoting the identifier field in the database. + FieldIdentifier = "identifier" + // FieldCredential holds the string denoting the credential field in the database. + FieldCredential = "credential" + // Table holds the table name of the linuseridentiy in the database. + Table = "lin_user_identiy" +) + +// Columns holds all SQL columns for linuseridentiy fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldIdentityType, + FieldIdentifier, + FieldCredential, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "lin_user_identiy" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "lin_user_lin_user_identiy", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} diff --git a/internal/data/model/linuseridentiy/where.go b/internal/data/model/linuseridentiy/where.go new file mode 100644 index 0000000..69704f1 --- /dev/null +++ b/internal/data/model/linuseridentiy/where.go @@ -0,0 +1,561 @@ +// Code generated by entc, DO NOT EDIT. + +package linuseridentiy + +import ( + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// IdentityType applies equality check predicate on the "identity_type" field. It's identical to IdentityTypeEQ. +func IdentityType(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentityType), v)) + }) +} + +// Identifier applies equality check predicate on the "identifier" field. It's identical to IdentifierEQ. +func Identifier(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentifier), v)) + }) +} + +// Credential applies equality check predicate on the "credential" field. It's identical to CredentialEQ. +func Credential(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCredential), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUserID), v...)) + }) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUserID), v)) + }) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUserID), v)) + }) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUserID), v)) + }) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUserID), v)) + }) +} + +// IdentityTypeEQ applies the EQ predicate on the "identity_type" field. +func IdentityTypeEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeNEQ applies the NEQ predicate on the "identity_type" field. +func IdentityTypeNEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeIn applies the In predicate on the "identity_type" field. +func IdentityTypeIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldIdentityType), v...)) + }) +} + +// IdentityTypeNotIn applies the NotIn predicate on the "identity_type" field. +func IdentityTypeNotIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldIdentityType), v...)) + }) +} + +// IdentityTypeGT applies the GT predicate on the "identity_type" field. +func IdentityTypeGT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeGTE applies the GTE predicate on the "identity_type" field. +func IdentityTypeGTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeLT applies the LT predicate on the "identity_type" field. +func IdentityTypeLT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeLTE applies the LTE predicate on the "identity_type" field. +func IdentityTypeLTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeContains applies the Contains predicate on the "identity_type" field. +func IdentityTypeContains(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeHasPrefix applies the HasPrefix predicate on the "identity_type" field. +func IdentityTypeHasPrefix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeHasSuffix applies the HasSuffix predicate on the "identity_type" field. +func IdentityTypeHasSuffix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeEqualFold applies the EqualFold predicate on the "identity_type" field. +func IdentityTypeEqualFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldIdentityType), v)) + }) +} + +// IdentityTypeContainsFold applies the ContainsFold predicate on the "identity_type" field. +func IdentityTypeContainsFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldIdentityType), v)) + }) +} + +// IdentifierEQ applies the EQ predicate on the "identifier" field. +func IdentifierEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierNEQ applies the NEQ predicate on the "identifier" field. +func IdentifierNEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierIn applies the In predicate on the "identifier" field. +func IdentifierIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldIdentifier), v...)) + }) +} + +// IdentifierNotIn applies the NotIn predicate on the "identifier" field. +func IdentifierNotIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldIdentifier), v...)) + }) +} + +// IdentifierGT applies the GT predicate on the "identifier" field. +func IdentifierGT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierGTE applies the GTE predicate on the "identifier" field. +func IdentifierGTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierLT applies the LT predicate on the "identifier" field. +func IdentifierLT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierLTE applies the LTE predicate on the "identifier" field. +func IdentifierLTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierContains applies the Contains predicate on the "identifier" field. +func IdentifierContains(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierHasPrefix applies the HasPrefix predicate on the "identifier" field. +func IdentifierHasPrefix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierHasSuffix applies the HasSuffix predicate on the "identifier" field. +func IdentifierHasSuffix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierEqualFold applies the EqualFold predicate on the "identifier" field. +func IdentifierEqualFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldIdentifier), v)) + }) +} + +// IdentifierContainsFold applies the ContainsFold predicate on the "identifier" field. +func IdentifierContainsFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldIdentifier), v)) + }) +} + +// CredentialEQ applies the EQ predicate on the "credential" field. +func CredentialEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCredential), v)) + }) +} + +// CredentialNEQ applies the NEQ predicate on the "credential" field. +func CredentialNEQ(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCredential), v)) + }) +} + +// CredentialIn applies the In predicate on the "credential" field. +func CredentialIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCredential), v...)) + }) +} + +// CredentialNotIn applies the NotIn predicate on the "credential" field. +func CredentialNotIn(vs ...string) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCredential), v...)) + }) +} + +// CredentialGT applies the GT predicate on the "credential" field. +func CredentialGT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCredential), v)) + }) +} + +// CredentialGTE applies the GTE predicate on the "credential" field. +func CredentialGTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCredential), v)) + }) +} + +// CredentialLT applies the LT predicate on the "credential" field. +func CredentialLT(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCredential), v)) + }) +} + +// CredentialLTE applies the LTE predicate on the "credential" field. +func CredentialLTE(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCredential), v)) + }) +} + +// CredentialContains applies the Contains predicate on the "credential" field. +func CredentialContains(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldCredential), v)) + }) +} + +// CredentialHasPrefix applies the HasPrefix predicate on the "credential" field. +func CredentialHasPrefix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldCredential), v)) + }) +} + +// CredentialHasSuffix applies the HasSuffix predicate on the "credential" field. +func CredentialHasSuffix(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldCredential), v)) + }) +} + +// CredentialEqualFold applies the EqualFold predicate on the "credential" field. +func CredentialEqualFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldCredential), v)) + }) +} + +// CredentialContainsFold applies the ContainsFold predicate on the "credential" field. +func CredentialContainsFold(v string) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldCredential), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LinUserIdentiy) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LinUserIdentiy) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LinUserIdentiy) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/data/model/linuseridentiy_create.go b/internal/data/model/linuseridentiy_create.go new file mode 100644 index 0000000..5c5c685 --- /dev/null +++ b/internal/data/model/linuseridentiy_create.go @@ -0,0 +1,271 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyCreate is the builder for creating a LinUserIdentiy entity. +type LinUserIdentiyCreate struct { + config + mutation *LinUserIdentiyMutation + hooks []Hook +} + +// SetUserID sets the "user_id" field. +func (luic *LinUserIdentiyCreate) SetUserID(i int) *LinUserIdentiyCreate { + luic.mutation.SetUserID(i) + return luic +} + +// SetIdentityType sets the "identity_type" field. +func (luic *LinUserIdentiyCreate) SetIdentityType(s string) *LinUserIdentiyCreate { + luic.mutation.SetIdentityType(s) + return luic +} + +// SetIdentifier sets the "identifier" field. +func (luic *LinUserIdentiyCreate) SetIdentifier(s string) *LinUserIdentiyCreate { + luic.mutation.SetIdentifier(s) + return luic +} + +// SetCredential sets the "credential" field. +func (luic *LinUserIdentiyCreate) SetCredential(s string) *LinUserIdentiyCreate { + luic.mutation.SetCredential(s) + return luic +} + +// Mutation returns the LinUserIdentiyMutation object of the builder. +func (luic *LinUserIdentiyCreate) Mutation() *LinUserIdentiyMutation { + return luic.mutation +} + +// Save creates the LinUserIdentiy in the database. +func (luic *LinUserIdentiyCreate) Save(ctx context.Context) (*LinUserIdentiy, error) { + var ( + err error + node *LinUserIdentiy + ) + if len(luic.hooks) == 0 { + if err = luic.check(); err != nil { + return nil, err + } + node, err = luic.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = luic.check(); err != nil { + return nil, err + } + luic.mutation = mutation + if node, err = luic.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(luic.hooks) - 1; i >= 0; i-- { + if luic.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luic.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luic.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (luic *LinUserIdentiyCreate) SaveX(ctx context.Context) *LinUserIdentiy { + v, err := luic.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (luic *LinUserIdentiyCreate) Exec(ctx context.Context) error { + _, err := luic.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luic *LinUserIdentiyCreate) ExecX(ctx context.Context) { + if err := luic.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (luic *LinUserIdentiyCreate) check() error { + if _, ok := luic.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} + } + if _, ok := luic.mutation.IdentityType(); !ok { + return &ValidationError{Name: "identity_type", err: errors.New(`model: missing required field "identity_type"`)} + } + if _, ok := luic.mutation.Identifier(); !ok { + return &ValidationError{Name: "identifier", err: errors.New(`model: missing required field "identifier"`)} + } + if _, ok := luic.mutation.Credential(); !ok { + return &ValidationError{Name: "credential", err: errors.New(`model: missing required field "credential"`)} + } + return nil +} + +func (luic *LinUserIdentiyCreate) sqlSave(ctx context.Context) (*LinUserIdentiy, error) { + _node, _spec := luic.createSpec() + if err := sqlgraph.CreateNode(ctx, luic.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (luic *LinUserIdentiyCreate) createSpec() (*LinUserIdentiy, *sqlgraph.CreateSpec) { + var ( + _node = &LinUserIdentiy{config: luic.config} + _spec = &sqlgraph.CreateSpec{ + Table: linuseridentiy.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + } + ) + if value, ok := luic.mutation.UserID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + _node.UserID = value + } + if value, ok := luic.mutation.IdentityType(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentityType, + }) + _node.IdentityType = value + } + if value, ok := luic.mutation.Identifier(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentifier, + }) + _node.Identifier = value + } + if value, ok := luic.mutation.Credential(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldCredential, + }) + _node.Credential = value + } + return _node, _spec +} + +// LinUserIdentiyCreateBulk is the builder for creating many LinUserIdentiy entities in bulk. +type LinUserIdentiyCreateBulk struct { + config + builders []*LinUserIdentiyCreate +} + +// Save creates the LinUserIdentiy entities in the database. +func (luicb *LinUserIdentiyCreateBulk) Save(ctx context.Context) ([]*LinUserIdentiy, error) { + specs := make([]*sqlgraph.CreateSpec, len(luicb.builders)) + nodes := make([]*LinUserIdentiy, len(luicb.builders)) + mutators := make([]Mutator, len(luicb.builders)) + for i := range luicb.builders { + func(i int, root context.Context) { + builder := luicb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, luicb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, luicb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, luicb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (luicb *LinUserIdentiyCreateBulk) SaveX(ctx context.Context) []*LinUserIdentiy { + v, err := luicb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (luicb *LinUserIdentiyCreateBulk) Exec(ctx context.Context) error { + _, err := luicb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luicb *LinUserIdentiyCreateBulk) ExecX(ctx context.Context) { + if err := luicb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/data/model/linuseridentiy_delete.go b/internal/data/model/linuseridentiy_delete.go new file mode 100644 index 0000000..74d2ac9 --- /dev/null +++ b/internal/data/model/linuseridentiy_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyDelete is the builder for deleting a LinUserIdentiy entity. +type LinUserIdentiyDelete struct { + config + hooks []Hook + mutation *LinUserIdentiyMutation +} + +// Where appends a list predicates to the LinUserIdentiyDelete builder. +func (luid *LinUserIdentiyDelete) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyDelete { + luid.mutation.Where(ps...) + return luid +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (luid *LinUserIdentiyDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(luid.hooks) == 0 { + affected, err = luid.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luid.mutation = mutation + affected, err = luid.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(luid.hooks) - 1; i >= 0; i-- { + if luid.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luid.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luid.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luid *LinUserIdentiyDelete) ExecX(ctx context.Context) int { + n, err := luid.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (luid *LinUserIdentiyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + if ps := luid.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, luid.driver, _spec) +} + +// LinUserIdentiyDeleteOne is the builder for deleting a single LinUserIdentiy entity. +type LinUserIdentiyDeleteOne struct { + luid *LinUserIdentiyDelete +} + +// Exec executes the deletion query. +func (luido *LinUserIdentiyDeleteOne) Exec(ctx context.Context) error { + n, err := luido.luid.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{linuseridentiy.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (luido *LinUserIdentiyDeleteOne) ExecX(ctx context.Context) { + luido.luid.ExecX(ctx) +} diff --git a/internal/data/model/linuseridentiy_query.go b/internal/data/model/linuseridentiy_query.go new file mode 100644 index 0000000..2a91964 --- /dev/null +++ b/internal/data/model/linuseridentiy_query.go @@ -0,0 +1,965 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyQuery is the builder for querying LinUserIdentiy entities. +type LinUserIdentiyQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.LinUserIdentiy + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinUserIdentiyQuery builder. +func (luiq *LinUserIdentiyQuery) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyQuery { + luiq.predicates = append(luiq.predicates, ps...) + return luiq +} + +// Limit adds a limit step to the query. +func (luiq *LinUserIdentiyQuery) Limit(limit int) *LinUserIdentiyQuery { + luiq.limit = &limit + return luiq +} + +// Offset adds an offset step to the query. +func (luiq *LinUserIdentiyQuery) Offset(offset int) *LinUserIdentiyQuery { + luiq.offset = &offset + return luiq +} + +// 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 (luiq *LinUserIdentiyQuery) Unique(unique bool) *LinUserIdentiyQuery { + luiq.unique = &unique + return luiq +} + +// Order adds an order step to the query. +func (luiq *LinUserIdentiyQuery) Order(o ...OrderFunc) *LinUserIdentiyQuery { + luiq.order = append(luiq.order, o...) + return luiq +} + +// First returns the first LinUserIdentiy entity from the query. +// Returns a *NotFoundError when no LinUserIdentiy was found. +func (luiq *LinUserIdentiyQuery) First(ctx context.Context) (*LinUserIdentiy, error) { + nodes, err := luiq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuseridentiy.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) FirstX(ctx context.Context) *LinUserIdentiy { + node, err := luiq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LinUserIdentiy ID from the query. +// Returns a *NotFoundError when no LinUserIdentiy ID was found. +func (luiq *LinUserIdentiyQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luiq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuseridentiy.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) FirstIDX(ctx context.Context) int { + id, err := luiq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Last returns the last LinUserIdentiy entity from the query. +// Returns a *NotFoundError when no LinUserIdentiy was found. +func (luiq *LinUserIdentiyQuery) Last(ctx context.Context) (*LinUserIdentiy, error) { + nodes, err := luiq.All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{linuseridentiy.Label} + } + return nodes[len(nodes)-1], nil +} + +// LastX is like Last, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) LastX(ctx context.Context) *LinUserIdentiy { + node, err := luiq.Last(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// LastID returns the last LinUserIdentiy ID from the query. +// Returns a *NotFoundError when no LinUserIdentiy ID was found. +func (luiq *LinUserIdentiyQuery) LastID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luiq.IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{linuseridentiy.Label} + return + } + return ids[len(ids)-1], nil +} + +// LastIDX is like LastID, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) LastIDX(ctx context.Context) int { + id, err := luiq.LastID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LinUserIdentiy entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one LinUserIdentiy entity is not found. +// Returns a *NotFoundError when no LinUserIdentiy entities are found. +func (luiq *LinUserIdentiyQuery) Only(ctx context.Context) (*LinUserIdentiy, error) { + nodes, err := luiq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{linuseridentiy.Label} + default: + return nil, &NotSingularError{linuseridentiy.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) OnlyX(ctx context.Context) *LinUserIdentiy { + node, err := luiq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LinUserIdentiy ID in the query. +// Returns a *NotSingularError when exactly one LinUserIdentiy ID is not found. +// Returns a *NotFoundError when no entities are found. +func (luiq *LinUserIdentiyQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = luiq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = &NotSingularError{linuseridentiy.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) OnlyIDX(ctx context.Context) int { + id, err := luiq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LinUserIdentiys. +func (luiq *LinUserIdentiyQuery) All(ctx context.Context) ([]*LinUserIdentiy, error) { + if err := luiq.prepareQuery(ctx); err != nil { + return nil, err + } + return luiq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) AllX(ctx context.Context) []*LinUserIdentiy { + nodes, err := luiq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LinUserIdentiy IDs. +func (luiq *LinUserIdentiyQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := luiq.Select(linuseridentiy.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) IDsX(ctx context.Context) []int { + ids, err := luiq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (luiq *LinUserIdentiyQuery) Count(ctx context.Context) (int, error) { + if err := luiq.prepareQuery(ctx); err != nil { + return 0, err + } + return luiq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) CountX(ctx context.Context) int { + count, err := luiq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (luiq *LinUserIdentiyQuery) Exist(ctx context.Context) (bool, error) { + if err := luiq.prepareQuery(ctx); err != nil { + return false, err + } + return luiq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (luiq *LinUserIdentiyQuery) ExistX(ctx context.Context) bool { + exist, err := luiq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinUserIdentiyQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (luiq *LinUserIdentiyQuery) Clone() *LinUserIdentiyQuery { + if luiq == nil { + return nil + } + return &LinUserIdentiyQuery{ + config: luiq.config, + limit: luiq.limit, + offset: luiq.offset, + order: append([]OrderFunc{}, luiq.order...), + predicates: append([]predicate.LinUserIdentiy{}, luiq.predicates...), + // clone intermediate query. + sql: luiq.sql.Clone(), + path: luiq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// UserID int `json:"user_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinUserIdentiy.Query(). +// GroupBy(linuseridentiy.FieldUserID). +// Aggregate(model.Count()). +// Scan(ctx, &v) +// +func (luiq *LinUserIdentiyQuery) GroupBy(field string, fields ...string) *LinUserIdentiyGroupBy { + group := &LinUserIdentiyGroupBy{config: luiq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := luiq.prepareQuery(ctx); err != nil { + return nil, err + } + return luiq.sqlQuery(ctx), nil + } + return group +} + +// 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 int `json:"user_id,omitempty"` +// } +// +// client.LinUserIdentiy.Query(). +// Select(linuseridentiy.FieldUserID). +// Scan(ctx, &v) +// +func (luiq *LinUserIdentiyQuery) Select(fields ...string) *LinUserIdentiySelect { + luiq.fields = append(luiq.fields, fields...) + return &LinUserIdentiySelect{LinUserIdentiyQuery: luiq} +} + +func (luiq *LinUserIdentiyQuery) prepareQuery(ctx context.Context) error { + for _, f := range luiq.fields { + if !linuseridentiy.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + } + if luiq.path != nil { + prev, err := luiq.path(ctx) + if err != nil { + return err + } + luiq.sql = prev + } + return nil +} + +func (luiq *LinUserIdentiyQuery) sqlAll(ctx context.Context) ([]*LinUserIdentiy, error) { + var ( + nodes = []*LinUserIdentiy{} + withFKs = luiq.withFKs + _spec = luiq.querySpec() + ) + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &LinUserIdentiy{config: luiq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("model: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, luiq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (luiq *LinUserIdentiyQuery) sqlCount(ctx context.Context) (int, error) { + _spec := luiq.querySpec() + return sqlgraph.CountNodes(ctx, luiq.driver, _spec) +} + +func (luiq *LinUserIdentiyQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := luiq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("model: check existence: %w", err) + } + return n > 0, nil +} + +func (luiq *LinUserIdentiyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + Columns: linuseridentiy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + From: luiq.sql, + Unique: true, + } + if unique := luiq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := luiq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.FieldID) + for i := range fields { + if fields[i] != linuseridentiy.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := luiq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := luiq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := luiq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := luiq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (luiq *LinUserIdentiyQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(luiq.driver.Dialect()) + t1 := builder.Table(linuseridentiy.Table) + columns := luiq.fields + if len(columns) == 0 { + columns = linuseridentiy.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if luiq.sql != nil { + selector = luiq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, p := range luiq.predicates { + p(selector) + } + for _, p := range luiq.order { + p(selector) + } + if offset := luiq.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 := luiq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinUserIdentiyGroupBy is the group-by builder for LinUserIdentiy entities. +type LinUserIdentiyGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (luigb *LinUserIdentiyGroupBy) Aggregate(fns ...AggregateFunc) *LinUserIdentiyGroupBy { + luigb.fns = append(luigb.fns, fns...) + return luigb +} + +// Scan applies the group-by query and scans the result into the given value. +func (luigb *LinUserIdentiyGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := luigb.path(ctx) + if err != nil { + return err + } + luigb.sql = query + return luigb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := luigb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) StringsX(ctx context.Context) []string { + v, err := luigb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = luigb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) StringX(ctx context.Context) string { + v, err := luigb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) IntsX(ctx context.Context) []int { + v, err := luigb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = luigb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) IntX(ctx context.Context) int { + v, err := luigb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := luigb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = luigb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) Float64X(ctx context.Context) float64 { + v, err := luigb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(luigb.fields) > 1 { + return nil, errors.New("model: LinUserIdentiyGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := luigb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) BoolsX(ctx context.Context) []bool { + v, err := luigb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (luigb *LinUserIdentiyGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = luigb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiyGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (luigb *LinUserIdentiyGroupBy) BoolX(ctx context.Context) bool { + v, err := luigb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (luigb *LinUserIdentiyGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range luigb.fields { + if !linuseridentiy.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := luigb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := luigb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (luigb *LinUserIdentiyGroupBy) sqlQuery() *sql.Selector { + selector := luigb.sql.Select() + aggregation := make([]string, 0, len(luigb.fns)) + for _, fn := range luigb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(luigb.fields)+len(luigb.fns)) + for _, f := range luigb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(luigb.fields...)...) +} + +// LinUserIdentiySelect is the builder for selecting fields of LinUserIdentiy entities. +type LinUserIdentiySelect struct { + *LinUserIdentiyQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (luis *LinUserIdentiySelect) Scan(ctx context.Context, v interface{}) error { + if err := luis.prepareQuery(ctx); err != nil { + return err + } + luis.sql = luis.LinUserIdentiyQuery.sqlQuery(ctx) + return luis.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (luis *LinUserIdentiySelect) ScanX(ctx context.Context, v interface{}) { + if err := luis.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Strings(ctx context.Context) ([]string, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (luis *LinUserIdentiySelect) StringsX(ctx context.Context) []string { + v, err := luis.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = luis.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (luis *LinUserIdentiySelect) StringX(ctx context.Context) string { + v, err := luis.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Ints(ctx context.Context) ([]int, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (luis *LinUserIdentiySelect) IntsX(ctx context.Context) []int { + v, err := luis.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = luis.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (luis *LinUserIdentiySelect) IntX(ctx context.Context) int { + v, err := luis.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Float64s(ctx context.Context) ([]float64, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (luis *LinUserIdentiySelect) Float64sX(ctx context.Context) []float64 { + v, err := luis.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = luis.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (luis *LinUserIdentiySelect) Float64X(ctx context.Context) float64 { + v, err := luis.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Bools(ctx context.Context) ([]bool, error) { + if len(luis.fields) > 1 { + return nil, errors.New("model: LinUserIdentiySelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := luis.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (luis *LinUserIdentiySelect) BoolsX(ctx context.Context) []bool { + v, err := luis.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (luis *LinUserIdentiySelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = luis.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{linuseridentiy.Label} + default: + err = fmt.Errorf("model: LinUserIdentiySelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (luis *LinUserIdentiySelect) BoolX(ctx context.Context) bool { + v, err := luis.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (luis *LinUserIdentiySelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := luis.sql.Query() + if err := luis.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/data/model/linuseridentiy_update.go b/internal/data/model/linuseridentiy_update.go new file mode 100644 index 0000000..d11f59b --- /dev/null +++ b/internal/data/model/linuseridentiy_update.go @@ -0,0 +1,370 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinUserIdentiyUpdate is the builder for updating LinUserIdentiy entities. +type LinUserIdentiyUpdate struct { + config + hooks []Hook + mutation *LinUserIdentiyMutation +} + +// Where appends a list predicates to the LinUserIdentiyUpdate builder. +func (luiu *LinUserIdentiyUpdate) Where(ps ...predicate.LinUserIdentiy) *LinUserIdentiyUpdate { + luiu.mutation.Where(ps...) + return luiu +} + +// SetUserID sets the "user_id" field. +func (luiu *LinUserIdentiyUpdate) SetUserID(i int) *LinUserIdentiyUpdate { + luiu.mutation.ResetUserID() + luiu.mutation.SetUserID(i) + return luiu +} + +// AddUserID adds i to the "user_id" field. +func (luiu *LinUserIdentiyUpdate) AddUserID(i int) *LinUserIdentiyUpdate { + luiu.mutation.AddUserID(i) + return luiu +} + +// SetIdentityType sets the "identity_type" field. +func (luiu *LinUserIdentiyUpdate) SetIdentityType(s string) *LinUserIdentiyUpdate { + luiu.mutation.SetIdentityType(s) + return luiu +} + +// SetIdentifier sets the "identifier" field. +func (luiu *LinUserIdentiyUpdate) SetIdentifier(s string) *LinUserIdentiyUpdate { + luiu.mutation.SetIdentifier(s) + return luiu +} + +// SetCredential sets the "credential" field. +func (luiu *LinUserIdentiyUpdate) SetCredential(s string) *LinUserIdentiyUpdate { + luiu.mutation.SetCredential(s) + return luiu +} + +// Mutation returns the LinUserIdentiyMutation object of the builder. +func (luiu *LinUserIdentiyUpdate) Mutation() *LinUserIdentiyMutation { + return luiu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (luiu *LinUserIdentiyUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(luiu.hooks) == 0 { + affected, err = luiu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luiu.mutation = mutation + affected, err = luiu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(luiu.hooks) - 1; i >= 0; i-- { + if luiu.hooks[i] == nil { + return 0, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luiu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luiu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luiu *LinUserIdentiyUpdate) SaveX(ctx context.Context) int { + affected, err := luiu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (luiu *LinUserIdentiyUpdate) Exec(ctx context.Context) error { + _, err := luiu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luiu *LinUserIdentiyUpdate) ExecX(ctx context.Context) { + if err := luiu.Exec(ctx); err != nil { + panic(err) + } +} + +func (luiu *LinUserIdentiyUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + Columns: linuseridentiy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + if ps := luiu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luiu.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiu.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiu.mutation.IdentityType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentityType, + }) + } + if value, ok := luiu.mutation.Identifier(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentifier, + }) + } + if value, ok := luiu.mutation.Credential(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldCredential, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, luiu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuseridentiy.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// LinUserIdentiyUpdateOne is the builder for updating a single LinUserIdentiy entity. +type LinUserIdentiyUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinUserIdentiyMutation +} + +// SetUserID sets the "user_id" field. +func (luiuo *LinUserIdentiyUpdateOne) SetUserID(i int) *LinUserIdentiyUpdateOne { + luiuo.mutation.ResetUserID() + luiuo.mutation.SetUserID(i) + return luiuo +} + +// AddUserID adds i to the "user_id" field. +func (luiuo *LinUserIdentiyUpdateOne) AddUserID(i int) *LinUserIdentiyUpdateOne { + luiuo.mutation.AddUserID(i) + return luiuo +} + +// SetIdentityType sets the "identity_type" field. +func (luiuo *LinUserIdentiyUpdateOne) SetIdentityType(s string) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetIdentityType(s) + return luiuo +} + +// SetIdentifier sets the "identifier" field. +func (luiuo *LinUserIdentiyUpdateOne) SetIdentifier(s string) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetIdentifier(s) + return luiuo +} + +// SetCredential sets the "credential" field. +func (luiuo *LinUserIdentiyUpdateOne) SetCredential(s string) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetCredential(s) + return luiuo +} + +// Mutation returns the LinUserIdentiyMutation object of the builder. +func (luiuo *LinUserIdentiyUpdateOne) Mutation() *LinUserIdentiyMutation { + return luiuo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (luiuo *LinUserIdentiyUpdateOne) Select(field string, fields ...string) *LinUserIdentiyUpdateOne { + luiuo.fields = append([]string{field}, fields...) + return luiuo +} + +// Save executes the query and returns the updated LinUserIdentiy entity. +func (luiuo *LinUserIdentiyUpdateOne) Save(ctx context.Context) (*LinUserIdentiy, error) { + var ( + err error + node *LinUserIdentiy + ) + if len(luiuo.hooks) == 0 { + node, err = luiuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinUserIdentiyMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + luiuo.mutation = mutation + node, err = luiuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(luiuo.hooks) - 1; i >= 0; i-- { + if luiuo.hooks[i] == nil { + return nil, fmt.Errorf("model: uninitialized hook (forgotten import model/runtime?)") + } + mut = luiuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, luiuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (luiuo *LinUserIdentiyUpdateOne) SaveX(ctx context.Context) *LinUserIdentiy { + node, err := luiuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (luiuo *LinUserIdentiyUpdateOne) Exec(ctx context.Context) error { + _, err := luiuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luiuo *LinUserIdentiyUpdateOne) ExecX(ctx context.Context) { + if err := luiuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (luiuo *LinUserIdentiyUpdateOne) sqlSave(ctx context.Context) (_node *LinUserIdentiy, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: linuseridentiy.Table, + Columns: linuseridentiy.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: linuseridentiy.FieldID, + }, + }, + } + id, ok := luiuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing LinUserIdentiy.ID for update")} + } + _spec.Node.ID.Value = id + if fields := luiuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, linuseridentiy.FieldID) + for _, f := range fields { + if !linuseridentiy.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("model: invalid field %q for query", f)} + } + if f != linuseridentiy.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := luiuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luiuo.mutation.UserID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiuo.mutation.AddedUserID(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: linuseridentiy.FieldUserID, + }) + } + if value, ok := luiuo.mutation.IdentityType(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentityType, + }) + } + if value, ok := luiuo.mutation.Identifier(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldIdentifier, + }) + } + if value, ok := luiuo.mutation.Credential(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: linuseridentiy.FieldCredential, + }) + } + _node = &LinUserIdentiy{config: luiuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, luiuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{linuseridentiy.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/internal/data/model/migrate/migrate.go b/internal/data/model/migrate/migrate.go new file mode 100644 index 0000000..e4a9a22 --- /dev/null +++ b/internal/data/model/migrate/migrate.go @@ -0,0 +1,72 @@ +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithFixture sets the foreign-key renaming option to the migration when upgrading + // ent from v0.1.0 (issue-#285). Defaults to false. + WithFixture = schema.WithFixture + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver + universalID bool +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +// +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + drv := &schema.WriteDriver{ + Writer: w, + Driver: s.drv, + } + migrate, err := schema.NewMigrate(drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} diff --git a/internal/data/model/migrate/schema.go b/internal/data/model/migrate/schema.go new file mode 100644 index 0000000..5de9495 --- /dev/null +++ b/internal/data/model/migrate/schema.go @@ -0,0 +1,219 @@ +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // BookColumns holds the columns for the "book" table. + BookColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "title", Type: field.TypeString}, + {Name: "author", Type: field.TypeString}, + {Name: "summary", Type: field.TypeString}, + {Name: "image", Type: field.TypeString}, + } + // BookTable holds the schema information for the "book" table. + BookTable = &schema.Table{ + Name: "book", + Columns: BookColumns, + PrimaryKey: []*schema.Column{BookColumns[0]}, + } + // LinFileColumns holds the columns for the "lin_file" table. + LinFileColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "path", Type: field.TypeString}, + {Name: "type", Type: field.TypeInt8}, + {Name: "name", Type: field.TypeString}, + {Name: "extension", Type: field.TypeString}, + {Name: "size", Type: field.TypeInt}, + {Name: "md5", Type: field.TypeString, Unique: true}, + } + // LinFileTable holds the schema information for the "lin_file" table. + LinFileTable = &schema.Table{ + Name: "lin_file", + Columns: LinFileColumns, + PrimaryKey: []*schema.Column{LinFileColumns[0]}, + } + // LinGroupColumns holds the columns for the "lin_group" table. + LinGroupColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Unique: true}, + {Name: "info", Type: field.TypeString}, + {Name: "level", Type: field.TypeInt8}, + } + // LinGroupTable holds the schema information for the "lin_group" table. + LinGroupTable = &schema.Table{ + Name: "lin_group", + Columns: LinGroupColumns, + PrimaryKey: []*schema.Column{LinGroupColumns[0]}, + } + // LinLogColumns holds the columns for the "lin_log" table. + LinLogColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime}, + {Name: "message", Type: field.TypeString}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "username", Type: field.TypeString}, + {Name: "status_code", Type: field.TypeInt}, + {Name: "method", Type: field.TypeString}, + {Name: "path", Type: field.TypeString}, + {Name: "permission", Type: field.TypeString}, + } + // LinLogTable holds the schema information for the "lin_log" table. + LinLogTable = &schema.Table{ + Name: "lin_log", + Columns: LinLogColumns, + PrimaryKey: []*schema.Column{LinLogColumns[0]}, + } + // LinPermissionColumns holds the columns for the "lin_permission" table. + LinPermissionColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "module", Type: field.TypeString}, + {Name: "mount", Type: field.TypeInt8}, + } + // LinPermissionTable holds the schema information for the "lin_permission" table. + LinPermissionTable = &schema.Table{ + Name: "lin_permission", + Columns: LinPermissionColumns, + PrimaryKey: []*schema.Column{LinPermissionColumns[0]}, + } + // LinUserColumns holds the columns for the "lin_user" table. + LinUserColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime}, + {Name: "username", Type: field.TypeString, Unique: true}, + {Name: "nickname", Type: field.TypeString}, + {Name: "avatar", Type: field.TypeString, Default: ""}, + {Name: "email", Type: field.TypeString, Unique: true}, + } + // LinUserTable holds the schema information for the "lin_user" table. + LinUserTable = &schema.Table{ + Name: "lin_user", + Columns: LinUserColumns, + PrimaryKey: []*schema.Column{LinUserColumns[0]}, + } + // LinUserIdentiyColumns holds the columns for the "lin_user_identiy" table. + LinUserIdentiyColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "identity_type", Type: field.TypeString}, + {Name: "identifier", Type: field.TypeString}, + {Name: "credential", Type: field.TypeString}, + {Name: "lin_user_lin_user_identiy", Type: field.TypeInt, Nullable: true}, + } + // LinUserIdentiyTable holds the schema information for the "lin_user_identiy" table. + LinUserIdentiyTable = &schema.Table{ + Name: "lin_user_identiy", + Columns: LinUserIdentiyColumns, + PrimaryKey: []*schema.Column{LinUserIdentiyColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_user_identiy_lin_user_lin_user_identiy", + Columns: []*schema.Column{LinUserIdentiyColumns[5]}, + RefColumns: []*schema.Column{LinUserColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // LinUserGroupColumns holds the columns for the "lin_user_group" table. + LinUserGroupColumns = []*schema.Column{ + {Name: "user_id", Type: field.TypeInt}, + {Name: "group_id", Type: field.TypeInt}, + } + // LinUserGroupTable holds the schema information for the "lin_user_group" table. + LinUserGroupTable = &schema.Table{ + Name: "lin_user_group", + Columns: LinUserGroupColumns, + PrimaryKey: []*schema.Column{LinUserGroupColumns[0], LinUserGroupColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_user_group_user_id", + Columns: []*schema.Column{LinUserGroupColumns[0]}, + RefColumns: []*schema.Column{LinGroupColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "lin_user_group_group_id", + Columns: []*schema.Column{LinUserGroupColumns[1]}, + RefColumns: []*schema.Column{LinUserColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // LinGroupPermissionColumns holds the columns for the "lin_group_permission" table. + LinGroupPermissionColumns = []*schema.Column{ + {Name: "permission_id", Type: field.TypeInt}, + {Name: "group_id", Type: field.TypeInt}, + } + // LinGroupPermissionTable holds the schema information for the "lin_group_permission" table. + LinGroupPermissionTable = &schema.Table{ + Name: "lin_group_permission", + Columns: LinGroupPermissionColumns, + PrimaryKey: []*schema.Column{LinGroupPermissionColumns[0], LinGroupPermissionColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_group_permission_permission_id", + Columns: []*schema.Column{LinGroupPermissionColumns[0]}, + RefColumns: []*schema.Column{LinPermissionColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "lin_group_permission_group_id", + Columns: []*schema.Column{LinGroupPermissionColumns[1]}, + RefColumns: []*schema.Column{LinGroupColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + BookTable, + LinFileTable, + LinGroupTable, + LinLogTable, + LinPermissionTable, + LinUserTable, + LinUserIdentiyTable, + LinUserGroupTable, + LinGroupPermissionTable, + } +) + +func init() { + BookTable.Annotation = &entsql.Annotation{ + Table: "book", + } + LinFileTable.Annotation = &entsql.Annotation{ + Table: "lin_file", + } + LinGroupTable.Annotation = &entsql.Annotation{ + Table: "lin_group", + } + LinLogTable.Annotation = &entsql.Annotation{ + Table: "lin_log", + } + LinPermissionTable.Annotation = &entsql.Annotation{ + Table: "lin_permission", + } + LinUserTable.Annotation = &entsql.Annotation{ + Table: "lin_user", + } + LinUserIdentiyTable.ForeignKeys[0].RefTable = LinUserTable + LinUserIdentiyTable.Annotation = &entsql.Annotation{ + Table: "lin_user_identiy", + } + LinUserGroupTable.ForeignKeys[0].RefTable = LinGroupTable + LinUserGroupTable.ForeignKeys[1].RefTable = LinUserTable + LinGroupPermissionTable.ForeignKeys[0].RefTable = LinPermissionTable + LinGroupPermissionTable.ForeignKeys[1].RefTable = LinGroupTable +} diff --git a/internal/data/model/mutation.go b/internal/data/model/mutation.go new file mode 100644 index 0000000..9391c9e --- /dev/null +++ b/internal/data/model/mutation.go @@ -0,0 +1,4393 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "fmt" + "lin-cms-go/internal/data/model/book" + "lin-cms-go/internal/data/model/linfile" + "lin-cms-go/internal/data/model/lingroup" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linpermission" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "lin-cms-go/internal/data/model/predicate" + "sync" + "time" + + "entgo.io/ent" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeBook = "Book" + TypeLinFile = "LinFile" + TypeLinGroup = "LinGroup" + TypeLinLog = "LinLog" + TypeLinPermission = "LinPermission" + TypeLinUser = "LinUser" + TypeLinUserIdentiy = "LinUserIdentiy" +) + +// BookMutation represents an operation that mutates the Book nodes in the graph. +type BookMutation struct { + config + op Op + typ string + id *int + title *string + author *string + summary *string + image *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Book, error) + predicates []predicate.Book +} + +var _ ent.Mutation = (*BookMutation)(nil) + +// bookOption allows management of the mutation configuration using functional options. +type bookOption func(*BookMutation) + +// newBookMutation creates new mutation for the Book entity. +func newBookMutation(c config, op Op, opts ...bookOption) *BookMutation { + m := &BookMutation{ + config: c, + op: op, + typ: TypeBook, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBookID sets the ID field of the mutation. +func withBookID(id int) bookOption { + return func(m *BookMutation) { + var ( + err error + once sync.Once + value *Book + ) + m.oldValue = func(ctx context.Context) (*Book, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Book.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBook sets the old Book of the mutation. +func withBook(node *Book) bookOption { + return func(m *BookMutation) { + m.oldValue = func(context.Context) (*Book, 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 BookMutation) 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 BookMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *BookMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetTitle sets the "title" field. +func (m *BookMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *BookMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Book entity. +// If the Book 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 *BookMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *BookMutation) ResetTitle() { + m.title = nil +} + +// SetAuthor sets the "author" field. +func (m *BookMutation) SetAuthor(s string) { + m.author = &s +} + +// Author returns the value of the "author" field in the mutation. +func (m *BookMutation) Author() (r string, exists bool) { + v := m.author + if v == nil { + return + } + return *v, true +} + +// OldAuthor returns the old "author" field's value of the Book entity. +// If the Book 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 *BookMutation) OldAuthor(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldAuthor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldAuthor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthor: %w", err) + } + return oldValue.Author, nil +} + +// ResetAuthor resets all changes to the "author" field. +func (m *BookMutation) ResetAuthor() { + m.author = nil +} + +// SetSummary sets the "summary" field. +func (m *BookMutation) SetSummary(s string) { + m.summary = &s +} + +// Summary returns the value of the "summary" field in the mutation. +func (m *BookMutation) Summary() (r string, exists bool) { + v := m.summary + if v == nil { + return + } + return *v, true +} + +// OldSummary returns the old "summary" field's value of the Book entity. +// If the Book 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 *BookMutation) OldSummary(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldSummary is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldSummary requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSummary: %w", err) + } + return oldValue.Summary, nil +} + +// ResetSummary resets all changes to the "summary" field. +func (m *BookMutation) ResetSummary() { + m.summary = nil +} + +// SetImage sets the "image" field. +func (m *BookMutation) SetImage(s string) { + m.image = &s +} + +// Image returns the value of the "image" field in the mutation. +func (m *BookMutation) Image() (r string, exists bool) { + v := m.image + if v == nil { + return + } + return *v, true +} + +// OldImage returns the old "image" field's value of the Book entity. +// If the Book 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 *BookMutation) OldImage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldImage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldImage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImage: %w", err) + } + return oldValue.Image, nil +} + +// ResetImage resets all changes to the "image" field. +func (m *BookMutation) ResetImage() { + m.image = nil +} + +// Where appends a list predicates to the BookMutation builder. +func (m *BookMutation) Where(ps ...predicate.Book) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *BookMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Book). +func (m *BookMutation) 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 *BookMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.title != nil { + fields = append(fields, book.FieldTitle) + } + if m.author != nil { + fields = append(fields, book.FieldAuthor) + } + if m.summary != nil { + fields = append(fields, book.FieldSummary) + } + if m.image != nil { + fields = append(fields, book.FieldImage) + } + 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 *BookMutation) Field(name string) (ent.Value, bool) { + switch name { + case book.FieldTitle: + return m.Title() + case book.FieldAuthor: + return m.Author() + case book.FieldSummary: + return m.Summary() + case book.FieldImage: + return m.Image() + } + 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 *BookMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case book.FieldTitle: + return m.OldTitle(ctx) + case book.FieldAuthor: + return m.OldAuthor(ctx) + case book.FieldSummary: + return m.OldSummary(ctx) + case book.FieldImage: + return m.OldImage(ctx) + } + return nil, fmt.Errorf("unknown Book 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 *BookMutation) SetField(name string, value ent.Value) error { + switch name { + case book.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case book.FieldAuthor: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthor(v) + return nil + case book.FieldSummary: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSummary(v) + return nil + case book.FieldImage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImage(v) + return nil + } + return fmt.Errorf("unknown Book field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BookMutation) 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 *BookMutation) 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 *BookMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Book numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BookMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BookMutation) 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 *BookMutation) ClearField(name string) error { + return fmt.Errorf("unknown Book 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 *BookMutation) ResetField(name string) error { + switch name { + case book.FieldTitle: + m.ResetTitle() + return nil + case book.FieldAuthor: + m.ResetAuthor() + return nil + case book.FieldSummary: + m.ResetSummary() + return nil + case book.FieldImage: + m.ResetImage() + return nil + } + return fmt.Errorf("unknown Book field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BookMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BookMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BookMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BookMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BookMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BookMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *BookMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Book 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 *BookMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Book edge %s", name) +} + +// LinFileMutation represents an operation that mutates the LinFile nodes in the graph. +type LinFileMutation struct { + config + op Op + typ string + id *int + _path *string + _type *int8 + add_type *int8 + name *string + extension *string + size *int + addsize *int + md5 *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinFile, error) + predicates []predicate.LinFile +} + +var _ ent.Mutation = (*LinFileMutation)(nil) + +// linfileOption allows management of the mutation configuration using functional options. +type linfileOption func(*LinFileMutation) + +// newLinFileMutation creates new mutation for the LinFile entity. +func newLinFileMutation(c config, op Op, opts ...linfileOption) *LinFileMutation { + m := &LinFileMutation{ + config: c, + op: op, + typ: TypeLinFile, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinFileID sets the ID field of the mutation. +func withLinFileID(id int) linfileOption { + return func(m *LinFileMutation) { + var ( + err error + once sync.Once + value *LinFile + ) + m.oldValue = func(ctx context.Context) (*LinFile, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinFile.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinFile sets the old LinFile of the mutation. +func withLinFile(node *LinFile) linfileOption { + return func(m *LinFileMutation) { + m.oldValue = func(context.Context) (*LinFile, 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 LinFileMutation) 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 LinFileMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinFileMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetPath sets the "path" field. +func (m *LinFileMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *LinFileMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *LinFileMutation) ResetPath() { + m._path = nil +} + +// SetType sets the "type" field. +func (m *LinFileMutation) SetType(i int8) { + m._type = &i + m.add_type = nil +} + +// GetType returns the value of the "type" field in the mutation. +func (m *LinFileMutation) GetType() (r int8, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldType(ctx context.Context) (v int8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// AddType adds i to the "type" field. +func (m *LinFileMutation) AddType(i int8) { + if m.add_type != nil { + *m.add_type += i + } else { + m.add_type = &i + } +} + +// AddedType returns the value that was added to the "type" field in this mutation. +func (m *LinFileMutation) AddedType() (r int8, exists bool) { + v := m.add_type + if v == nil { + return + } + return *v, true +} + +// ResetType resets all changes to the "type" field. +func (m *LinFileMutation) ResetType() { + m._type = nil + m.add_type = nil +} + +// SetName sets the "name" field. +func (m *LinFileMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *LinFileMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *LinFileMutation) ResetName() { + m.name = nil +} + +// SetExtension sets the "extension" field. +func (m *LinFileMutation) SetExtension(s string) { + m.extension = &s +} + +// Extension returns the value of the "extension" field in the mutation. +func (m *LinFileMutation) Extension() (r string, exists bool) { + v := m.extension + if v == nil { + return + } + return *v, true +} + +// OldExtension returns the old "extension" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldExtension(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldExtension is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldExtension requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExtension: %w", err) + } + return oldValue.Extension, nil +} + +// ResetExtension resets all changes to the "extension" field. +func (m *LinFileMutation) ResetExtension() { + m.extension = nil +} + +// SetSize sets the "size" field. +func (m *LinFileMutation) SetSize(i int) { + m.size = &i + m.addsize = nil +} + +// Size returns the value of the "size" field in the mutation. +func (m *LinFileMutation) Size() (r int, exists bool) { + v := m.size + if v == nil { + return + } + return *v, true +} + +// OldSize returns the old "size" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldSize(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldSize is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldSize requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSize: %w", err) + } + return oldValue.Size, nil +} + +// AddSize adds i to the "size" field. +func (m *LinFileMutation) AddSize(i int) { + if m.addsize != nil { + *m.addsize += i + } else { + m.addsize = &i + } +} + +// AddedSize returns the value that was added to the "size" field in this mutation. +func (m *LinFileMutation) AddedSize() (r int, exists bool) { + v := m.addsize + if v == nil { + return + } + return *v, true +} + +// ResetSize resets all changes to the "size" field. +func (m *LinFileMutation) ResetSize() { + m.size = nil + m.addsize = nil +} + +// SetMd5 sets the "md5" field. +func (m *LinFileMutation) SetMd5(s string) { + m.md5 = &s +} + +// Md5 returns the value of the "md5" field in the mutation. +func (m *LinFileMutation) Md5() (r string, exists bool) { + v := m.md5 + if v == nil { + return + } + return *v, true +} + +// OldMd5 returns the old "md5" field's value of the LinFile entity. +// If the LinFile 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 *LinFileMutation) OldMd5(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMd5 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMd5 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMd5: %w", err) + } + return oldValue.Md5, nil +} + +// ResetMd5 resets all changes to the "md5" field. +func (m *LinFileMutation) ResetMd5() { + m.md5 = nil +} + +// Where appends a list predicates to the LinFileMutation builder. +func (m *LinFileMutation) Where(ps ...predicate.LinFile) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinFileMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinFile). +func (m *LinFileMutation) 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 *LinFileMutation) Fields() []string { + fields := make([]string, 0, 6) + if m._path != nil { + fields = append(fields, linfile.FieldPath) + } + if m._type != nil { + fields = append(fields, linfile.FieldType) + } + if m.name != nil { + fields = append(fields, linfile.FieldName) + } + if m.extension != nil { + fields = append(fields, linfile.FieldExtension) + } + if m.size != nil { + fields = append(fields, linfile.FieldSize) + } + if m.md5 != nil { + fields = append(fields, linfile.FieldMd5) + } + 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 *LinFileMutation) Field(name string) (ent.Value, bool) { + switch name { + case linfile.FieldPath: + return m.Path() + case linfile.FieldType: + return m.GetType() + case linfile.FieldName: + return m.Name() + case linfile.FieldExtension: + return m.Extension() + case linfile.FieldSize: + return m.Size() + case linfile.FieldMd5: + return m.Md5() + } + 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 *LinFileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linfile.FieldPath: + return m.OldPath(ctx) + case linfile.FieldType: + return m.OldType(ctx) + case linfile.FieldName: + return m.OldName(ctx) + case linfile.FieldExtension: + return m.OldExtension(ctx) + case linfile.FieldSize: + return m.OldSize(ctx) + case linfile.FieldMd5: + return m.OldMd5(ctx) + } + return nil, fmt.Errorf("unknown LinFile 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 *LinFileMutation) SetField(name string, value ent.Value) error { + switch name { + case linfile.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case linfile.FieldType: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case linfile.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case linfile.FieldExtension: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExtension(v) + return nil + case linfile.FieldSize: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSize(v) + return nil + case linfile.FieldMd5: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMd5(v) + return nil + } + return fmt.Errorf("unknown LinFile field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinFileMutation) AddedFields() []string { + var fields []string + if m.add_type != nil { + fields = append(fields, linfile.FieldType) + } + if m.addsize != nil { + fields = append(fields, linfile.FieldSize) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinFileMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linfile.FieldType: + return m.AddedType() + case linfile.FieldSize: + return m.AddedSize() + } + 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 *LinFileMutation) AddField(name string, value ent.Value) error { + switch name { + case linfile.FieldType: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddType(v) + return nil + case linfile.FieldSize: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSize(v) + return nil + } + return fmt.Errorf("unknown LinFile numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinFileMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinFileMutation) 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 *LinFileMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinFile 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 *LinFileMutation) ResetField(name string) error { + switch name { + case linfile.FieldPath: + m.ResetPath() + return nil + case linfile.FieldType: + m.ResetType() + return nil + case linfile.FieldName: + m.ResetName() + return nil + case linfile.FieldExtension: + m.ResetExtension() + return nil + case linfile.FieldSize: + m.ResetSize() + return nil + case linfile.FieldMd5: + m.ResetMd5() + return nil + } + return fmt.Errorf("unknown LinFile field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinFileMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinFileMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinFileMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinFileMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinFileMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinFileMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinFileMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinFile 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 *LinFileMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinFile edge %s", name) +} + +// LinGroupMutation represents an operation that mutates the LinGroup nodes in the graph. +type LinGroupMutation struct { + config + op Op + typ string + id *int + name *string + info *string + level *int8 + addlevel *int8 + clearedFields map[string]struct{} + lin_user map[int]struct{} + removedlin_user map[int]struct{} + clearedlin_user bool + lin_permission map[int]struct{} + removedlin_permission map[int]struct{} + clearedlin_permission bool + done bool + oldValue func(context.Context) (*LinGroup, error) + predicates []predicate.LinGroup +} + +var _ ent.Mutation = (*LinGroupMutation)(nil) + +// lingroupOption allows management of the mutation configuration using functional options. +type lingroupOption func(*LinGroupMutation) + +// newLinGroupMutation creates new mutation for the LinGroup entity. +func newLinGroupMutation(c config, op Op, opts ...lingroupOption) *LinGroupMutation { + m := &LinGroupMutation{ + config: c, + op: op, + typ: TypeLinGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinGroupID sets the ID field of the mutation. +func withLinGroupID(id int) lingroupOption { + return func(m *LinGroupMutation) { + var ( + err error + once sync.Once + value *LinGroup + ) + m.oldValue = func(ctx context.Context) (*LinGroup, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinGroup sets the old LinGroup of the mutation. +func withLinGroup(node *LinGroup) lingroupOption { + return func(m *LinGroupMutation) { + m.oldValue = func(context.Context) (*LinGroup, 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 LinGroupMutation) 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 LinGroupMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinGroupMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetName sets the "name" field. +func (m *LinGroupMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *LinGroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *LinGroupMutation) ResetName() { + m.name = nil +} + +// SetInfo sets the "info" field. +func (m *LinGroupMutation) SetInfo(s string) { + m.info = &s +} + +// Info returns the value of the "info" field in the mutation. +func (m *LinGroupMutation) Info() (r string, exists bool) { + v := m.info + if v == nil { + return + } + return *v, true +} + +// OldInfo returns the old "info" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldInfo(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldInfo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldInfo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInfo: %w", err) + } + return oldValue.Info, nil +} + +// ResetInfo resets all changes to the "info" field. +func (m *LinGroupMutation) ResetInfo() { + m.info = nil +} + +// SetLevel sets the "level" field. +func (m *LinGroupMutation) SetLevel(i int8) { + m.level = &i + m.addlevel = nil +} + +// Level returns the value of the "level" field in the mutation. +func (m *LinGroupMutation) Level() (r int8, exists bool) { + v := m.level + if v == nil { + return + } + return *v, true +} + +// OldLevel returns the old "level" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldLevel(ctx context.Context) (v int8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldLevel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldLevel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLevel: %w", err) + } + return oldValue.Level, nil +} + +// AddLevel adds i to the "level" field. +func (m *LinGroupMutation) AddLevel(i int8) { + if m.addlevel != nil { + *m.addlevel += i + } else { + m.addlevel = &i + } +} + +// AddedLevel returns the value that was added to the "level" field in this mutation. +func (m *LinGroupMutation) AddedLevel() (r int8, exists bool) { + v := m.addlevel + if v == nil { + return + } + return *v, true +} + +// ResetLevel resets all changes to the "level" field. +func (m *LinGroupMutation) ResetLevel() { + m.level = nil + m.addlevel = nil +} + +// AddLinUserIDs adds the "lin_user" edge to the LinUser entity by ids. +func (m *LinGroupMutation) AddLinUserIDs(ids ...int) { + if m.lin_user == nil { + m.lin_user = make(map[int]struct{}) + } + for i := range ids { + m.lin_user[ids[i]] = struct{}{} + } +} + +// ClearLinUser clears the "lin_user" edge to the LinUser entity. +func (m *LinGroupMutation) ClearLinUser() { + m.clearedlin_user = true +} + +// LinUserCleared reports if the "lin_user" edge to the LinUser entity was cleared. +func (m *LinGroupMutation) LinUserCleared() bool { + return m.clearedlin_user +} + +// RemoveLinUserIDs removes the "lin_user" edge to the LinUser entity by IDs. +func (m *LinGroupMutation) RemoveLinUserIDs(ids ...int) { + if m.removedlin_user == nil { + m.removedlin_user = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_user, ids[i]) + m.removedlin_user[ids[i]] = struct{}{} + } +} + +// RemovedLinUser returns the removed IDs of the "lin_user" edge to the LinUser entity. +func (m *LinGroupMutation) RemovedLinUserIDs() (ids []int) { + for id := range m.removedlin_user { + ids = append(ids, id) + } + return +} + +// LinUserIDs returns the "lin_user" edge IDs in the mutation. +func (m *LinGroupMutation) LinUserIDs() (ids []int) { + for id := range m.lin_user { + ids = append(ids, id) + } + return +} + +// ResetLinUser resets all changes to the "lin_user" edge. +func (m *LinGroupMutation) ResetLinUser() { + m.lin_user = nil + m.clearedlin_user = false + m.removedlin_user = nil +} + +// AddLinPermissionIDs adds the "lin_permission" edge to the LinPermission entity by ids. +func (m *LinGroupMutation) AddLinPermissionIDs(ids ...int) { + if m.lin_permission == nil { + m.lin_permission = make(map[int]struct{}) + } + for i := range ids { + m.lin_permission[ids[i]] = struct{}{} + } +} + +// ClearLinPermission clears the "lin_permission" edge to the LinPermission entity. +func (m *LinGroupMutation) ClearLinPermission() { + m.clearedlin_permission = true +} + +// LinPermissionCleared reports if the "lin_permission" edge to the LinPermission entity was cleared. +func (m *LinGroupMutation) LinPermissionCleared() bool { + return m.clearedlin_permission +} + +// RemoveLinPermissionIDs removes the "lin_permission" edge to the LinPermission entity by IDs. +func (m *LinGroupMutation) RemoveLinPermissionIDs(ids ...int) { + if m.removedlin_permission == nil { + m.removedlin_permission = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_permission, ids[i]) + m.removedlin_permission[ids[i]] = struct{}{} + } +} + +// RemovedLinPermission returns the removed IDs of the "lin_permission" edge to the LinPermission entity. +func (m *LinGroupMutation) RemovedLinPermissionIDs() (ids []int) { + for id := range m.removedlin_permission { + ids = append(ids, id) + } + return +} + +// LinPermissionIDs returns the "lin_permission" edge IDs in the mutation. +func (m *LinGroupMutation) LinPermissionIDs() (ids []int) { + for id := range m.lin_permission { + ids = append(ids, id) + } + return +} + +// ResetLinPermission resets all changes to the "lin_permission" edge. +func (m *LinGroupMutation) ResetLinPermission() { + m.lin_permission = nil + m.clearedlin_permission = false + m.removedlin_permission = nil +} + +// Where appends a list predicates to the LinGroupMutation builder. +func (m *LinGroupMutation) Where(ps ...predicate.LinGroup) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinGroupMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinGroup). +func (m *LinGroupMutation) 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 *LinGroupMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, lingroup.FieldName) + } + if m.info != nil { + fields = append(fields, lingroup.FieldInfo) + } + if m.level != nil { + fields = append(fields, lingroup.FieldLevel) + } + 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 *LinGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case lingroup.FieldName: + return m.Name() + case lingroup.FieldInfo: + return m.Info() + case lingroup.FieldLevel: + return m.Level() + } + 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 *LinGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case lingroup.FieldName: + return m.OldName(ctx) + case lingroup.FieldInfo: + return m.OldInfo(ctx) + case lingroup.FieldLevel: + return m.OldLevel(ctx) + } + return nil, fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case lingroup.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case lingroup.FieldInfo: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInfo(v) + return nil + case lingroup.FieldLevel: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLevel(v) + return nil + } + return fmt.Errorf("unknown LinGroup field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinGroupMutation) AddedFields() []string { + var fields []string + if m.addlevel != nil { + fields = append(fields, lingroup.FieldLevel) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinGroupMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case lingroup.FieldLevel: + return m.AddedLevel() + } + 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 *LinGroupMutation) AddField(name string, value ent.Value) error { + switch name { + case lingroup.FieldLevel: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddLevel(v) + return nil + } + return fmt.Errorf("unknown LinGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinGroupMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinGroupMutation) 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 *LinGroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) ResetField(name string) error { + switch name { + case lingroup.FieldName: + m.ResetName() + return nil + case lingroup.FieldInfo: + m.ResetInfo() + return nil + case lingroup.FieldLevel: + m.ResetLevel() + return nil + } + return fmt.Errorf("unknown LinGroup field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.lin_user != nil { + edges = append(edges, lingroup.EdgeLinUser) + } + if m.lin_permission != nil { + edges = append(edges, lingroup.EdgeLinPermission) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case lingroup.EdgeLinUser: + ids := make([]ent.Value, 0, len(m.lin_user)) + for id := range m.lin_user { + ids = append(ids, id) + } + return ids + case lingroup.EdgeLinPermission: + ids := make([]ent.Value, 0, len(m.lin_permission)) + for id := range m.lin_permission { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedlin_user != nil { + edges = append(edges, lingroup.EdgeLinUser) + } + if m.removedlin_permission != nil { + edges = append(edges, lingroup.EdgeLinPermission) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case lingroup.EdgeLinUser: + ids := make([]ent.Value, 0, len(m.removedlin_user)) + for id := range m.removedlin_user { + ids = append(ids, id) + } + return ids + case lingroup.EdgeLinPermission: + ids := make([]ent.Value, 0, len(m.removedlin_permission)) + for id := range m.removedlin_permission { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedlin_user { + edges = append(edges, lingroup.EdgeLinUser) + } + if m.clearedlin_permission { + edges = append(edges, lingroup.EdgeLinPermission) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinGroupMutation) EdgeCleared(name string) bool { + switch name { + case lingroup.EdgeLinUser: + return m.clearedlin_user + case lingroup.EdgeLinPermission: + return m.clearedlin_permission + } + 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 *LinGroupMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LinGroup 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 *LinGroupMutation) ResetEdge(name string) error { + switch name { + case lingroup.EdgeLinUser: + m.ResetLinUser() + return nil + case lingroup.EdgeLinPermission: + m.ResetLinPermission() + return nil + } + return fmt.Errorf("unknown LinGroup edge %s", name) +} + +// LinLogMutation represents an operation that mutates the LinLog nodes in the graph. +type LinLogMutation struct { + config + op Op + typ string + id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time + message *string + user_id *int + adduser_id *int + username *string + status_code *int + addstatus_code *int + method *string + _path *string + permission *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinLog, error) + predicates []predicate.LinLog +} + +var _ ent.Mutation = (*LinLogMutation)(nil) + +// linlogOption allows management of the mutation configuration using functional options. +type linlogOption func(*LinLogMutation) + +// newLinLogMutation creates new mutation for the LinLog entity. +func newLinLogMutation(c config, op Op, opts ...linlogOption) *LinLogMutation { + m := &LinLogMutation{ + config: c, + op: op, + typ: TypeLinLog, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinLogID sets the ID field of the mutation. +func withLinLogID(id int) linlogOption { + return func(m *LinLogMutation) { + var ( + err error + once sync.Once + value *LinLog + ) + m.oldValue = func(ctx context.Context) (*LinLog, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinLog.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinLog sets the old LinLog of the mutation. +func withLinLog(node *LinLog) linlogOption { + return func(m *LinLogMutation) { + m.oldValue = func(context.Context) (*LinLog, 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 LinLogMutation) 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 LinLogMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinLogMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetCreateTime sets the "create_time" field. +func (m *LinLogMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *LinLogMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *LinLogMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *LinLogMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *LinLogMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *LinLogMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *LinLogMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *LinLogMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *LinLogMutation) ResetDeleteTime() { + m.delete_time = nil +} + +// SetMessage sets the "message" field. +func (m *LinLogMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *LinLogMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return + } + return *v, true +} + +// OldMessage returns the old "message" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil +} + +// ResetMessage resets all changes to the "message" field. +func (m *LinLogMutation) ResetMessage() { + m.message = nil +} + +// SetUserID sets the "user_id" field. +func (m *LinLogMutation) SetUserID(i int) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *LinLogMutation) UserID() (r int, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// AddUserID adds i to the "user_id" field. +func (m *LinLogMutation) AddUserID(i int) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *LinLogMutation) AddedUserID() (r int, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *LinLogMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetUsername sets the "username" field. +func (m *LinLogMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *LinLogMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *LinLogMutation) ResetUsername() { + m.username = nil +} + +// SetStatusCode sets the "status_code" field. +func (m *LinLogMutation) SetStatusCode(i int) { + m.status_code = &i + m.addstatus_code = nil +} + +// StatusCode returns the value of the "status_code" field in the mutation. +func (m *LinLogMutation) StatusCode() (r int, exists bool) { + v := m.status_code + if v == nil { + return + } + return *v, true +} + +// OldStatusCode returns the old "status_code" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldStatusCode(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldStatusCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldStatusCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatusCode: %w", err) + } + return oldValue.StatusCode, nil +} + +// AddStatusCode adds i to the "status_code" field. +func (m *LinLogMutation) AddStatusCode(i int) { + if m.addstatus_code != nil { + *m.addstatus_code += i + } else { + m.addstatus_code = &i + } +} + +// AddedStatusCode returns the value that was added to the "status_code" field in this mutation. +func (m *LinLogMutation) AddedStatusCode() (r int, exists bool) { + v := m.addstatus_code + if v == nil { + return + } + return *v, true +} + +// ResetStatusCode resets all changes to the "status_code" field. +func (m *LinLogMutation) ResetStatusCode() { + m.status_code = nil + m.addstatus_code = nil +} + +// SetMethod sets the "method" field. +func (m *LinLogMutation) SetMethod(s string) { + m.method = &s +} + +// Method returns the value of the "method" field in the mutation. +func (m *LinLogMutation) Method() (r string, exists bool) { + v := m.method + if v == nil { + return + } + return *v, true +} + +// OldMethod returns the old "method" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldMethod(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMethod is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMethod requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMethod: %w", err) + } + return oldValue.Method, nil +} + +// ResetMethod resets all changes to the "method" field. +func (m *LinLogMutation) ResetMethod() { + m.method = nil +} + +// SetPath sets the "path" field. +func (m *LinLogMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *LinLogMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *LinLogMutation) ResetPath() { + m._path = nil +} + +// SetPermission sets the "permission" field. +func (m *LinLogMutation) SetPermission(s string) { + m.permission = &s +} + +// Permission returns the value of the "permission" field in the mutation. +func (m *LinLogMutation) Permission() (r string, exists bool) { + v := m.permission + if v == nil { + return + } + return *v, true +} + +// OldPermission returns the old "permission" field's value of the LinLog entity. +// If the LinLog 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 *LinLogMutation) OldPermission(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldPermission is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldPermission requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPermission: %w", err) + } + return oldValue.Permission, nil +} + +// ResetPermission resets all changes to the "permission" field. +func (m *LinLogMutation) ResetPermission() { + m.permission = nil +} + +// Where appends a list predicates to the LinLogMutation builder. +func (m *LinLogMutation) Where(ps ...predicate.LinLog) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinLogMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinLog). +func (m *LinLogMutation) 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 *LinLogMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.create_time != nil { + fields = append(fields, linlog.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, linlog.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, linlog.FieldDeleteTime) + } + if m.message != nil { + fields = append(fields, linlog.FieldMessage) + } + if m.user_id != nil { + fields = append(fields, linlog.FieldUserID) + } + if m.username != nil { + fields = append(fields, linlog.FieldUsername) + } + if m.status_code != nil { + fields = append(fields, linlog.FieldStatusCode) + } + if m.method != nil { + fields = append(fields, linlog.FieldMethod) + } + if m._path != nil { + fields = append(fields, linlog.FieldPath) + } + if m.permission != nil { + fields = append(fields, linlog.FieldPermission) + } + 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 *LinLogMutation) Field(name string) (ent.Value, bool) { + switch name { + case linlog.FieldCreateTime: + return m.CreateTime() + case linlog.FieldUpdateTime: + return m.UpdateTime() + case linlog.FieldDeleteTime: + return m.DeleteTime() + case linlog.FieldMessage: + return m.Message() + case linlog.FieldUserID: + return m.UserID() + case linlog.FieldUsername: + return m.Username() + case linlog.FieldStatusCode: + return m.StatusCode() + case linlog.FieldMethod: + return m.Method() + case linlog.FieldPath: + return m.Path() + case linlog.FieldPermission: + return m.Permission() + } + 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 *LinLogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linlog.FieldCreateTime: + return m.OldCreateTime(ctx) + case linlog.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case linlog.FieldDeleteTime: + return m.OldDeleteTime(ctx) + case linlog.FieldMessage: + return m.OldMessage(ctx) + case linlog.FieldUserID: + return m.OldUserID(ctx) + case linlog.FieldUsername: + return m.OldUsername(ctx) + case linlog.FieldStatusCode: + return m.OldStatusCode(ctx) + case linlog.FieldMethod: + return m.OldMethod(ctx) + case linlog.FieldPath: + return m.OldPath(ctx) + case linlog.FieldPermission: + return m.OldPermission(ctx) + } + return nil, fmt.Errorf("unknown LinLog 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 *LinLogMutation) SetField(name string, value ent.Value) error { + switch name { + case linlog.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case linlog.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case linlog.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil + case linlog.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case linlog.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case linlog.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case linlog.FieldStatusCode: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatusCode(v) + return nil + case linlog.FieldMethod: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMethod(v) + return nil + case linlog.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case linlog.FieldPermission: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPermission(v) + return nil + } + return fmt.Errorf("unknown LinLog field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinLogMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, linlog.FieldUserID) + } + if m.addstatus_code != nil { + fields = append(fields, linlog.FieldStatusCode) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinLogMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linlog.FieldUserID: + return m.AddedUserID() + case linlog.FieldStatusCode: + return m.AddedStatusCode() + } + 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 *LinLogMutation) AddField(name string, value ent.Value) error { + switch name { + case linlog.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + case linlog.FieldStatusCode: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStatusCode(v) + return nil + } + return fmt.Errorf("unknown LinLog numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinLogMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinLogMutation) 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 *LinLogMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinLog 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 *LinLogMutation) ResetField(name string) error { + switch name { + case linlog.FieldCreateTime: + m.ResetCreateTime() + return nil + case linlog.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case linlog.FieldDeleteTime: + m.ResetDeleteTime() + return nil + case linlog.FieldMessage: + m.ResetMessage() + return nil + case linlog.FieldUserID: + m.ResetUserID() + return nil + case linlog.FieldUsername: + m.ResetUsername() + return nil + case linlog.FieldStatusCode: + m.ResetStatusCode() + return nil + case linlog.FieldMethod: + m.ResetMethod() + return nil + case linlog.FieldPath: + m.ResetPath() + return nil + case linlog.FieldPermission: + m.ResetPermission() + return nil + } + return fmt.Errorf("unknown LinLog field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinLogMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinLogMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinLogMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinLogMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinLogMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinLogMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinLogMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinLog 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 *LinLogMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinLog edge %s", name) +} + +// LinPermissionMutation represents an operation that mutates the LinPermission nodes in the graph. +type LinPermissionMutation struct { + config + op Op + typ string + id *int + name *string + module *string + mount *int8 + addmount *int8 + clearedFields map[string]struct{} + lin_group map[int]struct{} + removedlin_group map[int]struct{} + clearedlin_group bool + done bool + oldValue func(context.Context) (*LinPermission, error) + predicates []predicate.LinPermission +} + +var _ ent.Mutation = (*LinPermissionMutation)(nil) + +// linpermissionOption allows management of the mutation configuration using functional options. +type linpermissionOption func(*LinPermissionMutation) + +// newLinPermissionMutation creates new mutation for the LinPermission entity. +func newLinPermissionMutation(c config, op Op, opts ...linpermissionOption) *LinPermissionMutation { + m := &LinPermissionMutation{ + config: c, + op: op, + typ: TypeLinPermission, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinPermissionID sets the ID field of the mutation. +func withLinPermissionID(id int) linpermissionOption { + return func(m *LinPermissionMutation) { + var ( + err error + once sync.Once + value *LinPermission + ) + m.oldValue = func(ctx context.Context) (*LinPermission, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinPermission.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinPermission sets the old LinPermission of the mutation. +func withLinPermission(node *LinPermission) linpermissionOption { + return func(m *LinPermissionMutation) { + m.oldValue = func(context.Context) (*LinPermission, 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 LinPermissionMutation) 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 LinPermissionMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinPermissionMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetName sets the "name" field. +func (m *LinPermissionMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *LinPermissionMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the LinPermission entity. +// If the LinPermission 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 *LinPermissionMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *LinPermissionMutation) ResetName() { + m.name = nil +} + +// SetModule sets the "module" field. +func (m *LinPermissionMutation) SetModule(s string) { + m.module = &s +} + +// Module returns the value of the "module" field in the mutation. +func (m *LinPermissionMutation) Module() (r string, exists bool) { + v := m.module + if v == nil { + return + } + return *v, true +} + +// OldModule returns the old "module" field's value of the LinPermission entity. +// If the LinPermission 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 *LinPermissionMutation) OldModule(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldModule is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldModule requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModule: %w", err) + } + return oldValue.Module, nil +} + +// ResetModule resets all changes to the "module" field. +func (m *LinPermissionMutation) ResetModule() { + m.module = nil +} + +// SetMount sets the "mount" field. +func (m *LinPermissionMutation) SetMount(i int8) { + m.mount = &i + m.addmount = nil +} + +// Mount returns the value of the "mount" field in the mutation. +func (m *LinPermissionMutation) Mount() (r int8, exists bool) { + v := m.mount + if v == nil { + return + } + return *v, true +} + +// OldMount returns the old "mount" field's value of the LinPermission entity. +// If the LinPermission 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 *LinPermissionMutation) OldMount(ctx context.Context) (v int8, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldMount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldMount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMount: %w", err) + } + return oldValue.Mount, nil +} + +// AddMount adds i to the "mount" field. +func (m *LinPermissionMutation) AddMount(i int8) { + if m.addmount != nil { + *m.addmount += i + } else { + m.addmount = &i + } +} + +// AddedMount returns the value that was added to the "mount" field in this mutation. +func (m *LinPermissionMutation) AddedMount() (r int8, exists bool) { + v := m.addmount + if v == nil { + return + } + return *v, true +} + +// ResetMount resets all changes to the "mount" field. +func (m *LinPermissionMutation) ResetMount() { + m.mount = nil + m.addmount = nil +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by ids. +func (m *LinPermissionMutation) AddLinGroupIDs(ids ...int) { + if m.lin_group == nil { + m.lin_group = make(map[int]struct{}) + } + for i := range ids { + m.lin_group[ids[i]] = struct{}{} + } +} + +// ClearLinGroup clears the "lin_group" edge to the LinGroup entity. +func (m *LinPermissionMutation) ClearLinGroup() { + m.clearedlin_group = true +} + +// LinGroupCleared reports if the "lin_group" edge to the LinGroup entity was cleared. +func (m *LinPermissionMutation) LinGroupCleared() bool { + return m.clearedlin_group +} + +// RemoveLinGroupIDs removes the "lin_group" edge to the LinGroup entity by IDs. +func (m *LinPermissionMutation) RemoveLinGroupIDs(ids ...int) { + if m.removedlin_group == nil { + m.removedlin_group = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_group, ids[i]) + m.removedlin_group[ids[i]] = struct{}{} + } +} + +// RemovedLinGroup returns the removed IDs of the "lin_group" edge to the LinGroup entity. +func (m *LinPermissionMutation) RemovedLinGroupIDs() (ids []int) { + for id := range m.removedlin_group { + ids = append(ids, id) + } + return +} + +// LinGroupIDs returns the "lin_group" edge IDs in the mutation. +func (m *LinPermissionMutation) LinGroupIDs() (ids []int) { + for id := range m.lin_group { + ids = append(ids, id) + } + return +} + +// ResetLinGroup resets all changes to the "lin_group" edge. +func (m *LinPermissionMutation) ResetLinGroup() { + m.lin_group = nil + m.clearedlin_group = false + m.removedlin_group = nil +} + +// Where appends a list predicates to the LinPermissionMutation builder. +func (m *LinPermissionMutation) Where(ps ...predicate.LinPermission) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinPermissionMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinPermission). +func (m *LinPermissionMutation) 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 *LinPermissionMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, linpermission.FieldName) + } + if m.module != nil { + fields = append(fields, linpermission.FieldModule) + } + if m.mount != nil { + fields = append(fields, linpermission.FieldMount) + } + 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 *LinPermissionMutation) Field(name string) (ent.Value, bool) { + switch name { + case linpermission.FieldName: + return m.Name() + case linpermission.FieldModule: + return m.Module() + case linpermission.FieldMount: + return m.Mount() + } + 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 *LinPermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linpermission.FieldName: + return m.OldName(ctx) + case linpermission.FieldModule: + return m.OldModule(ctx) + case linpermission.FieldMount: + return m.OldMount(ctx) + } + return nil, fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) SetField(name string, value ent.Value) error { + switch name { + case linpermission.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case linpermission.FieldModule: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModule(v) + return nil + case linpermission.FieldMount: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMount(v) + return nil + } + return fmt.Errorf("unknown LinPermission field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinPermissionMutation) AddedFields() []string { + var fields []string + if m.addmount != nil { + fields = append(fields, linpermission.FieldMount) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinPermissionMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linpermission.FieldMount: + return m.AddedMount() + } + 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 *LinPermissionMutation) AddField(name string, value ent.Value) error { + switch name { + case linpermission.FieldMount: + v, ok := value.(int8) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMount(v) + return nil + } + return fmt.Errorf("unknown LinPermission numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinPermissionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinPermissionMutation) 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 *LinPermissionMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) ResetField(name string) error { + switch name { + case linpermission.FieldName: + m.ResetName() + return nil + case linpermission.FieldModule: + m.ResetModule() + return nil + case linpermission.FieldMount: + m.ResetMount() + return nil + } + return fmt.Errorf("unknown LinPermission field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinPermissionMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.lin_group != nil { + edges = append(edges, linpermission.EdgeLinGroup) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinPermissionMutation) AddedIDs(name string) []ent.Value { + switch name { + case linpermission.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.lin_group)) + for id := range m.lin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinPermissionMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedlin_group != nil { + edges = append(edges, linpermission.EdgeLinGroup) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinPermissionMutation) RemovedIDs(name string) []ent.Value { + switch name { + case linpermission.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.removedlin_group)) + for id := range m.removedlin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinPermissionMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedlin_group { + edges = append(edges, linpermission.EdgeLinGroup) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinPermissionMutation) EdgeCleared(name string) bool { + switch name { + case linpermission.EdgeLinGroup: + return m.clearedlin_group + } + 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 *LinPermissionMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LinPermission 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 *LinPermissionMutation) ResetEdge(name string) error { + switch name { + case linpermission.EdgeLinGroup: + m.ResetLinGroup() + return nil + } + return fmt.Errorf("unknown LinPermission edge %s", name) +} + +// LinUserMutation represents an operation that mutates the LinUser nodes in the graph. +type LinUserMutation struct { + config + op Op + typ string + id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time + username *string + nickname *string + avatar *string + email *string + clearedFields map[string]struct{} + lin_user_identiy map[int]struct{} + removedlin_user_identiy map[int]struct{} + clearedlin_user_identiy bool + lin_group map[int]struct{} + removedlin_group map[int]struct{} + clearedlin_group bool + done bool + oldValue func(context.Context) (*LinUser, error) + predicates []predicate.LinUser +} + +var _ ent.Mutation = (*LinUserMutation)(nil) + +// linuserOption allows management of the mutation configuration using functional options. +type linuserOption func(*LinUserMutation) + +// newLinUserMutation creates new mutation for the LinUser entity. +func newLinUserMutation(c config, op Op, opts ...linuserOption) *LinUserMutation { + m := &LinUserMutation{ + config: c, + op: op, + typ: TypeLinUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinUserID sets the ID field of the mutation. +func withLinUserID(id int) linuserOption { + return func(m *LinUserMutation) { + var ( + err error + once sync.Once + value *LinUser + ) + m.oldValue = func(ctx context.Context) (*LinUser, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinUser.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinUser sets the old LinUser of the mutation. +func withLinUser(node *LinUser) linuserOption { + return func(m *LinUserMutation) { + m.oldValue = func(context.Context) (*LinUser, 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 LinUserMutation) 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 LinUserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinUserMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetCreateTime sets the "create_time" field. +func (m *LinUserMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *LinUserMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *LinUserMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *LinUserMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *LinUserMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *LinUserMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *LinUserMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *LinUserMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *LinUserMutation) ResetDeleteTime() { + m.delete_time = nil +} + +// SetUsername sets the "username" field. +func (m *LinUserMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *LinUserMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *LinUserMutation) ResetUsername() { + m.username = nil +} + +// SetNickname sets the "nickname" field. +func (m *LinUserMutation) SetNickname(s string) { + m.nickname = &s +} + +// Nickname returns the value of the "nickname" field in the mutation. +func (m *LinUserMutation) 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 LinUser entity. +// If the LinUser 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 *LinUserMutation) OldNickname(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldNickname is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// ResetNickname resets all changes to the "nickname" field. +func (m *LinUserMutation) ResetNickname() { + m.nickname = nil +} + +// SetAvatar sets the "avatar" field. +func (m *LinUserMutation) SetAvatar(s string) { + m.avatar = &s +} + +// Avatar returns the value of the "avatar" field in the mutation. +func (m *LinUserMutation) Avatar() (r string, exists bool) { + v := m.avatar + if v == nil { + return + } + return *v, true +} + +// OldAvatar returns the old "avatar" field's value of the LinUser entity. +// If the LinUser 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 *LinUserMutation) OldAvatar(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldAvatar is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldAvatar requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAvatar: %w", err) + } + return oldValue.Avatar, nil +} + +// ResetAvatar resets all changes to the "avatar" field. +func (m *LinUserMutation) ResetAvatar() { + m.avatar = nil +} + +// SetEmail sets the "email" field. +func (m *LinUserMutation) SetEmail(s string) { + m.email = &s +} + +// Email returns the value of the "email" field in the mutation. +func (m *LinUserMutation) 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 LinUser entity. +// If the LinUser 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 *LinUserMutation) OldEmail(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldEmail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// ResetEmail resets all changes to the "email" field. +func (m *LinUserMutation) ResetEmail() { + m.email = nil +} + +// AddLinUserIdentiyIDs adds the "lin_user_identiy" edge to the LinUserIdentiy entity by ids. +func (m *LinUserMutation) AddLinUserIdentiyIDs(ids ...int) { + if m.lin_user_identiy == nil { + m.lin_user_identiy = make(map[int]struct{}) + } + for i := range ids { + m.lin_user_identiy[ids[i]] = struct{}{} + } +} + +// ClearLinUserIdentiy clears the "lin_user_identiy" edge to the LinUserIdentiy entity. +func (m *LinUserMutation) ClearLinUserIdentiy() { + m.clearedlin_user_identiy = true +} + +// LinUserIdentiyCleared reports if the "lin_user_identiy" edge to the LinUserIdentiy entity was cleared. +func (m *LinUserMutation) LinUserIdentiyCleared() bool { + return m.clearedlin_user_identiy +} + +// RemoveLinUserIdentiyIDs removes the "lin_user_identiy" edge to the LinUserIdentiy entity by IDs. +func (m *LinUserMutation) RemoveLinUserIdentiyIDs(ids ...int) { + if m.removedlin_user_identiy == nil { + m.removedlin_user_identiy = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_user_identiy, ids[i]) + m.removedlin_user_identiy[ids[i]] = struct{}{} + } +} + +// RemovedLinUserIdentiy returns the removed IDs of the "lin_user_identiy" edge to the LinUserIdentiy entity. +func (m *LinUserMutation) RemovedLinUserIdentiyIDs() (ids []int) { + for id := range m.removedlin_user_identiy { + ids = append(ids, id) + } + return +} + +// LinUserIdentiyIDs returns the "lin_user_identiy" edge IDs in the mutation. +func (m *LinUserMutation) LinUserIdentiyIDs() (ids []int) { + for id := range m.lin_user_identiy { + ids = append(ids, id) + } + return +} + +// ResetLinUserIdentiy resets all changes to the "lin_user_identiy" edge. +func (m *LinUserMutation) ResetLinUserIdentiy() { + m.lin_user_identiy = nil + m.clearedlin_user_identiy = false + m.removedlin_user_identiy = nil +} + +// AddLinGroupIDs adds the "lin_group" edge to the LinGroup entity by ids. +func (m *LinUserMutation) AddLinGroupIDs(ids ...int) { + if m.lin_group == nil { + m.lin_group = make(map[int]struct{}) + } + for i := range ids { + m.lin_group[ids[i]] = struct{}{} + } +} + +// ClearLinGroup clears the "lin_group" edge to the LinGroup entity. +func (m *LinUserMutation) ClearLinGroup() { + m.clearedlin_group = true +} + +// LinGroupCleared reports if the "lin_group" edge to the LinGroup entity was cleared. +func (m *LinUserMutation) LinGroupCleared() bool { + return m.clearedlin_group +} + +// RemoveLinGroupIDs removes the "lin_group" edge to the LinGroup entity by IDs. +func (m *LinUserMutation) RemoveLinGroupIDs(ids ...int) { + if m.removedlin_group == nil { + m.removedlin_group = make(map[int]struct{}) + } + for i := range ids { + delete(m.lin_group, ids[i]) + m.removedlin_group[ids[i]] = struct{}{} + } +} + +// RemovedLinGroup returns the removed IDs of the "lin_group" edge to the LinGroup entity. +func (m *LinUserMutation) RemovedLinGroupIDs() (ids []int) { + for id := range m.removedlin_group { + ids = append(ids, id) + } + return +} + +// LinGroupIDs returns the "lin_group" edge IDs in the mutation. +func (m *LinUserMutation) LinGroupIDs() (ids []int) { + for id := range m.lin_group { + ids = append(ids, id) + } + return +} + +// ResetLinGroup resets all changes to the "lin_group" edge. +func (m *LinUserMutation) ResetLinGroup() { + m.lin_group = nil + m.clearedlin_group = false + m.removedlin_group = nil +} + +// Where appends a list predicates to the LinUserMutation builder. +func (m *LinUserMutation) Where(ps ...predicate.LinUser) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinUserMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinUser). +func (m *LinUserMutation) 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 *LinUserMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.create_time != nil { + fields = append(fields, linuser.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, linuser.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, linuser.FieldDeleteTime) + } + if m.username != nil { + fields = append(fields, linuser.FieldUsername) + } + if m.nickname != nil { + fields = append(fields, linuser.FieldNickname) + } + if m.avatar != nil { + fields = append(fields, linuser.FieldAvatar) + } + if m.email != nil { + fields = append(fields, linuser.FieldEmail) + } + 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 *LinUserMutation) Field(name string) (ent.Value, bool) { + switch name { + case linuser.FieldCreateTime: + return m.CreateTime() + case linuser.FieldUpdateTime: + return m.UpdateTime() + case linuser.FieldDeleteTime: + return m.DeleteTime() + case linuser.FieldUsername: + return m.Username() + case linuser.FieldNickname: + return m.Nickname() + case linuser.FieldAvatar: + return m.Avatar() + case linuser.FieldEmail: + return m.Email() + } + 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 *LinUserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linuser.FieldCreateTime: + return m.OldCreateTime(ctx) + case linuser.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case linuser.FieldDeleteTime: + return m.OldDeleteTime(ctx) + case linuser.FieldUsername: + return m.OldUsername(ctx) + case linuser.FieldNickname: + return m.OldNickname(ctx) + case linuser.FieldAvatar: + return m.OldAvatar(ctx) + case linuser.FieldEmail: + return m.OldEmail(ctx) + } + return nil, fmt.Errorf("unknown LinUser 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 *LinUserMutation) SetField(name string, value ent.Value) error { + switch name { + case linuser.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case linuser.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case linuser.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil + case linuser.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case linuser.FieldNickname: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNickname(v) + return nil + case linuser.FieldAvatar: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatar(v) + return nil + case linuser.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + } + return fmt.Errorf("unknown LinUser field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinUserMutation) 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 *LinUserMutation) 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 *LinUserMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LinUser numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinUserMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinUserMutation) 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 *LinUserMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinUser 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 *LinUserMutation) ResetField(name string) error { + switch name { + case linuser.FieldCreateTime: + m.ResetCreateTime() + return nil + case linuser.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case linuser.FieldDeleteTime: + m.ResetDeleteTime() + return nil + case linuser.FieldUsername: + m.ResetUsername() + return nil + case linuser.FieldNickname: + m.ResetNickname() + return nil + case linuser.FieldAvatar: + m.ResetAvatar() + return nil + case linuser.FieldEmail: + m.ResetEmail() + return nil + } + return fmt.Errorf("unknown LinUser field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinUserMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.lin_user_identiy != nil { + edges = append(edges, linuser.EdgeLinUserIdentiy) + } + if m.lin_group != nil { + edges = append(edges, linuser.EdgeLinGroup) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinUserMutation) AddedIDs(name string) []ent.Value { + switch name { + case linuser.EdgeLinUserIdentiy: + ids := make([]ent.Value, 0, len(m.lin_user_identiy)) + for id := range m.lin_user_identiy { + ids = append(ids, id) + } + return ids + case linuser.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.lin_group)) + for id := range m.lin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinUserMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedlin_user_identiy != nil { + edges = append(edges, linuser.EdgeLinUserIdentiy) + } + if m.removedlin_group != nil { + edges = append(edges, linuser.EdgeLinGroup) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinUserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case linuser.EdgeLinUserIdentiy: + ids := make([]ent.Value, 0, len(m.removedlin_user_identiy)) + for id := range m.removedlin_user_identiy { + ids = append(ids, id) + } + return ids + case linuser.EdgeLinGroup: + ids := make([]ent.Value, 0, len(m.removedlin_group)) + for id := range m.removedlin_group { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinUserMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedlin_user_identiy { + edges = append(edges, linuser.EdgeLinUserIdentiy) + } + if m.clearedlin_group { + edges = append(edges, linuser.EdgeLinGroup) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinUserMutation) EdgeCleared(name string) bool { + switch name { + case linuser.EdgeLinUserIdentiy: + return m.clearedlin_user_identiy + case linuser.EdgeLinGroup: + return m.clearedlin_group + } + 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 *LinUserMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown LinUser 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 *LinUserMutation) ResetEdge(name string) error { + switch name { + case linuser.EdgeLinUserIdentiy: + m.ResetLinUserIdentiy() + return nil + case linuser.EdgeLinGroup: + m.ResetLinGroup() + return nil + } + return fmt.Errorf("unknown LinUser edge %s", name) +} + +// LinUserIdentiyMutation represents an operation that mutates the LinUserIdentiy nodes in the graph. +type LinUserIdentiyMutation struct { + config + op Op + typ string + id *int + user_id *int + adduser_id *int + identity_type *string + identifier *string + credential *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LinUserIdentiy, error) + predicates []predicate.LinUserIdentiy +} + +var _ ent.Mutation = (*LinUserIdentiyMutation)(nil) + +// linuseridentiyOption allows management of the mutation configuration using functional options. +type linuseridentiyOption func(*LinUserIdentiyMutation) + +// newLinUserIdentiyMutation creates new mutation for the LinUserIdentiy entity. +func newLinUserIdentiyMutation(c config, op Op, opts ...linuseridentiyOption) *LinUserIdentiyMutation { + m := &LinUserIdentiyMutation{ + config: c, + op: op, + typ: TypeLinUserIdentiy, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinUserIdentiyID sets the ID field of the mutation. +func withLinUserIdentiyID(id int) linuseridentiyOption { + return func(m *LinUserIdentiyMutation) { + var ( + err error + once sync.Once + value *LinUserIdentiy + ) + m.oldValue = func(ctx context.Context) (*LinUserIdentiy, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LinUserIdentiy.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLinUserIdentiy sets the old LinUserIdentiy of the mutation. +func withLinUserIdentiy(node *LinUserIdentiy) linuseridentiyOption { + return func(m *LinUserIdentiyMutation) { + m.oldValue = func(context.Context) (*LinUserIdentiy, 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 LinUserIdentiyMutation) 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 LinUserIdentiyMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("model: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *LinUserIdentiyMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetUserID sets the "user_id" field. +func (m *LinUserIdentiyMutation) SetUserID(i int) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *LinUserIdentiyMutation) UserID() (r int, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("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 +} + +// AddUserID adds i to the "user_id" field. +func (m *LinUserIdentiyMutation) AddUserID(i int) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *LinUserIdentiyMutation) AddedUserID() (r int, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *LinUserIdentiyMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetIdentityType sets the "identity_type" field. +func (m *LinUserIdentiyMutation) SetIdentityType(s string) { + m.identity_type = &s +} + +// IdentityType returns the value of the "identity_type" field in the mutation. +func (m *LinUserIdentiyMutation) IdentityType() (r string, exists bool) { + v := m.identity_type + if v == nil { + return + } + return *v, true +} + +// OldIdentityType returns the old "identity_type" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldIdentityType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldIdentityType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldIdentityType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIdentityType: %w", err) + } + return oldValue.IdentityType, nil +} + +// ResetIdentityType resets all changes to the "identity_type" field. +func (m *LinUserIdentiyMutation) ResetIdentityType() { + m.identity_type = nil +} + +// SetIdentifier sets the "identifier" field. +func (m *LinUserIdentiyMutation) SetIdentifier(s string) { + m.identifier = &s +} + +// Identifier returns the value of the "identifier" field in the mutation. +func (m *LinUserIdentiyMutation) Identifier() (r string, exists bool) { + v := m.identifier + if v == nil { + return + } + return *v, true +} + +// OldIdentifier returns the old "identifier" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldIdentifier(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldIdentifier is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldIdentifier requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIdentifier: %w", err) + } + return oldValue.Identifier, nil +} + +// ResetIdentifier resets all changes to the "identifier" field. +func (m *LinUserIdentiyMutation) ResetIdentifier() { + m.identifier = nil +} + +// SetCredential sets the "credential" field. +func (m *LinUserIdentiyMutation) SetCredential(s string) { + m.credential = &s +} + +// Credential returns the value of the "credential" field in the mutation. +func (m *LinUserIdentiyMutation) Credential() (r string, exists bool) { + v := m.credential + if v == nil { + return + } + return *v, true +} + +// OldCredential returns the old "credential" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldCredential(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCredential is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCredential requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCredential: %w", err) + } + return oldValue.Credential, nil +} + +// ResetCredential resets all changes to the "credential" field. +func (m *LinUserIdentiyMutation) ResetCredential() { + m.credential = nil +} + +// Where appends a list predicates to the LinUserIdentiyMutation builder. +func (m *LinUserIdentiyMutation) Where(ps ...predicate.LinUserIdentiy) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *LinUserIdentiyMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (LinUserIdentiy). +func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.user_id != nil { + fields = append(fields, linuseridentiy.FieldUserID) + } + if m.identity_type != nil { + fields = append(fields, linuseridentiy.FieldIdentityType) + } + if m.identifier != nil { + fields = append(fields, linuseridentiy.FieldIdentifier) + } + if m.credential != nil { + fields = append(fields, linuseridentiy.FieldCredential) + } + 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 *LinUserIdentiyMutation) Field(name string) (ent.Value, bool) { + switch name { + case linuseridentiy.FieldUserID: + return m.UserID() + case linuseridentiy.FieldIdentityType: + return m.IdentityType() + case linuseridentiy.FieldIdentifier: + return m.Identifier() + case linuseridentiy.FieldCredential: + return m.Credential() + } + 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 *LinUserIdentiyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case linuseridentiy.FieldUserID: + return m.OldUserID(ctx) + case linuseridentiy.FieldIdentityType: + return m.OldIdentityType(ctx) + case linuseridentiy.FieldIdentifier: + return m.OldIdentifier(ctx) + case linuseridentiy.FieldCredential: + return m.OldCredential(ctx) + } + return nil, fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) SetField(name string, value ent.Value) error { + switch name { + case linuseridentiy.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case linuseridentiy.FieldIdentityType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentityType(v) + return nil + case linuseridentiy.FieldIdentifier: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentifier(v) + return nil + case linuseridentiy.FieldCredential: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCredential(v) + return nil + } + return fmt.Errorf("unknown LinUserIdentiy field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinUserIdentiyMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, linuseridentiy.FieldUserID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LinUserIdentiyMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case linuseridentiy.FieldUserID: + return m.AddedUserID() + } + 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 *LinUserIdentiyMutation) AddField(name string, value ent.Value) error { + switch name { + case linuseridentiy.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + } + return fmt.Errorf("unknown LinUserIdentiy numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinUserIdentiyMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) ClearField(name string) error { + return fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) ResetField(name string) error { + switch name { + case linuseridentiy.FieldUserID: + m.ResetUserID() + return nil + case linuseridentiy.FieldIdentityType: + m.ResetIdentityType() + return nil + case linuseridentiy.FieldIdentifier: + m.ResetIdentifier() + return nil + case linuseridentiy.FieldCredential: + m.ResetCredential() + return nil + } + return fmt.Errorf("unknown LinUserIdentiy field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinUserIdentiyMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinUserIdentiyMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinUserIdentiyMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinUserIdentiyMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinUserIdentiyMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinUserIdentiyMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LinUserIdentiyMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LinUserIdentiy 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 *LinUserIdentiyMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LinUserIdentiy edge %s", name) +} diff --git a/internal/data/model/predicate/predicate.go b/internal/data/model/predicate/predicate.go new file mode 100644 index 0000000..f4db95b --- /dev/null +++ b/internal/data/model/predicate/predicate.go @@ -0,0 +1,28 @@ +// Code generated by entc, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Book is the predicate function for book builders. +type Book func(*sql.Selector) + +// LinFile is the predicate function for linfile builders. +type LinFile func(*sql.Selector) + +// LinGroup is the predicate function for lingroup builders. +type LinGroup func(*sql.Selector) + +// LinLog is the predicate function for linlog builders. +type LinLog func(*sql.Selector) + +// LinPermission is the predicate function for linpermission builders. +type LinPermission func(*sql.Selector) + +// LinUser is the predicate function for linuser builders. +type LinUser func(*sql.Selector) + +// LinUserIdentiy is the predicate function for linuseridentiy builders. +type LinUserIdentiy func(*sql.Selector) diff --git a/internal/data/model/runtime.go b/internal/data/model/runtime.go new file mode 100644 index 0000000..345205e --- /dev/null +++ b/internal/data/model/runtime.go @@ -0,0 +1,58 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "lin-cms-go/internal/data/ent/schema" + "lin-cms-go/internal/data/model/linlog" + "lin-cms-go/internal/data/model/linuser" + "time" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + linlogMixin := schema.LinLog{}.Mixin() + linlogMixinFields0 := linlogMixin[0].Fields() + _ = linlogMixinFields0 + linlogFields := schema.LinLog{}.Fields() + _ = linlogFields + // linlogDescCreateTime is the schema descriptor for create_time field. + linlogDescCreateTime := linlogMixinFields0[0].Descriptor() + // linlog.DefaultCreateTime holds the default value on creation for the create_time field. + linlog.DefaultCreateTime = linlogDescCreateTime.Default.(func() time.Time) + // linlogDescUpdateTime is the schema descriptor for update_time field. + linlogDescUpdateTime := linlogMixinFields0[1].Descriptor() + // linlog.DefaultUpdateTime holds the default value on creation for the update_time field. + linlog.DefaultUpdateTime = linlogDescUpdateTime.Default.(func() time.Time) + // linlog.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + linlog.UpdateDefaultUpdateTime = linlogDescUpdateTime.UpdateDefault.(func() time.Time) + // linlogDescDeleteTime is the schema descriptor for delete_time field. + linlogDescDeleteTime := linlogMixinFields0[2].Descriptor() + // linlog.DefaultDeleteTime holds the default value on creation for the delete_time field. + linlog.DefaultDeleteTime = linlogDescDeleteTime.Default.(func() time.Time) + linuserMixin := schema.LinUser{}.Mixin() + linuserMixinFields0 := linuserMixin[0].Fields() + _ = linuserMixinFields0 + linuserFields := schema.LinUser{}.Fields() + _ = linuserFields + // linuserDescCreateTime is the schema descriptor for create_time field. + linuserDescCreateTime := linuserMixinFields0[0].Descriptor() + // linuser.DefaultCreateTime holds the default value on creation for the create_time field. + linuser.DefaultCreateTime = linuserDescCreateTime.Default.(func() time.Time) + // linuserDescUpdateTime is the schema descriptor for update_time field. + linuserDescUpdateTime := linuserMixinFields0[1].Descriptor() + // linuser.DefaultUpdateTime holds the default value on creation for the update_time field. + linuser.DefaultUpdateTime = linuserDescUpdateTime.Default.(func() time.Time) + // linuser.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + linuser.UpdateDefaultUpdateTime = linuserDescUpdateTime.UpdateDefault.(func() time.Time) + // linuserDescDeleteTime is the schema descriptor for delete_time field. + linuserDescDeleteTime := linuserMixinFields0[2].Descriptor() + // linuser.DefaultDeleteTime holds the default value on creation for the delete_time field. + linuser.DefaultDeleteTime = linuserDescDeleteTime.Default.(func() time.Time) + // linuserDescAvatar is the schema descriptor for avatar field. + linuserDescAvatar := linuserFields[2].Descriptor() + // linuser.DefaultAvatar holds the default value on creation for the avatar field. + linuser.DefaultAvatar = linuserDescAvatar.Default.(string) +} diff --git a/internal/data/model/runtime/runtime.go b/internal/data/model/runtime/runtime.go new file mode 100644 index 0000000..73d2fd8 --- /dev/null +++ b/internal/data/model/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by entc, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in lin-cms-go/internal/data/model/runtime.go + +const ( + Version = "v0.9.1" // Version of ent codegen. + Sum = "h1:IG8andyeD79GG24U8Q+1Y45hQXj6gY5evSBcva5gtBk=" // Sum of ent codegen. +) diff --git a/internal/data/model/tx.go b/internal/data/model/tx.go new file mode 100644 index 0000000..e9dbdce --- /dev/null +++ b/internal/data/model/tx.go @@ -0,0 +1,228 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Book is the client for interacting with the Book builders. + Book *BookClient + // LinFile is the client for interacting with the LinFile builders. + LinFile *LinFileClient + // LinGroup is the client for interacting with the LinGroup builders. + LinGroup *LinGroupClient + // LinLog is the client for interacting with the LinLog builders. + LinLog *LinLogClient + // LinPermission is the client for interacting with the LinPermission builders. + LinPermission *LinPermissionClient + // LinUser is the client for interacting with the LinUser builders. + LinUser *LinUserClient + // LinUserIdentiy is the client for interacting with the LinUserIdentiy builders. + LinUserIdentiy *LinUserIdentiyClient + + // lazily loaded. + client *Client + clientOnce sync.Once + + // completion callbacks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook + + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Committer method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + tx.mu.Lock() + hooks := append([]CommitHook(nil), tx.onCommit...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onCommit = append(tx.onCommit, f) +} + +type ( + // Rollbacker is the interface that wraps the Rollbacker method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + tx.mu.Lock() + hooks := append([]RollbackHook(nil), tx.onRollback...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onRollback = append(tx.onRollback, f) +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Book = NewBookClient(tx.config) + tx.LinFile = NewLinFileClient(tx.config) + tx.LinGroup = NewLinGroupClient(tx.config) + tx.LinLog = NewLinLogClient(tx.config) + tx.LinPermission = NewLinPermissionClient(tx.config) + tx.LinUser = NewLinUserClient(tx.config) + tx.LinUserIdentiy = NewLinUserIdentiyClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Book.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) From 43c25815de77170efab044cbdba5d0211761ef72 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 8 Nov 2021 16:19:07 +0800 Subject: [PATCH 30/44] feat: get all lin_permission --- api/permission.go | 4 ++-- docs/rest.http | 15 ++++++++++++ internal/biz/log.go | 15 +++++------- internal/biz/permission.go | 21 +++++++++++++++-- internal/data/groupPermission.go | 40 +++++++++++++++++++------------- 5 files changed, 66 insertions(+), 29 deletions(-) diff --git a/api/permission.go b/api/permission.go index 1db1b9b..e20ef17 100644 --- a/api/permission.go +++ b/api/permission.go @@ -8,7 +8,7 @@ import ( ) func GetAllPermissions(c *fiber.Ctx) error { - data, err := biz.GetAllPermissions() + data, err := biz.GetAllPermissions(c.Context()) if err != nil { return err @@ -42,7 +42,7 @@ func RemovePermissions(c *fiber.Ctx) error { return err } - err := biz.RemovePermissions(req) + err := biz.RemovePermissions(c.Context(), req.GroupId, req.PermissionIds) if err != nil { return err diff --git a/docs/rest.http b/docs/rest.http index 723d419..2bef517 100644 --- a/docs/rest.http +++ b/docs/rest.http @@ -19,6 +19,21 @@ Content-Type: application/json "password": "123456" } +### +GET http://localhost:3000/cms/admin/permissions +Content-Type: application/json +Authorization: Bearer {{token}} + +### +POST http://localhost:3000/cms/admin/permissions/remove +Content-Type: application/json +Authorization: Bearer {{token}} + +{ + "group_id": 1, + "permission_ids": [1,2] +} + ### POST http://localhost:3000/cms/admin/permissions/dispatch Content-Type: application/json diff --git a/internal/biz/log.go b/internal/biz/log.go index eb28b18..f416522 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -8,21 +8,19 @@ import ( "lin-cms-go/internal/data/model/predicate" "lin-cms-go/internal/request" "lin-cms-go/pkg/utils" - "time" ) func GetLogs(ctx context.Context, req request.GetLogs, page int, size int) (res interface{}, total int, err error) { var logs []*model.LinLog - var start time.Time - var end time.Time + paging := data.NewPaging(page, size) var query []predicate.LinLog if req.Name != "" { query = append(query, data.WithUsername(req.Name)) } if req.Start != "" && req.End != "" { - start = utils.String2time(req.Start) - end = utils.String2time(req.End) + start := utils.String2time(req.Start) + end := utils.String2time(req.End) q := linlog.And(linlog.CreateTimeGT(start), linlog.CreateTimeLT(end)) query = append(query, q) } @@ -37,16 +35,15 @@ func GetLogs(ctx context.Context, req request.GetLogs, page int, size int) (res func SearchLogs(ctx context.Context, req request.SearchLogs, page int, size int) (res interface{}, total int, err error) { var logs []*model.LinLog - var start time.Time - var end time.Time + paging := data.NewPaging(page, size) var query []predicate.LinLog if req.Name != "" { query = append(query, data.WithUsername(req.Name)) } if req.Start != "" && req.End != "" { - start = utils.String2time(req.Start) - end = utils.String2time(req.End) + start := utils.String2time(req.Start) + end := utils.String2time(req.End) q := linlog.And(linlog.CreateTimeGT(start), linlog.CreateTimeLT(end)) query = append(query, q) } diff --git a/internal/biz/permission.go b/internal/biz/permission.go index 6307316..274feb2 100644 --- a/internal/biz/permission.go +++ b/internal/biz/permission.go @@ -3,10 +3,21 @@ package biz import ( "context" "lin-cms-go/internal/data" + "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" ) -func GetAllPermissions() (data map[string]interface{}, err error) { +func GetAllPermissions(ctx context.Context) (res interface{}, err error) { + list, err := data.ListAllPermissions(ctx) + if err != nil { + return + } + m := make(map[string][]model.LinPermission) + for _, v := range list { + + m[v.Module] = append(m[v.Module], *v) + } + res = m return } @@ -16,8 +27,14 @@ func DispatchPermission(req request.DispatchPermission) (err error) { func DispatchPermissions(ctx context.Context, groupId int, permissionIds []int) (err error) { err = data.BatchCreateGroupPermission(ctx, groupId, permissionIds) + return } -func RemovePermissions(req request.RemovePermissions) (err error) { +func RemovePermissions(ctx context.Context, groupId int, permissionIds []int) (err error) { + _, err = data.GetGroupPermissionByGroupId(ctx, groupId) + if err != nil { + return + } + err = data.DeleteGroupPermission(ctx, groupId, permissionIds) return } diff --git a/internal/data/groupPermission.go b/internal/data/groupPermission.go index a83f385..db724af 100644 --- a/internal/data/groupPermission.go +++ b/internal/data/groupPermission.go @@ -2,29 +2,37 @@ package data import ( "context" + "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/lingroup" ) +func ListAllPermissions(ctx context.Context) (list []*model.LinPermission, err error) { + list, err = GetDB().LinPermission.Query().All(ctx) + return +} func BatchCreateGroupPermission(ctx context.Context, groupId int, permissionId []int) (err error) { _, err = GetDB().LinGroup.Update().Where(lingroup.ID(groupId)).AddLinPermissionIDs(permissionId...).Save(ctx) return } -//func GetGroupPermissionByGroupId(ctx context.Context, groupId int) (groupPermission []*model.LinGroupPermission, err error) { -// groupPermission, err = GetDB().LinGroupPermission.Query().Where(lingrouppermission.GroupID(groupId)).All(ctx) -// return -//} +func GetGroupPermissionByGroupId(ctx context.Context, groupId int) (groupPermission *model.LinGroup, err error) { + groupPermission, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).WithLinPermission().First(ctx) + return +} + +func DeleteGroupPermission(ctx context.Context, groupId int, permissionId []int) (err error) { + //TODO 删除前判断数据是否存在放biz,不然error不好处理,职责不清晰,有可能别人调用的时候又查一次,从命名上看这个方法就是做删除,不用里面加其他操作 + //group, err := GetGroupPermissionByGroupId(ctx, groupId) + //if err != nil { + // return err + //} -//func DeleteGroupPermission(ctx context.Context, groupId int) (err error) { -// groupPermission, err := GetGroupPermissionByGroupId(ctx, groupId) -// if err != nil { -// return err -// } -// if len(groupPermission) == 0 { -// return nil -// } -// -// _, err = GetDB().LinGroupPermission.Delete().Where(lingrouppermission.GroupIDEQ(groupId)).Exec(ctx) -// return -//} + _, err = GetDB().LinGroup.Update().Where(lingroup.ID(groupId)).RemoveLinPermissionIDs(permissionId...).Save(ctx) + //_, err = GetDB().LinGroupPermission.Delete().Where(lingrouppermission.GroupIDEQ(groupId)).Exec(ctx) + return +} +func ClearLinPermission(ctx context.Context, groupId int) (err error) { + _, err = GetDB().LinGroup.Update().Where(lingroup.ID(groupId)).ClearLinPermission().Save(ctx) + return +} From b9fbf4c5cc63d8f001bf8e36aa31fb0cbee88609 Mon Sep 17 00:00:00 2001 From: LiYuanits Date: Mon, 8 Nov 2021 16:54:35 +0800 Subject: [PATCH 31/44] feat:group --- api/group.go | 37 ++++++++------- internal/biz/group.go | 100 +++++++++++++++++++++++++++++++++++------ pkg/errcode/message.go | 35 ++++++++++----- 3 files changed, 132 insertions(+), 40 deletions(-) diff --git a/api/group.go b/api/group.go index 4e30e1e..783cdc9 100644 --- a/api/group.go +++ b/api/group.go @@ -9,55 +9,62 @@ import ( ) func GetGroups(c *fiber.Ctx) error { - data, err := biz.GetGroups() + data, err := biz.GetGroups(c.Context()) if err != nil { - return err } return core.SetData(c, data) - } + func GetGroup(c *fiber.Ctx) error { id, err := utils.StringToInt(c.Params("id")) if err != nil { - return err } - data, err := biz.GetGroup(id) + data, err := biz.GetGroup(c.Context(), id) if err != nil { return err } return core.SetData(c, data) - } + func CreateGroup(c *fiber.Ctx) error { var req request.CreateGroup if err := core.ParseRequest(c, &req); err != nil { return err } - - err := biz.CreateGroup(req.Name, req.Info) - return err + err := biz.CreateGroup(c.Context(), req.Name, req.Info, req.PermissionIds) + if err != nil { + return err + } + return core.SuccessResp(c) } + func UpdateGroup(c *fiber.Ctx) error { var req request.UpdateGroup if err := core.ParseRequest(c, &req); err != nil { return err } + id, err := utils.StringToInt(c.Params("id")) + if err != nil { + return err + } - err := biz.UpdateGroup(req) - - return err + err = biz.UpdateGroup(c.Context(), id, req) + if err != nil { + return err + } + return core.SuccessResp(c) } func DeleteGroup(c *fiber.Ctx) error { id, err := utils.StringToInt(c.Params("id")) if err != nil { - return err } - err = biz.DeleteGroup(id) - if err != nil { + // TODO 删除分组功能还没写完 + err = biz.DeleteGroup(c.Context(), id) + if err != nil { return err } return core.SuccessResp(c) diff --git a/internal/biz/group.go b/internal/biz/group.go index 1c857bf..c57fc1d 100644 --- a/internal/biz/group.go +++ b/internal/biz/group.go @@ -1,30 +1,104 @@ package biz import ( + "context" + "lin-cms-go/internal/data" + "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" + "lin-cms-go/pkg/core" + "lin-cms-go/pkg/enum" + "lin-cms-go/pkg/errcode" ) -func GetGroups() (data map[string]interface{}, err error) { +type Group struct { + Id int `json:"id"` + Name string `json:"name"` + Info string `json:"info"` + Level int8 `json:"level"` +} + +func GetGroups(ctx context.Context) (res interface{}, err error) { + var linGroupModel []*model.LinGroup + linGroupModel, err = data.GetAllGroup(ctx) + res = simplifyGroup(linGroupModel) return } -func GetGroup(id int) (data map[string]interface{}, err error) { - //groupModel,e := model.GetLinGroupById(id) - //if e != nil { - // return - //} + +func GetGroup(ctx context.Context, id int) (res interface{}, err error) { + var linGroupModel *model.LinGroup + linGroupModel, err = data.GetLinGroupById(ctx, id, enum.ROOT) + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.GroupNotFound) + return + } + res = Group{Id: linGroupModel.ID, Name: linGroupModel.Name, Info: linGroupModel.Info, Level: linGroupModel.Level} return } -func CreateGroup(name, info string) (err error) { - //groupModel := model.Group{ - // Name: name, - // Info:info, - //} +func simplifyGroup(groupModel []*model.LinGroup) []Group { + res := make([]Group, 0, len(groupModel)) + for _, v := range groupModel { + res = append(res, Group{Id: v.ID, Name: v.Name, Info: v.Info, Level: v.Level}) + } + return res +} + +func CreateGroup(ctx context.Context, name string, info string, permissionIds []int) (err error) { + group, _ := data.GetLinGroupByName(ctx, name) + if group != nil { + err = core.NewErrorCode(errcode.GroupFound) + return + } + for _, v := range permissionIds { + _, err = data.GetLinPermissionById(ctx, v) + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.PermissionNotFound) + return + } + } + groupModel, err := data.CreateGroup(ctx, name, info, enum.USER) + if err != nil { + return + } + + err = data.BatchCreateGroupPermission(ctx, groupModel.ID, permissionIds) + if err != nil { + return + } return } -func UpdateGroup(req request.UpdateGroup) (err error) { + +func UpdateGroup(ctx context.Context, id int, req request.UpdateGroup) (err error) { + _, err = data.GetLinGroupById(ctx, id, enum.ROOT) + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.GroupNotFound) + return + } + err = data.UpdateGroup(ctx, id, req.Name, req.Info) return } -func DeleteGroup(id int) (err error) { + +func DeleteGroup(ctx context.Context, id int) (err error) { + var linGroup *model.LinGroup + linGroup, err = data.GetLinGroupById(ctx, id, enum.ROOT) + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.GroupNotFound) + return + } + if err != nil { + return + } + if linGroup.Level == enum.ROOT { + err = core.NewErrorCode(errcode.RootGroupNotAllowDelete) + } + + if linGroup.Level == enum.GUEST { + err = core.NewErrorCode(errcode.GuestGroupNotAllowDelete) + } + + //err = data.DeleteGroupPermission(ctx, id) + + // lin_group删除这个表的 lin_group_permission 删除这个表数据 lin_user_group 删除这个表的数据 + return } diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index 0d5ff74..2e155ab 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -14,21 +14,32 @@ const ( UserNotFound BookNotFound BookTitleRepetition + GroupNotFound + GroupFound + RootGroupNotAllowDelete + GuestGroupNotAllowDelete + + PermissionNotFound ) var MsgFlags = map[int]string{ - SUCCESS: "ok", - InvalidParams: "请求参数错误", - DBError: "数据库错误", - ServerError: "系统异常,请联系管理员!", - AuthCheckTokenFail: "Token鉴权失败", - AuthCheckTokenTimeout: "Token已超时", - ErrorAuthToken: "Token错误", - ErrorPassWord: "密码错误", - UserFound: "用户已存在", - UserNotFound: "用户不存在", - BookNotFound: "书籍不存在", - BookTitleRepetition: "书籍标题重复", + SUCCESS: "ok", + InvalidParams: "请求参数错误", + DBError: "数据库错误", + ServerError: "系统异常,请联系管理员!", + AuthCheckTokenFail: "Token鉴权失败", + AuthCheckTokenTimeout: "Token已超时", + ErrorAuthToken: "Token错误", + ErrorPassWord: "密码错误", + UserFound: "用户已存在", + UserNotFound: "用户不存在", + BookNotFound: "书籍不存在", + BookTitleRepetition: "书籍标题重复", + GroupNotFound: "分组不存在", + RootGroupNotAllowDelete: "root分组不允许删除", + GuestGroupNotAllowDelete: "guest分组不允许删除", + GroupFound: "分组已存在", + PermissionNotFound: "权限不存在", } func GetMsg(code int) string { From d74a2b8d7e9f2f2cd64ca3b59f55ee0758fd3743 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 8 Nov 2021 17:52:30 +0800 Subject: [PATCH 32/44] fix: delete group --- api/group.go | 1 - docs/rest.http | 6 +- go.mod | 1 + internal/biz/group.go | 12 +- internal/data/ent/schema/lin_group.go | 7 +- internal/data/ent/schema/lin_user_identiy.go | 10 +- internal/data/group.go | 12 +- internal/data/init.go | 25 ++ internal/data/model/lingroup.go | 33 ++ internal/data/model/lingroup/lingroup.go | 26 +- internal/data/model/lingroup/where.go | 250 +++++++++++++ internal/data/model/lingroup_create.go | 94 +++++ internal/data/model/lingroup_query.go | 8 +- internal/data/model/lingroup_update.go | 87 +++++ internal/data/model/linuser/linuser.go | 2 +- internal/data/model/linuseridentiy.go | 33 ++ .../model/linuseridentiy/linuseridentiy.go | 24 ++ internal/data/model/linuseridentiy/where.go | 250 +++++++++++++ internal/data/model/linuseridentiy_create.go | 94 +++++ internal/data/model/linuseridentiy_query.go | 8 +- internal/data/model/linuseridentiy_update.go | 87 +++++ internal/data/model/migrate/schema.go | 14 +- internal/data/model/mutation.go | 328 +++++++++++++++++- internal/data/model/runtime.go | 40 +++ pkg/core/response.go | 16 +- 25 files changed, 1425 insertions(+), 43 deletions(-) diff --git a/api/group.go b/api/group.go index 783cdc9..86c862e 100644 --- a/api/group.go +++ b/api/group.go @@ -62,7 +62,6 @@ func DeleteGroup(c *fiber.Ctx) error { return err } - // TODO 删除分组功能还没写完 err = biz.DeleteGroup(c.Context(), id) if err != nil { return err diff --git a/docs/rest.http b/docs/rest.http index 2bef517..6069bc3 100644 --- a/docs/rest.http +++ b/docs/rest.http @@ -46,4 +46,8 @@ Authorization: Bearer {{token}} ### GET http://localhost:3000/cms/user/permissions Content-Type: application/json -Authorization: Bearer {{token}} \ No newline at end of file +Authorization: Bearer {{token}} +### +DELETE http://localhost:3000/cms/admin/group/1 +Content-Type: application/json +Authorization: Bearer {{token}} diff --git a/go.mod b/go.mod index 498ee5d..d6c4ed3 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/gofiber/jwt/v3 v3.1.2 github.com/golang-jwt/jwt/v4 v4.1.0 github.com/grestful/logs v1.0.7 + github.com/pkg/errors v0.8.1 github.com/stretchr/testify v1.7.0 golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a gopkg.in/yaml.v2 v2.4.0 diff --git a/internal/biz/group.go b/internal/biz/group.go index c57fc1d..114edfd 100644 --- a/internal/biz/group.go +++ b/internal/biz/group.go @@ -26,7 +26,7 @@ func GetGroups(ctx context.Context) (res interface{}, err error) { func GetGroup(ctx context.Context, id int) (res interface{}, err error) { var linGroupModel *model.LinGroup - linGroupModel, err = data.GetLinGroupById(ctx, id, enum.ROOT) + linGroupModel, err = data.GetLinGroupById(ctx, id) if model.IsNotFound(err) { err = core.NewErrorCode(errcode.GroupNotFound) return @@ -69,7 +69,7 @@ func CreateGroup(ctx context.Context, name string, info string, permissionIds [] } func UpdateGroup(ctx context.Context, id int, req request.UpdateGroup) (err error) { - _, err = data.GetLinGroupById(ctx, id, enum.ROOT) + _, err = data.GetLinGroupById(ctx, id) if model.IsNotFound(err) { err = core.NewErrorCode(errcode.GroupNotFound) return @@ -80,7 +80,7 @@ func UpdateGroup(ctx context.Context, id int, req request.UpdateGroup) (err erro func DeleteGroup(ctx context.Context, id int) (err error) { var linGroup *model.LinGroup - linGroup, err = data.GetLinGroupById(ctx, id, enum.ROOT) + linGroup, err = data.GetLinGroupById(ctx, id) if model.IsNotFound(err) { err = core.NewErrorCode(errcode.GroupNotFound) return @@ -90,15 +90,15 @@ func DeleteGroup(ctx context.Context, id int) (err error) { } if linGroup.Level == enum.ROOT { err = core.NewErrorCode(errcode.RootGroupNotAllowDelete) + return } if linGroup.Level == enum.GUEST { err = core.NewErrorCode(errcode.GuestGroupNotAllowDelete) + return } - //err = data.DeleteGroupPermission(ctx, id) - - // lin_group删除这个表的 lin_group_permission 删除这个表数据 lin_user_group 删除这个表的数据 + err = data.DeleteGroup(ctx, id) return } diff --git a/internal/data/ent/schema/lin_group.go b/internal/data/ent/schema/lin_group.go index 3b08d01..52a696f 100644 --- a/internal/data/ent/schema/lin_group.go +++ b/internal/data/ent/schema/lin_group.go @@ -27,8 +27,13 @@ func (LinGroup) Fields() []ent.Field { func (LinGroup) Edges() []ent.Edge { return []ent.Edge{ edge.To("lin_user", LinUser.Type).StorageKey( - edge.Table("lin_user_group"), edge.Columns("user_id", "group_id"), + edge.Table("lin_user_group"), edge.Columns("group_id", "user_id"), ), edge.From("lin_permission", LinPermission.Type).Ref("lin_group"), } } +func (LinGroup) Mixin() []ent.Mixin { + return []ent.Mixin{ + TimeMixin{}, + } +} diff --git a/internal/data/ent/schema/lin_user_identiy.go b/internal/data/ent/schema/lin_user_identiy.go index 4d15cd9..43ef3da 100644 --- a/internal/data/ent/schema/lin_user_identiy.go +++ b/internal/data/ent/schema/lin_user_identiy.go @@ -25,8 +25,8 @@ func (LinUserIdentiy) Fields() []ent.Field { } } -//func (LinUserIdentiy) Mixin() []ent.Mixin { -// return []ent.Mixin{ -// mixin.Time{}, -// } -//} +func (LinUserIdentiy) Mixin() []ent.Mixin { + return []ent.Mixin{ + TimeMixin{}, + } +} diff --git a/internal/data/group.go b/internal/data/group.go index e2580fd..4d5697a 100644 --- a/internal/data/group.go +++ b/internal/data/group.go @@ -5,6 +5,7 @@ import ( "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/lingroup" "lin-cms-go/pkg/enum" + "time" ) func GetAllGroup(ctx context.Context) (groups []*model.LinGroup, err error) { @@ -12,13 +13,13 @@ func GetAllGroup(ctx context.Context) (groups []*model.LinGroup, err error) { return } -func GetLinGroupById(ctx context.Context, groupId int, level int8) (group *model.LinGroup, err error) { - group, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).Where(lingroup.And(lingroup.LevelGT(level))).First(ctx) +func GetLinGroupById(ctx context.Context, groupId int) (group *model.LinGroup, err error) { + group, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).First(ctx) return } func GetRootLinGroup(ctx context.Context, groupId int) (group *model.LinGroup, err error) { - group, err = GetLinGroupById(ctx, groupId, enum.ROOT) + group, err = GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).Where(lingroup.And(lingroup.LevelGT(enum.ROOT))).First(ctx) return } func GetLinGroupByName(ctx context.Context, name string) (group *model.LinGroup, err error) { @@ -39,9 +40,10 @@ func UpdateGroup(ctx context.Context, id int, name string, info string) (err err return } -// TODO update delete_time +// update delete_time func DeleteGroup(ctx context.Context, id int) (err error) { + _, err = GetDB().LinGroup.Update().SetDeleteTime(time.Now()).ClearLinPermission().ClearLinUser().Where(lingroup.ID(id)).Save(ctx) - return nil + return err } diff --git a/internal/data/init.go b/internal/data/init.go index 3b0fa9e..b6f3c0d 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -1,6 +1,8 @@ package data import ( + "context" + "github.com/pkg/errors" "lin-cms-go/internal/conf" "lin-cms-go/internal/data/model" @@ -64,3 +66,26 @@ func (d *DataSource) GetDb(name string) *model.Client { func GetDB() *model.Client { return ds.GetDb("default") } +func WithTx(ctx context.Context, client *model.Client, fn func(tx *model.Tx) error) error { + tx, err := client.Tx(ctx) + if err != nil { + return err + } + defer func() { + if v := recover(); v != nil { + tx.Rollback() + panic(v) + } + }() + if err := fn(tx); err != nil { + if rerr := tx.Rollback(); rerr != nil { + err = errors.Wrapf(err, "rolling back transaction: %v", rerr) + + } + return err + } + if err := tx.Commit(); err != nil { + return errors.Wrapf(err, "committing transaction: %v", err) + } + return nil +} diff --git a/internal/data/model/lingroup.go b/internal/data/model/lingroup.go index 6972969..22e166a 100644 --- a/internal/data/model/lingroup.go +++ b/internal/data/model/lingroup.go @@ -6,6 +6,7 @@ import ( "fmt" "lin-cms-go/internal/data/model/lingroup" "strings" + "time" "entgo.io/ent/dialect/sql" ) @@ -15,6 +16,12 @@ type LinGroup struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` // Name holds the value of the "name" field. // 分组名称,例如:搬砖者 Name string `json:"name,omitempty"` @@ -67,6 +74,8 @@ func (*LinGroup) scanValues(columns []string) ([]interface{}, error) { values[i] = new(sql.NullInt64) case lingroup.FieldName, lingroup.FieldInfo: values[i] = new(sql.NullString) + case lingroup.FieldCreateTime, lingroup.FieldUpdateTime, lingroup.FieldDeleteTime: + values[i] = new(sql.NullTime) default: return nil, fmt.Errorf("unexpected column %q for type LinGroup", columns[i]) } @@ -88,6 +97,24 @@ func (lg *LinGroup) assignValues(columns []string, values []interface{}) error { return fmt.Errorf("unexpected type %T for field id", value) } lg.ID = int(value.Int64) + case lingroup.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + lg.CreateTime = value.Time + } + case lingroup.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + lg.UpdateTime = value.Time + } + case lingroup.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + lg.DeleteTime = value.Time + } case lingroup.FieldName: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field name", values[i]) @@ -144,6 +171,12 @@ func (lg *LinGroup) String() string { var builder strings.Builder builder.WriteString("LinGroup(") builder.WriteString(fmt.Sprintf("id=%v", lg.ID)) + builder.WriteString(", create_time=") + builder.WriteString(lg.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(lg.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(lg.DeleteTime.Format(time.ANSIC)) builder.WriteString(", name=") builder.WriteString(lg.Name) builder.WriteString(", info=") diff --git a/internal/data/model/lingroup/lingroup.go b/internal/data/model/lingroup/lingroup.go index 9e1e505..f2ada9b 100644 --- a/internal/data/model/lingroup/lingroup.go +++ b/internal/data/model/lingroup/lingroup.go @@ -2,11 +2,21 @@ package lingroup +import ( + "time" +) + const ( // Label holds the string label denoting the lingroup type in the database. Label = "lin_group" // FieldID holds the string denoting the id field in the database. FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" // FieldName holds the string denoting the name field in the database. FieldName = "name" // FieldInfo holds the string denoting the info field in the database. @@ -34,6 +44,9 @@ const ( // Columns holds all SQL columns for lingroup fields. var Columns = []string{ FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, FieldName, FieldInfo, FieldLevel, @@ -42,7 +55,7 @@ var Columns = []string{ var ( // LinUserPrimaryKey and LinUserColumn2 are the table columns denoting the // primary key for the lin_user relation (M2M). - LinUserPrimaryKey = []string{"user_id", "group_id"} + LinUserPrimaryKey = []string{"group_id", "user_id"} // LinPermissionPrimaryKey and LinPermissionColumn2 are the table columns denoting the // primary key for the lin_permission relation (M2M). LinPermissionPrimaryKey = []string{"permission_id", "group_id"} @@ -57,3 +70,14 @@ func ValidColumn(column string) bool { } return false } + +var ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // DefaultDeleteTime holds the default value on creation for the "delete_time" field. + DefaultDeleteTime func() time.Time +) diff --git a/internal/data/model/lingroup/where.go b/internal/data/model/lingroup/where.go index d4c70dd..70e1745 100644 --- a/internal/data/model/lingroup/where.go +++ b/internal/data/model/lingroup/where.go @@ -4,6 +4,7 @@ package lingroup import ( "lin-cms-go/internal/data/model/predicate" + "time" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -92,6 +93,27 @@ func IDLTE(id int) predicate.LinGroup { }) } +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + // Name applies equality check predicate on the "name" field. It's identical to NameEQ. func Name(v string) predicate.LinGroup { return predicate.LinGroup(func(s *sql.Selector) { @@ -113,6 +135,234 @@ func Level(v int8) predicate.LinGroup { }) } +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.LinGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinGroup(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + // NameEQ applies the EQ predicate on the "name" field. func NameEQ(v string) predicate.LinGroup { return predicate.LinGroup(func(s *sql.Selector) { diff --git a/internal/data/model/lingroup_create.go b/internal/data/model/lingroup_create.go index 9b3b354..76e1a8b 100644 --- a/internal/data/model/lingroup_create.go +++ b/internal/data/model/lingroup_create.go @@ -9,6 +9,7 @@ import ( "lin-cms-go/internal/data/model/lingroup" "lin-cms-go/internal/data/model/linpermission" "lin-cms-go/internal/data/model/linuser" + "time" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -21,6 +22,48 @@ type LinGroupCreate struct { hooks []Hook } +// SetCreateTime sets the "create_time" field. +func (lgc *LinGroupCreate) SetCreateTime(t time.Time) *LinGroupCreate { + lgc.mutation.SetCreateTime(t) + return lgc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (lgc *LinGroupCreate) SetNillableCreateTime(t *time.Time) *LinGroupCreate { + if t != nil { + lgc.SetCreateTime(*t) + } + return lgc +} + +// SetUpdateTime sets the "update_time" field. +func (lgc *LinGroupCreate) SetUpdateTime(t time.Time) *LinGroupCreate { + lgc.mutation.SetUpdateTime(t) + return lgc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (lgc *LinGroupCreate) SetNillableUpdateTime(t *time.Time) *LinGroupCreate { + if t != nil { + lgc.SetUpdateTime(*t) + } + return lgc +} + +// SetDeleteTime sets the "delete_time" field. +func (lgc *LinGroupCreate) SetDeleteTime(t time.Time) *LinGroupCreate { + lgc.mutation.SetDeleteTime(t) + return lgc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (lgc *LinGroupCreate) SetNillableDeleteTime(t *time.Time) *LinGroupCreate { + if t != nil { + lgc.SetDeleteTime(*t) + } + return lgc +} + // SetName sets the "name" field. func (lgc *LinGroupCreate) SetName(s string) *LinGroupCreate { lgc.mutation.SetName(s) @@ -80,6 +123,7 @@ func (lgc *LinGroupCreate) Save(ctx context.Context) (*LinGroup, error) { err error node *LinGroup ) + lgc.defaults() if len(lgc.hooks) == 0 { if err = lgc.check(); err != nil { return nil, err @@ -137,8 +181,33 @@ func (lgc *LinGroupCreate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (lgc *LinGroupCreate) defaults() { + if _, ok := lgc.mutation.CreateTime(); !ok { + v := lingroup.DefaultCreateTime() + lgc.mutation.SetCreateTime(v) + } + if _, ok := lgc.mutation.UpdateTime(); !ok { + v := lingroup.DefaultUpdateTime() + lgc.mutation.SetUpdateTime(v) + } + if _, ok := lgc.mutation.DeleteTime(); !ok { + v := lingroup.DefaultDeleteTime() + lgc.mutation.SetDeleteTime(v) + } +} + // check runs all checks and user-defined validators on the builder. func (lgc *LinGroupCreate) check() error { + if _, ok := lgc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := lgc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } + if _, ok := lgc.mutation.DeleteTime(); !ok { + return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} + } if _, ok := lgc.mutation.Name(); !ok { return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} } @@ -175,6 +244,30 @@ func (lgc *LinGroupCreate) createSpec() (*LinGroup, *sqlgraph.CreateSpec) { }, } ) + if value, ok := lgc.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := lgc.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := lgc.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldDeleteTime, + }) + _node.DeleteTime = value + } if value, ok := lgc.mutation.Name(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -254,6 +347,7 @@ func (lgcb *LinGroupCreateBulk) Save(ctx context.Context) ([]*LinGroup, error) { for i := range lgcb.builders { func(i int, root context.Context) { builder := lgcb.builders[i] + builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*LinGroupMutation) if !ok { diff --git a/internal/data/model/lingroup_query.go b/internal/data/model/lingroup_query.go index b9e8d72..6460311 100644 --- a/internal/data/model/lingroup_query.go +++ b/internal/data/model/lingroup_query.go @@ -372,12 +372,12 @@ func (lgq *LinGroupQuery) WithLinPermission(opts ...func(*LinPermissionQuery)) * // Example: // // var v []struct { -// Name string `json:"name,omitempty"` +// CreateTime time.Time `json:"create_time,omitempty"` // Count int `json:"count,omitempty"` // } // // client.LinGroup.Query(). -// GroupBy(lingroup.FieldName). +// GroupBy(lingroup.FieldCreateTime). // Aggregate(model.Count()). // Scan(ctx, &v) // @@ -399,11 +399,11 @@ func (lgq *LinGroupQuery) GroupBy(field string, fields ...string) *LinGroupGroup // Example: // // var v []struct { -// Name string `json:"name,omitempty"` +// CreateTime time.Time `json:"create_time,omitempty"` // } // // client.LinGroup.Query(). -// Select(lingroup.FieldName). +// Select(lingroup.FieldCreateTime). // Scan(ctx, &v) // func (lgq *LinGroupQuery) Select(fields ...string) *LinGroupSelect { diff --git a/internal/data/model/lingroup_update.go b/internal/data/model/lingroup_update.go index 09bd286..7f7085d 100644 --- a/internal/data/model/lingroup_update.go +++ b/internal/data/model/lingroup_update.go @@ -9,6 +9,7 @@ import ( "lin-cms-go/internal/data/model/linpermission" "lin-cms-go/internal/data/model/linuser" "lin-cms-go/internal/data/model/predicate" + "time" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -28,6 +29,26 @@ func (lgu *LinGroupUpdate) Where(ps ...predicate.LinGroup) *LinGroupUpdate { return lgu } +// SetUpdateTime sets the "update_time" field. +func (lgu *LinGroupUpdate) SetUpdateTime(t time.Time) *LinGroupUpdate { + lgu.mutation.SetUpdateTime(t) + return lgu +} + +// SetDeleteTime sets the "delete_time" field. +func (lgu *LinGroupUpdate) SetDeleteTime(t time.Time) *LinGroupUpdate { + lgu.mutation.SetDeleteTime(t) + return lgu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (lgu *LinGroupUpdate) SetNillableDeleteTime(t *time.Time) *LinGroupUpdate { + if t != nil { + lgu.SetDeleteTime(*t) + } + return lgu +} + // SetName sets the "name" field. func (lgu *LinGroupUpdate) SetName(s string) *LinGroupUpdate { lgu.mutation.SetName(s) @@ -136,6 +157,7 @@ func (lgu *LinGroupUpdate) Save(ctx context.Context) (int, error) { err error affected int ) + lgu.defaults() if len(lgu.hooks) == 0 { affected, err = lgu.sqlSave(ctx) } else { @@ -184,6 +206,14 @@ func (lgu *LinGroupUpdate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (lgu *LinGroupUpdate) defaults() { + if _, ok := lgu.mutation.UpdateTime(); !ok { + v := lingroup.UpdateDefaultUpdateTime() + lgu.mutation.SetUpdateTime(v) + } +} + func (lgu *LinGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -202,6 +232,20 @@ func (lgu *LinGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { } } } + if value, ok := lgu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldUpdateTime, + }) + } + if value, ok := lgu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldDeleteTime, + }) + } if value, ok := lgu.mutation.Name(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -357,6 +401,26 @@ type LinGroupUpdateOne struct { mutation *LinGroupMutation } +// SetUpdateTime sets the "update_time" field. +func (lguo *LinGroupUpdateOne) SetUpdateTime(t time.Time) *LinGroupUpdateOne { + lguo.mutation.SetUpdateTime(t) + return lguo +} + +// SetDeleteTime sets the "delete_time" field. +func (lguo *LinGroupUpdateOne) SetDeleteTime(t time.Time) *LinGroupUpdateOne { + lguo.mutation.SetDeleteTime(t) + return lguo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (lguo *LinGroupUpdateOne) SetNillableDeleteTime(t *time.Time) *LinGroupUpdateOne { + if t != nil { + lguo.SetDeleteTime(*t) + } + return lguo +} + // SetName sets the "name" field. func (lguo *LinGroupUpdateOne) SetName(s string) *LinGroupUpdateOne { lguo.mutation.SetName(s) @@ -472,6 +536,7 @@ func (lguo *LinGroupUpdateOne) Save(ctx context.Context) (*LinGroup, error) { err error node *LinGroup ) + lguo.defaults() if len(lguo.hooks) == 0 { node, err = lguo.sqlSave(ctx) } else { @@ -520,6 +585,14 @@ func (lguo *LinGroupUpdateOne) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (lguo *LinGroupUpdateOne) defaults() { + if _, ok := lguo.mutation.UpdateTime(); !ok { + v := lingroup.UpdateDefaultUpdateTime() + lguo.mutation.SetUpdateTime(v) + } +} + func (lguo *LinGroupUpdateOne) sqlSave(ctx context.Context) (_node *LinGroup, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -555,6 +628,20 @@ func (lguo *LinGroupUpdateOne) sqlSave(ctx context.Context) (_node *LinGroup, er } } } + if value, ok := lguo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldUpdateTime, + }) + } + if value, ok := lguo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: lingroup.FieldDeleteTime, + }) + } if value, ok := lguo.mutation.Name(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, diff --git a/internal/data/model/linuser/linuser.go b/internal/data/model/linuser/linuser.go index 8943e07..314cfe7 100644 --- a/internal/data/model/linuser/linuser.go +++ b/internal/data/model/linuser/linuser.go @@ -60,7 +60,7 @@ var Columns = []string{ var ( // LinGroupPrimaryKey and LinGroupColumn2 are the table columns denoting the // primary key for the lin_group relation (M2M). - LinGroupPrimaryKey = []string{"user_id", "group_id"} + LinGroupPrimaryKey = []string{"group_id", "user_id"} ) // ValidColumn reports if the column name is valid (part of the table columns). diff --git a/internal/data/model/linuseridentiy.go b/internal/data/model/linuseridentiy.go index 5834615..05fefe3 100644 --- a/internal/data/model/linuseridentiy.go +++ b/internal/data/model/linuseridentiy.go @@ -6,6 +6,7 @@ import ( "fmt" "lin-cms-go/internal/data/model/linuseridentiy" "strings" + "time" "entgo.io/ent/dialect/sql" ) @@ -15,6 +16,12 @@ type LinUserIdentiy struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` // UserID holds the value of the "user_id" field. // 用户id UserID int `json:"user_id,omitempty"` @@ -36,6 +43,8 @@ func (*LinUserIdentiy) scanValues(columns []string) ([]interface{}, error) { values[i] = new(sql.NullInt64) case linuseridentiy.FieldIdentityType, linuseridentiy.FieldIdentifier, linuseridentiy.FieldCredential: values[i] = new(sql.NullString) + case linuseridentiy.FieldCreateTime, linuseridentiy.FieldUpdateTime, linuseridentiy.FieldDeleteTime: + values[i] = new(sql.NullTime) case linuseridentiy.ForeignKeys[0]: // lin_user_lin_user_identiy values[i] = new(sql.NullInt64) default: @@ -59,6 +68,24 @@ func (lui *LinUserIdentiy) assignValues(columns []string, values []interface{}) return fmt.Errorf("unexpected type %T for field id", value) } lui.ID = int(value.Int64) + case linuseridentiy.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + lui.CreateTime = value.Time + } + case linuseridentiy.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + lui.UpdateTime = value.Time + } + case linuseridentiy.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + lui.DeleteTime = value.Time + } case linuseridentiy.FieldUserID: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field user_id", values[i]) @@ -118,6 +145,12 @@ func (lui *LinUserIdentiy) String() string { var builder strings.Builder builder.WriteString("LinUserIdentiy(") builder.WriteString(fmt.Sprintf("id=%v", lui.ID)) + builder.WriteString(", create_time=") + builder.WriteString(lui.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(lui.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(lui.DeleteTime.Format(time.ANSIC)) builder.WriteString(", user_id=") builder.WriteString(fmt.Sprintf("%v", lui.UserID)) builder.WriteString(", identity_type=") diff --git a/internal/data/model/linuseridentiy/linuseridentiy.go b/internal/data/model/linuseridentiy/linuseridentiy.go index 7339818..066aa4f 100644 --- a/internal/data/model/linuseridentiy/linuseridentiy.go +++ b/internal/data/model/linuseridentiy/linuseridentiy.go @@ -2,11 +2,21 @@ package linuseridentiy +import ( + "time" +) + const ( // Label holds the string label denoting the linuseridentiy type in the database. Label = "lin_user_identiy" // FieldID holds the string denoting the id field in the database. FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" // FieldUserID holds the string denoting the user_id field in the database. FieldUserID = "user_id" // FieldIdentityType holds the string denoting the identity_type field in the database. @@ -22,6 +32,9 @@ const ( // Columns holds all SQL columns for linuseridentiy fields. var Columns = []string{ FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, FieldUserID, FieldIdentityType, FieldIdentifier, @@ -48,3 +61,14 @@ func ValidColumn(column string) bool { } return false } + +var ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // DefaultDeleteTime holds the default value on creation for the "delete_time" field. + DefaultDeleteTime func() time.Time +) diff --git a/internal/data/model/linuseridentiy/where.go b/internal/data/model/linuseridentiy/where.go index 69704f1..3e14fad 100644 --- a/internal/data/model/linuseridentiy/where.go +++ b/internal/data/model/linuseridentiy/where.go @@ -4,6 +4,7 @@ package linuseridentiy import ( "lin-cms-go/internal/data/model/predicate" + "time" "entgo.io/ent/dialect/sql" ) @@ -91,6 +92,27 @@ func IDLTE(id int) predicate.LinUserIdentiy { }) } +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + // UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. func UserID(v int) predicate.LinUserIdentiy { return predicate.LinUserIdentiy(func(s *sql.Selector) { @@ -119,6 +141,234 @@ func Credential(v string) predicate.LinUserIdentiy { }) } +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.LinUserIdentiy { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.LinUserIdentiy(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + // UserIDEQ applies the EQ predicate on the "user_id" field. func UserIDEQ(v int) predicate.LinUserIdentiy { return predicate.LinUserIdentiy(func(s *sql.Selector) { diff --git a/internal/data/model/linuseridentiy_create.go b/internal/data/model/linuseridentiy_create.go index 5c5c685..2f3aac2 100644 --- a/internal/data/model/linuseridentiy_create.go +++ b/internal/data/model/linuseridentiy_create.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "lin-cms-go/internal/data/model/linuseridentiy" + "time" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -19,6 +20,48 @@ type LinUserIdentiyCreate struct { hooks []Hook } +// SetCreateTime sets the "create_time" field. +func (luic *LinUserIdentiyCreate) SetCreateTime(t time.Time) *LinUserIdentiyCreate { + luic.mutation.SetCreateTime(t) + return luic +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (luic *LinUserIdentiyCreate) SetNillableCreateTime(t *time.Time) *LinUserIdentiyCreate { + if t != nil { + luic.SetCreateTime(*t) + } + return luic +} + +// SetUpdateTime sets the "update_time" field. +func (luic *LinUserIdentiyCreate) SetUpdateTime(t time.Time) *LinUserIdentiyCreate { + luic.mutation.SetUpdateTime(t) + return luic +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (luic *LinUserIdentiyCreate) SetNillableUpdateTime(t *time.Time) *LinUserIdentiyCreate { + if t != nil { + luic.SetUpdateTime(*t) + } + return luic +} + +// SetDeleteTime sets the "delete_time" field. +func (luic *LinUserIdentiyCreate) SetDeleteTime(t time.Time) *LinUserIdentiyCreate { + luic.mutation.SetDeleteTime(t) + return luic +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luic *LinUserIdentiyCreate) SetNillableDeleteTime(t *time.Time) *LinUserIdentiyCreate { + if t != nil { + luic.SetDeleteTime(*t) + } + return luic +} + // SetUserID sets the "user_id" field. func (luic *LinUserIdentiyCreate) SetUserID(i int) *LinUserIdentiyCreate { luic.mutation.SetUserID(i) @@ -54,6 +97,7 @@ func (luic *LinUserIdentiyCreate) Save(ctx context.Context) (*LinUserIdentiy, er err error node *LinUserIdentiy ) + luic.defaults() if len(luic.hooks) == 0 { if err = luic.check(); err != nil { return nil, err @@ -111,8 +155,33 @@ func (luic *LinUserIdentiyCreate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (luic *LinUserIdentiyCreate) defaults() { + if _, ok := luic.mutation.CreateTime(); !ok { + v := linuseridentiy.DefaultCreateTime() + luic.mutation.SetCreateTime(v) + } + if _, ok := luic.mutation.UpdateTime(); !ok { + v := linuseridentiy.DefaultUpdateTime() + luic.mutation.SetUpdateTime(v) + } + if _, ok := luic.mutation.DeleteTime(); !ok { + v := linuseridentiy.DefaultDeleteTime() + luic.mutation.SetDeleteTime(v) + } +} + // check runs all checks and user-defined validators on the builder. func (luic *LinUserIdentiyCreate) check() error { + if _, ok := luic.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := luic.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } + if _, ok := luic.mutation.DeleteTime(); !ok { + return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} + } if _, ok := luic.mutation.UserID(); !ok { return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} } @@ -152,6 +221,30 @@ func (luic *LinUserIdentiyCreate) createSpec() (*LinUserIdentiy, *sqlgraph.Creat }, } ) + if value, ok := luic.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := luic.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := luic.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldDeleteTime, + }) + _node.DeleteTime = value + } if value, ok := luic.mutation.UserID(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ Type: field.TypeInt, @@ -201,6 +294,7 @@ func (luicb *LinUserIdentiyCreateBulk) Save(ctx context.Context) ([]*LinUserIden for i := range luicb.builders { func(i int, root context.Context) { builder := luicb.builders[i] + builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*LinUserIdentiyMutation) if !ok { diff --git a/internal/data/model/linuseridentiy_query.go b/internal/data/model/linuseridentiy_query.go index 2a91964..21e989e 100644 --- a/internal/data/model/linuseridentiy_query.go +++ b/internal/data/model/linuseridentiy_query.go @@ -299,12 +299,12 @@ func (luiq *LinUserIdentiyQuery) Clone() *LinUserIdentiyQuery { // Example: // // var v []struct { -// UserID int `json:"user_id,omitempty"` +// CreateTime time.Time `json:"create_time,omitempty"` // Count int `json:"count,omitempty"` // } // // client.LinUserIdentiy.Query(). -// GroupBy(linuseridentiy.FieldUserID). +// GroupBy(linuseridentiy.FieldCreateTime). // Aggregate(model.Count()). // Scan(ctx, &v) // @@ -326,11 +326,11 @@ func (luiq *LinUserIdentiyQuery) GroupBy(field string, fields ...string) *LinUse // Example: // // var v []struct { -// UserID int `json:"user_id,omitempty"` +// CreateTime time.Time `json:"create_time,omitempty"` // } // // client.LinUserIdentiy.Query(). -// Select(linuseridentiy.FieldUserID). +// Select(linuseridentiy.FieldCreateTime). // Scan(ctx, &v) // func (luiq *LinUserIdentiyQuery) Select(fields ...string) *LinUserIdentiySelect { diff --git a/internal/data/model/linuseridentiy_update.go b/internal/data/model/linuseridentiy_update.go index d11f59b..6033b6b 100644 --- a/internal/data/model/linuseridentiy_update.go +++ b/internal/data/model/linuseridentiy_update.go @@ -7,6 +7,7 @@ import ( "fmt" "lin-cms-go/internal/data/model/linuseridentiy" "lin-cms-go/internal/data/model/predicate" + "time" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -26,6 +27,26 @@ func (luiu *LinUserIdentiyUpdate) Where(ps ...predicate.LinUserIdentiy) *LinUser return luiu } +// SetUpdateTime sets the "update_time" field. +func (luiu *LinUserIdentiyUpdate) SetUpdateTime(t time.Time) *LinUserIdentiyUpdate { + luiu.mutation.SetUpdateTime(t) + return luiu +} + +// SetDeleteTime sets the "delete_time" field. +func (luiu *LinUserIdentiyUpdate) SetDeleteTime(t time.Time) *LinUserIdentiyUpdate { + luiu.mutation.SetDeleteTime(t) + return luiu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luiu *LinUserIdentiyUpdate) SetNillableDeleteTime(t *time.Time) *LinUserIdentiyUpdate { + if t != nil { + luiu.SetDeleteTime(*t) + } + return luiu +} + // SetUserID sets the "user_id" field. func (luiu *LinUserIdentiyUpdate) SetUserID(i int) *LinUserIdentiyUpdate { luiu.mutation.ResetUserID() @@ -68,6 +89,7 @@ func (luiu *LinUserIdentiyUpdate) Save(ctx context.Context) (int, error) { err error affected int ) + luiu.defaults() if len(luiu.hooks) == 0 { affected, err = luiu.sqlSave(ctx) } else { @@ -116,6 +138,14 @@ func (luiu *LinUserIdentiyUpdate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (luiu *LinUserIdentiyUpdate) defaults() { + if _, ok := luiu.mutation.UpdateTime(); !ok { + v := linuseridentiy.UpdateDefaultUpdateTime() + luiu.mutation.SetUpdateTime(v) + } +} + func (luiu *LinUserIdentiyUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -134,6 +164,20 @@ func (luiu *LinUserIdentiyUpdate) sqlSave(ctx context.Context) (n int, err error } } } + if value, ok := luiu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldUpdateTime, + }) + } + if value, ok := luiu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldDeleteTime, + }) + } if value, ok := luiu.mutation.UserID(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt, @@ -188,6 +232,26 @@ type LinUserIdentiyUpdateOne struct { mutation *LinUserIdentiyMutation } +// SetUpdateTime sets the "update_time" field. +func (luiuo *LinUserIdentiyUpdateOne) SetUpdateTime(t time.Time) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetUpdateTime(t) + return luiuo +} + +// SetDeleteTime sets the "delete_time" field. +func (luiuo *LinUserIdentiyUpdateOne) SetDeleteTime(t time.Time) *LinUserIdentiyUpdateOne { + luiuo.mutation.SetDeleteTime(t) + return luiuo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (luiuo *LinUserIdentiyUpdateOne) SetNillableDeleteTime(t *time.Time) *LinUserIdentiyUpdateOne { + if t != nil { + luiuo.SetDeleteTime(*t) + } + return luiuo +} + // SetUserID sets the "user_id" field. func (luiuo *LinUserIdentiyUpdateOne) SetUserID(i int) *LinUserIdentiyUpdateOne { luiuo.mutation.ResetUserID() @@ -237,6 +301,7 @@ func (luiuo *LinUserIdentiyUpdateOne) Save(ctx context.Context) (*LinUserIdentiy err error node *LinUserIdentiy ) + luiuo.defaults() if len(luiuo.hooks) == 0 { node, err = luiuo.sqlSave(ctx) } else { @@ -285,6 +350,14 @@ func (luiuo *LinUserIdentiyUpdateOne) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (luiuo *LinUserIdentiyUpdateOne) defaults() { + if _, ok := luiuo.mutation.UpdateTime(); !ok { + v := linuseridentiy.UpdateDefaultUpdateTime() + luiuo.mutation.SetUpdateTime(v) + } +} + func (luiuo *LinUserIdentiyUpdateOne) sqlSave(ctx context.Context) (_node *LinUserIdentiy, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -320,6 +393,20 @@ func (luiuo *LinUserIdentiyUpdateOne) sqlSave(ctx context.Context) (_node *LinUs } } } + if value, ok := luiuo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldUpdateTime, + }) + } + if value, ok := luiuo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: linuseridentiy.FieldDeleteTime, + }) + } if value, ok := luiuo.mutation.UserID(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt, diff --git a/internal/data/model/migrate/schema.go b/internal/data/model/migrate/schema.go index 5de9495..d1b25a0 100644 --- a/internal/data/model/migrate/schema.go +++ b/internal/data/model/migrate/schema.go @@ -42,6 +42,9 @@ var ( // LinGroupColumns holds the columns for the "lin_group" table. LinGroupColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime}, {Name: "name", Type: field.TypeString, Unique: true}, {Name: "info", Type: field.TypeString}, {Name: "level", Type: field.TypeInt8}, @@ -105,6 +108,9 @@ var ( // LinUserIdentiyColumns holds the columns for the "lin_user_identiy" table. LinUserIdentiyColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime}, {Name: "user_id", Type: field.TypeInt}, {Name: "identity_type", Type: field.TypeString}, {Name: "identifier", Type: field.TypeString}, @@ -119,7 +125,7 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "lin_user_identiy_lin_user_lin_user_identiy", - Columns: []*schema.Column{LinUserIdentiyColumns[5]}, + Columns: []*schema.Column{LinUserIdentiyColumns[8]}, RefColumns: []*schema.Column{LinUserColumns[0]}, OnDelete: schema.SetNull, }, @@ -127,8 +133,8 @@ var ( } // LinUserGroupColumns holds the columns for the "lin_user_group" table. LinUserGroupColumns = []*schema.Column{ - {Name: "user_id", Type: field.TypeInt}, {Name: "group_id", Type: field.TypeInt}, + {Name: "user_id", Type: field.TypeInt}, } // LinUserGroupTable holds the schema information for the "lin_user_group" table. LinUserGroupTable = &schema.Table{ @@ -137,13 +143,13 @@ var ( PrimaryKey: []*schema.Column{LinUserGroupColumns[0], LinUserGroupColumns[1]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "lin_user_group_user_id", + Symbol: "lin_user_group_group_id", Columns: []*schema.Column{LinUserGroupColumns[0]}, RefColumns: []*schema.Column{LinGroupColumns[0]}, OnDelete: schema.Cascade, }, { - Symbol: "lin_user_group_group_id", + Symbol: "lin_user_group_user_id", Columns: []*schema.Column{LinUserGroupColumns[1]}, RefColumns: []*schema.Column{LinUserColumns[0]}, OnDelete: schema.Cascade, diff --git a/internal/data/model/mutation.go b/internal/data/model/mutation.go index 9391c9e..24559b9 100644 --- a/internal/data/model/mutation.go +++ b/internal/data/model/mutation.go @@ -1128,6 +1128,9 @@ type LinGroupMutation struct { op Op typ string id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time name *string info *string level *int8 @@ -1223,6 +1226,114 @@ func (m *LinGroupMutation) ID() (id int, exists bool) { return *m.id, true } +// SetCreateTime sets the "create_time" field. +func (m *LinGroupMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *LinGroupMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *LinGroupMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *LinGroupMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *LinGroupMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *LinGroupMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *LinGroupMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *LinGroupMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the LinGroup entity. +// If the LinGroup 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 *LinGroupMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *LinGroupMutation) ResetDeleteTime() { + m.delete_time = nil +} + // SetName sets the "name" field. func (m *LinGroupMutation) SetName(s string) { m.name = &s @@ -1478,7 +1589,16 @@ func (m *LinGroupMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *LinGroupMutation) Fields() []string { - fields := make([]string, 0, 3) + fields := make([]string, 0, 6) + if m.create_time != nil { + fields = append(fields, lingroup.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, lingroup.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, lingroup.FieldDeleteTime) + } if m.name != nil { fields = append(fields, lingroup.FieldName) } @@ -1496,6 +1616,12 @@ func (m *LinGroupMutation) Fields() []string { // schema. func (m *LinGroupMutation) Field(name string) (ent.Value, bool) { switch name { + case lingroup.FieldCreateTime: + return m.CreateTime() + case lingroup.FieldUpdateTime: + return m.UpdateTime() + case lingroup.FieldDeleteTime: + return m.DeleteTime() case lingroup.FieldName: return m.Name() case lingroup.FieldInfo: @@ -1511,6 +1637,12 @@ func (m *LinGroupMutation) Field(name string) (ent.Value, bool) { // database failed. func (m *LinGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { + case lingroup.FieldCreateTime: + return m.OldCreateTime(ctx) + case lingroup.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case lingroup.FieldDeleteTime: + return m.OldDeleteTime(ctx) case lingroup.FieldName: return m.OldName(ctx) case lingroup.FieldInfo: @@ -1526,6 +1658,27 @@ func (m *LinGroupMutation) OldField(ctx context.Context, name string) (ent.Value // type. func (m *LinGroupMutation) SetField(name string, value ent.Value) error { switch name { + case lingroup.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case lingroup.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case lingroup.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil case lingroup.FieldName: v, ok := value.(string) if !ok { @@ -1611,6 +1764,15 @@ func (m *LinGroupMutation) ClearField(name string) error { // It returns an error if the field is not defined in the schema. func (m *LinGroupMutation) ResetField(name string) error { switch name { + case lingroup.FieldCreateTime: + m.ResetCreateTime() + return nil + case lingroup.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case lingroup.FieldDeleteTime: + m.ResetDeleteTime() + return nil case lingroup.FieldName: m.ResetName() return nil @@ -3908,6 +4070,9 @@ type LinUserIdentiyMutation struct { op Op typ string id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time user_id *int adduser_id *int identity_type *string @@ -3998,6 +4163,114 @@ func (m *LinUserIdentiyMutation) ID() (id int, exists bool) { return *m.id, true } +// SetCreateTime sets the "create_time" field. +func (m *LinUserIdentiyMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *LinUserIdentiyMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *LinUserIdentiyMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *LinUserIdentiyMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *LinUserIdentiyMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *LinUserIdentiyMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *LinUserIdentiyMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *LinUserIdentiyMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the LinUserIdentiy entity. +// If the LinUserIdentiy 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 *LinUserIdentiyMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *LinUserIdentiyMutation) ResetDeleteTime() { + m.delete_time = nil +} + // SetUserID sets the "user_id" field. func (m *LinUserIdentiyMutation) SetUserID(i int) { m.user_id = &i @@ -4181,7 +4454,16 @@ func (m *LinUserIdentiyMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *LinUserIdentiyMutation) Fields() []string { - fields := make([]string, 0, 4) + fields := make([]string, 0, 7) + if m.create_time != nil { + fields = append(fields, linuseridentiy.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, linuseridentiy.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, linuseridentiy.FieldDeleteTime) + } if m.user_id != nil { fields = append(fields, linuseridentiy.FieldUserID) } @@ -4202,6 +4484,12 @@ func (m *LinUserIdentiyMutation) Fields() []string { // schema. func (m *LinUserIdentiyMutation) Field(name string) (ent.Value, bool) { switch name { + case linuseridentiy.FieldCreateTime: + return m.CreateTime() + case linuseridentiy.FieldUpdateTime: + return m.UpdateTime() + case linuseridentiy.FieldDeleteTime: + return m.DeleteTime() case linuseridentiy.FieldUserID: return m.UserID() case linuseridentiy.FieldIdentityType: @@ -4219,6 +4507,12 @@ func (m *LinUserIdentiyMutation) Field(name string) (ent.Value, bool) { // database failed. func (m *LinUserIdentiyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { + case linuseridentiy.FieldCreateTime: + return m.OldCreateTime(ctx) + case linuseridentiy.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case linuseridentiy.FieldDeleteTime: + return m.OldDeleteTime(ctx) case linuseridentiy.FieldUserID: return m.OldUserID(ctx) case linuseridentiy.FieldIdentityType: @@ -4236,6 +4530,27 @@ func (m *LinUserIdentiyMutation) OldField(ctx context.Context, name string) (ent // type. func (m *LinUserIdentiyMutation) SetField(name string, value ent.Value) error { switch name { + case linuseridentiy.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case linuseridentiy.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case linuseridentiy.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil case linuseridentiy.FieldUserID: v, ok := value.(int) if !ok { @@ -4328,6 +4643,15 @@ func (m *LinUserIdentiyMutation) ClearField(name string) error { // It returns an error if the field is not defined in the schema. func (m *LinUserIdentiyMutation) ResetField(name string) error { switch name { + case linuseridentiy.FieldCreateTime: + m.ResetCreateTime() + return nil + case linuseridentiy.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case linuseridentiy.FieldDeleteTime: + m.ResetDeleteTime() + return nil case linuseridentiy.FieldUserID: m.ResetUserID() return nil diff --git a/internal/data/model/runtime.go b/internal/data/model/runtime.go index 345205e..fbd3038 100644 --- a/internal/data/model/runtime.go +++ b/internal/data/model/runtime.go @@ -4,8 +4,10 @@ package model import ( "lin-cms-go/internal/data/ent/schema" + "lin-cms-go/internal/data/model/lingroup" "lin-cms-go/internal/data/model/linlog" "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" "time" ) @@ -13,6 +15,25 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + lingroupMixin := schema.LinGroup{}.Mixin() + lingroupMixinFields0 := lingroupMixin[0].Fields() + _ = lingroupMixinFields0 + lingroupFields := schema.LinGroup{}.Fields() + _ = lingroupFields + // lingroupDescCreateTime is the schema descriptor for create_time field. + lingroupDescCreateTime := lingroupMixinFields0[0].Descriptor() + // lingroup.DefaultCreateTime holds the default value on creation for the create_time field. + lingroup.DefaultCreateTime = lingroupDescCreateTime.Default.(func() time.Time) + // lingroupDescUpdateTime is the schema descriptor for update_time field. + lingroupDescUpdateTime := lingroupMixinFields0[1].Descriptor() + // lingroup.DefaultUpdateTime holds the default value on creation for the update_time field. + lingroup.DefaultUpdateTime = lingroupDescUpdateTime.Default.(func() time.Time) + // lingroup.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + lingroup.UpdateDefaultUpdateTime = lingroupDescUpdateTime.UpdateDefault.(func() time.Time) + // lingroupDescDeleteTime is the schema descriptor for delete_time field. + lingroupDescDeleteTime := lingroupMixinFields0[2].Descriptor() + // lingroup.DefaultDeleteTime holds the default value on creation for the delete_time field. + lingroup.DefaultDeleteTime = lingroupDescDeleteTime.Default.(func() time.Time) linlogMixin := schema.LinLog{}.Mixin() linlogMixinFields0 := linlogMixin[0].Fields() _ = linlogMixinFields0 @@ -55,4 +76,23 @@ func init() { linuserDescAvatar := linuserFields[2].Descriptor() // linuser.DefaultAvatar holds the default value on creation for the avatar field. linuser.DefaultAvatar = linuserDescAvatar.Default.(string) + linuseridentiyMixin := schema.LinUserIdentiy{}.Mixin() + linuseridentiyMixinFields0 := linuseridentiyMixin[0].Fields() + _ = linuseridentiyMixinFields0 + linuseridentiyFields := schema.LinUserIdentiy{}.Fields() + _ = linuseridentiyFields + // linuseridentiyDescCreateTime is the schema descriptor for create_time field. + linuseridentiyDescCreateTime := linuseridentiyMixinFields0[0].Descriptor() + // linuseridentiy.DefaultCreateTime holds the default value on creation for the create_time field. + linuseridentiy.DefaultCreateTime = linuseridentiyDescCreateTime.Default.(func() time.Time) + // linuseridentiyDescUpdateTime is the schema descriptor for update_time field. + linuseridentiyDescUpdateTime := linuseridentiyMixinFields0[1].Descriptor() + // linuseridentiy.DefaultUpdateTime holds the default value on creation for the update_time field. + linuseridentiy.DefaultUpdateTime = linuseridentiyDescUpdateTime.Default.(func() time.Time) + // linuseridentiy.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + linuseridentiy.UpdateDefaultUpdateTime = linuseridentiyDescUpdateTime.UpdateDefault.(func() time.Time) + // linuseridentiyDescDeleteTime is the schema descriptor for delete_time field. + linuseridentiyDescDeleteTime := linuseridentiyMixinFields0[2].Descriptor() + // linuseridentiy.DefaultDeleteTime holds the default value on creation for the delete_time field. + linuseridentiy.DefaultDeleteTime = linuseridentiyDescDeleteTime.Default.(func() time.Time) } diff --git a/pkg/core/response.go b/pkg/core/response.go index c87c28f..2c1c989 100644 --- a/pkg/core/response.go +++ b/pkg/core/response.go @@ -24,16 +24,16 @@ func (err IError) Error() (re string) { } func NewErrorCode(code int) (err error) { - err = IError{ - Code: code, - Message: errcode.GetMsg(code), + err = HttpError{ + NewIError(code, errcode.GetMsg(code)), + fiber.StatusBadRequest, } return } func NewErrorMessage(code int, message string) (err error) { - err = IError{ - Code: code, - Message: message, + err = HttpError{ + NewIError(code, message), + fiber.StatusBadRequest, } return } @@ -122,7 +122,7 @@ func HandleServerError(c *fiber.Ctx, err error) error { } func (err *HttpError) HandleHttpError(c *fiber.Ctx) error { - return c.JSON(HttpError{IError{ + return c.Status(err.Status).JSON(IError{ Code: err.Code, Message: err.Message, - }, err.Status}) + }) } From 6d10490ca60824441e381b997f8c2377e84c8591 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Tue, 9 Nov 2021 14:00:10 +0800 Subject: [PATCH 33/44] feat : userlog middleware --- api/log.go | 1 + api/permission.go | 2 + internal/biz/biz.go | 6 +- internal/data/ent/schema/lin_user_group.go | 2 +- internal/data/log.go | 6 ++ internal/data/model/lingroup/lingroup.go | 2 - internal/data/model/lingroup/where.go | 14 +++ internal/data/model/lingroup_create.go | 7 -- internal/data/model/lingroup_update.go | 24 +++++ internal/data/model/linlog/linlog.go | 2 - internal/data/model/linlog/where.go | 14 +++ internal/data/model/linlog_create.go | 7 -- internal/data/model/linlog_update.go | 24 +++++ internal/data/model/linuser/linuser.go | 2 - internal/data/model/linuser/where.go | 14 +++ internal/data/model/linuser_create.go | 7 -- internal/data/model/linuser_update.go | 24 +++++ .../model/linuseridentiy/linuseridentiy.go | 2 - internal/data/model/linuseridentiy/where.go | 14 +++ internal/data/model/linuseridentiy_create.go | 7 -- internal/data/model/linuseridentiy_update.go | 24 +++++ internal/data/model/migrate/schema.go | 8 +- internal/data/model/mutation.go | 96 ++++++++++++++++++- internal/data/model/runtime.go | 16 ---- internal/server/http.go | 33 ------- internal/server/middleware.go | 22 +++++ main.go | 13 +-- 27 files changed, 289 insertions(+), 104 deletions(-) delete mode 100644 internal/server/http.go create mode 100644 internal/server/middleware.go diff --git a/api/log.go b/api/log.go index 03cd5c1..0d59344 100644 --- a/api/log.go +++ b/api/log.go @@ -17,6 +17,7 @@ func GetLogs(c *fiber.Ctx) error { if err := core.ParseQuery(c, &req); err != nil { return err } + data, total, err := biz.GetLogs(c.Context(), req, page, size) if err != nil { return err diff --git a/api/permission.go b/api/permission.go index e20ef17..0648106 100644 --- a/api/permission.go +++ b/api/permission.go @@ -8,6 +8,8 @@ import ( ) func GetAllPermissions(c *fiber.Ctx) error { + c.Locals("logMessage", "this is a message") + data, err := biz.GetAllPermissions(c.Context()) if err != nil { diff --git a/internal/biz/biz.go b/internal/biz/biz.go index 2c367bc..a7a73f0 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -8,7 +8,11 @@ import ( ) func LocalUser(c *fiber.Ctx) (user model.LinUser) { - jwtToken := c.Locals("user").(*jwt.Token) + local := c.Locals("user") + if local == nil { + return + } + jwtToken := local.(*jwt.Token) claims := jwtToken.Claims.(jwt.MapClaims) bytes, _ := utils.JSONEncode(claims["user"]) utils.JSONDecode(bytes, &user) diff --git a/internal/data/ent/schema/lin_user_group.go b/internal/data/ent/schema/lin_user_group.go index 02011ec..f7ed412 100644 --- a/internal/data/ent/schema/lin_user_group.go +++ b/internal/data/ent/schema/lin_user_group.go @@ -23,6 +23,6 @@ func (TimeMixin) Fields() []ent.Field { Default(time.Now). UpdateDefault(time.Now), field.Time("delete_time"). - Default(nil), + Optional(), } } diff --git a/internal/data/log.go b/internal/data/log.go index 112a21a..6c1705e 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -38,3 +38,9 @@ func GetLogUsersTotal(ctx context.Context) (total int, err error) { total, err = GetDB().LinLog.Query().Select(linlog.FieldUsername).Count(ctx) return } +func CreateLog(ctx context.Context, statusCode, userId int, username, message, method, path, permission string) (err error) { + + _, err = GetDB().LinLog.Create().SetStatusCode(statusCode).SetUserID(userId).SetUsername(username).SetMessage(message). + SetMethod(method).SetPath(path).SetPermission(permission).Save(ctx) + return +} diff --git a/internal/data/model/lingroup/lingroup.go b/internal/data/model/lingroup/lingroup.go index f2ada9b..70b549b 100644 --- a/internal/data/model/lingroup/lingroup.go +++ b/internal/data/model/lingroup/lingroup.go @@ -78,6 +78,4 @@ var ( DefaultUpdateTime func() time.Time // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. UpdateDefaultUpdateTime func() time.Time - // DefaultDeleteTime holds the default value on creation for the "delete_time" field. - DefaultDeleteTime func() time.Time ) diff --git a/internal/data/model/lingroup/where.go b/internal/data/model/lingroup/where.go index 70e1745..f03739a 100644 --- a/internal/data/model/lingroup/where.go +++ b/internal/data/model/lingroup/where.go @@ -363,6 +363,20 @@ func DeleteTimeLTE(v time.Time) predicate.LinGroup { }) } +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDeleteTime))) + }) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.LinGroup { + return predicate.LinGroup(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDeleteTime))) + }) +} + // NameEQ applies the EQ predicate on the "name" field. func NameEQ(v string) predicate.LinGroup { return predicate.LinGroup(func(s *sql.Selector) { diff --git a/internal/data/model/lingroup_create.go b/internal/data/model/lingroup_create.go index 76e1a8b..9399b1c 100644 --- a/internal/data/model/lingroup_create.go +++ b/internal/data/model/lingroup_create.go @@ -191,10 +191,6 @@ func (lgc *LinGroupCreate) defaults() { v := lingroup.DefaultUpdateTime() lgc.mutation.SetUpdateTime(v) } - if _, ok := lgc.mutation.DeleteTime(); !ok { - v := lingroup.DefaultDeleteTime() - lgc.mutation.SetDeleteTime(v) - } } // check runs all checks and user-defined validators on the builder. @@ -205,9 +201,6 @@ func (lgc *LinGroupCreate) check() error { if _, ok := lgc.mutation.UpdateTime(); !ok { return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} } - if _, ok := lgc.mutation.DeleteTime(); !ok { - return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} - } if _, ok := lgc.mutation.Name(); !ok { return &ValidationError{Name: "name", err: errors.New(`model: missing required field "name"`)} } diff --git a/internal/data/model/lingroup_update.go b/internal/data/model/lingroup_update.go index 7f7085d..9cbc7c5 100644 --- a/internal/data/model/lingroup_update.go +++ b/internal/data/model/lingroup_update.go @@ -49,6 +49,12 @@ func (lgu *LinGroupUpdate) SetNillableDeleteTime(t *time.Time) *LinGroupUpdate { return lgu } +// ClearDeleteTime clears the value of the "delete_time" field. +func (lgu *LinGroupUpdate) ClearDeleteTime() *LinGroupUpdate { + lgu.mutation.ClearDeleteTime() + return lgu +} + // SetName sets the "name" field. func (lgu *LinGroupUpdate) SetName(s string) *LinGroupUpdate { lgu.mutation.SetName(s) @@ -246,6 +252,12 @@ func (lgu *LinGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { Column: lingroup.FieldDeleteTime, }) } + if lgu.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: lingroup.FieldDeleteTime, + }) + } if value, ok := lgu.mutation.Name(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -421,6 +433,12 @@ func (lguo *LinGroupUpdateOne) SetNillableDeleteTime(t *time.Time) *LinGroupUpda return lguo } +// ClearDeleteTime clears the value of the "delete_time" field. +func (lguo *LinGroupUpdateOne) ClearDeleteTime() *LinGroupUpdateOne { + lguo.mutation.ClearDeleteTime() + return lguo +} + // SetName sets the "name" field. func (lguo *LinGroupUpdateOne) SetName(s string) *LinGroupUpdateOne { lguo.mutation.SetName(s) @@ -642,6 +660,12 @@ func (lguo *LinGroupUpdateOne) sqlSave(ctx context.Context) (_node *LinGroup, er Column: lingroup.FieldDeleteTime, }) } + if lguo.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: lingroup.FieldDeleteTime, + }) + } if value, ok := lguo.mutation.Name(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, diff --git a/internal/data/model/linlog/linlog.go b/internal/data/model/linlog/linlog.go index 14f4ab7..cb53813 100644 --- a/internal/data/model/linlog/linlog.go +++ b/internal/data/model/linlog/linlog.go @@ -67,6 +67,4 @@ var ( DefaultUpdateTime func() time.Time // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. UpdateDefaultUpdateTime func() time.Time - // DefaultDeleteTime holds the default value on creation for the "delete_time" field. - DefaultDeleteTime func() time.Time ) diff --git a/internal/data/model/linlog/where.go b/internal/data/model/linlog/where.go index c877f50..e263558 100644 --- a/internal/data/model/linlog/where.go +++ b/internal/data/model/linlog/where.go @@ -390,6 +390,20 @@ func DeleteTimeLTE(v time.Time) predicate.LinLog { }) } +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDeleteTime))) + }) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.LinLog { + return predicate.LinLog(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDeleteTime))) + }) +} + // MessageEQ applies the EQ predicate on the "message" field. func MessageEQ(v string) predicate.LinLog { return predicate.LinLog(func(s *sql.Selector) { diff --git a/internal/data/model/linlog_create.go b/internal/data/model/linlog_create.go index 9b9b76d..acd101a 100644 --- a/internal/data/model/linlog_create.go +++ b/internal/data/model/linlog_create.go @@ -183,10 +183,6 @@ func (llc *LinLogCreate) defaults() { v := linlog.DefaultUpdateTime() llc.mutation.SetUpdateTime(v) } - if _, ok := llc.mutation.DeleteTime(); !ok { - v := linlog.DefaultDeleteTime() - llc.mutation.SetDeleteTime(v) - } } // check runs all checks and user-defined validators on the builder. @@ -197,9 +193,6 @@ func (llc *LinLogCreate) check() error { if _, ok := llc.mutation.UpdateTime(); !ok { return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} } - if _, ok := llc.mutation.DeleteTime(); !ok { - return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} - } if _, ok := llc.mutation.Message(); !ok { return &ValidationError{Name: "message", err: errors.New(`model: missing required field "message"`)} } diff --git a/internal/data/model/linlog_update.go b/internal/data/model/linlog_update.go index 7b53bc4..ce7e23c 100644 --- a/internal/data/model/linlog_update.go +++ b/internal/data/model/linlog_update.go @@ -47,6 +47,12 @@ func (llu *LinLogUpdate) SetNillableDeleteTime(t *time.Time) *LinLogUpdate { return llu } +// ClearDeleteTime clears the value of the "delete_time" field. +func (llu *LinLogUpdate) ClearDeleteTime() *LinLogUpdate { + llu.mutation.ClearDeleteTime() + return llu +} + // SetMessage sets the "message" field. func (llu *LinLogUpdate) SetMessage(s string) *LinLogUpdate { llu.mutation.SetMessage(s) @@ -203,6 +209,12 @@ func (llu *LinLogUpdate) sqlSave(ctx context.Context) (n int, err error) { Column: linlog.FieldDeleteTime, }) } + if llu.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: linlog.FieldDeleteTime, + }) + } if value, ok := llu.mutation.Message(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -305,6 +317,12 @@ func (lluo *LinLogUpdateOne) SetNillableDeleteTime(t *time.Time) *LinLogUpdateOn return lluo } +// ClearDeleteTime clears the value of the "delete_time" field. +func (lluo *LinLogUpdateOne) ClearDeleteTime() *LinLogUpdateOne { + lluo.mutation.ClearDeleteTime() + return lluo +} + // SetMessage sets the "message" field. func (lluo *LinLogUpdateOne) SetMessage(s string) *LinLogUpdateOne { lluo.mutation.SetMessage(s) @@ -485,6 +503,12 @@ func (lluo *LinLogUpdateOne) sqlSave(ctx context.Context) (_node *LinLog, err er Column: linlog.FieldDeleteTime, }) } + if lluo.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: linlog.FieldDeleteTime, + }) + } if value, ok := lluo.mutation.Message(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, diff --git a/internal/data/model/linuser/linuser.go b/internal/data/model/linuser/linuser.go index 314cfe7..3024df4 100644 --- a/internal/data/model/linuser/linuser.go +++ b/internal/data/model/linuser/linuser.go @@ -80,8 +80,6 @@ var ( DefaultUpdateTime func() time.Time // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. UpdateDefaultUpdateTime func() time.Time - // DefaultDeleteTime holds the default value on creation for the "delete_time" field. - DefaultDeleteTime func() time.Time // DefaultAvatar holds the default value on creation for the "avatar" field. DefaultAvatar string ) diff --git a/internal/data/model/linuser/where.go b/internal/data/model/linuser/where.go index 2b13f11..6b1ba39 100644 --- a/internal/data/model/linuser/where.go +++ b/internal/data/model/linuser/where.go @@ -370,6 +370,20 @@ func DeleteTimeLTE(v time.Time) predicate.LinUser { }) } +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDeleteTime))) + }) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.LinUser { + return predicate.LinUser(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDeleteTime))) + }) +} + // UsernameEQ applies the EQ predicate on the "username" field. func UsernameEQ(v string) predicate.LinUser { return predicate.LinUser(func(s *sql.Selector) { diff --git a/internal/data/model/linuser_create.go b/internal/data/model/linuser_create.go index 60825f5..58f2c34 100644 --- a/internal/data/model/linuser_create.go +++ b/internal/data/model/linuser_create.go @@ -205,10 +205,6 @@ func (luc *LinUserCreate) defaults() { v := linuser.DefaultUpdateTime() luc.mutation.SetUpdateTime(v) } - if _, ok := luc.mutation.DeleteTime(); !ok { - v := linuser.DefaultDeleteTime() - luc.mutation.SetDeleteTime(v) - } if _, ok := luc.mutation.Avatar(); !ok { v := linuser.DefaultAvatar luc.mutation.SetAvatar(v) @@ -223,9 +219,6 @@ func (luc *LinUserCreate) check() error { if _, ok := luc.mutation.UpdateTime(); !ok { return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} } - if _, ok := luc.mutation.DeleteTime(); !ok { - return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} - } if _, ok := luc.mutation.Username(); !ok { return &ValidationError{Name: "username", err: errors.New(`model: missing required field "username"`)} } diff --git a/internal/data/model/linuser_update.go b/internal/data/model/linuser_update.go index be3c6fb..59b46bd 100644 --- a/internal/data/model/linuser_update.go +++ b/internal/data/model/linuser_update.go @@ -49,6 +49,12 @@ func (luu *LinUserUpdate) SetNillableDeleteTime(t *time.Time) *LinUserUpdate { return luu } +// ClearDeleteTime clears the value of the "delete_time" field. +func (luu *LinUserUpdate) ClearDeleteTime() *LinUserUpdate { + luu.mutation.ClearDeleteTime() + return luu +} + // SetUsername sets the "username" field. func (luu *LinUserUpdate) SetUsername(s string) *LinUserUpdate { luu.mutation.SetUsername(s) @@ -253,6 +259,12 @@ func (luu *LinUserUpdate) sqlSave(ctx context.Context) (n int, err error) { Column: linuser.FieldDeleteTime, }) } + if luu.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: linuser.FieldDeleteTime, + }) + } if value, ok := luu.mutation.Username(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -428,6 +440,12 @@ func (luuo *LinUserUpdateOne) SetNillableDeleteTime(t *time.Time) *LinUserUpdate return luuo } +// ClearDeleteTime clears the value of the "delete_time" field. +func (luuo *LinUserUpdateOne) ClearDeleteTime() *LinUserUpdateOne { + luuo.mutation.ClearDeleteTime() + return luuo +} + // SetUsername sets the "username" field. func (luuo *LinUserUpdateOne) SetUsername(s string) *LinUserUpdateOne { luuo.mutation.SetUsername(s) @@ -656,6 +674,12 @@ func (luuo *LinUserUpdateOne) sqlSave(ctx context.Context) (_node *LinUser, err Column: linuser.FieldDeleteTime, }) } + if luuo.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: linuser.FieldDeleteTime, + }) + } if value, ok := luuo.mutation.Username(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, diff --git a/internal/data/model/linuseridentiy/linuseridentiy.go b/internal/data/model/linuseridentiy/linuseridentiy.go index 066aa4f..68522b1 100644 --- a/internal/data/model/linuseridentiy/linuseridentiy.go +++ b/internal/data/model/linuseridentiy/linuseridentiy.go @@ -69,6 +69,4 @@ var ( DefaultUpdateTime func() time.Time // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. UpdateDefaultUpdateTime func() time.Time - // DefaultDeleteTime holds the default value on creation for the "delete_time" field. - DefaultDeleteTime func() time.Time ) diff --git a/internal/data/model/linuseridentiy/where.go b/internal/data/model/linuseridentiy/where.go index 3e14fad..1878b0f 100644 --- a/internal/data/model/linuseridentiy/where.go +++ b/internal/data/model/linuseridentiy/where.go @@ -369,6 +369,20 @@ func DeleteTimeLTE(v time.Time) predicate.LinUserIdentiy { }) } +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDeleteTime))) + }) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.LinUserIdentiy { + return predicate.LinUserIdentiy(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDeleteTime))) + }) +} + // UserIDEQ applies the EQ predicate on the "user_id" field. func UserIDEQ(v int) predicate.LinUserIdentiy { return predicate.LinUserIdentiy(func(s *sql.Selector) { diff --git a/internal/data/model/linuseridentiy_create.go b/internal/data/model/linuseridentiy_create.go index 2f3aac2..eaeaac5 100644 --- a/internal/data/model/linuseridentiy_create.go +++ b/internal/data/model/linuseridentiy_create.go @@ -165,10 +165,6 @@ func (luic *LinUserIdentiyCreate) defaults() { v := linuseridentiy.DefaultUpdateTime() luic.mutation.SetUpdateTime(v) } - if _, ok := luic.mutation.DeleteTime(); !ok { - v := linuseridentiy.DefaultDeleteTime() - luic.mutation.SetDeleteTime(v) - } } // check runs all checks and user-defined validators on the builder. @@ -179,9 +175,6 @@ func (luic *LinUserIdentiyCreate) check() error { if _, ok := luic.mutation.UpdateTime(); !ok { return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} } - if _, ok := luic.mutation.DeleteTime(); !ok { - return &ValidationError{Name: "delete_time", err: errors.New(`model: missing required field "delete_time"`)} - } if _, ok := luic.mutation.UserID(); !ok { return &ValidationError{Name: "user_id", err: errors.New(`model: missing required field "user_id"`)} } diff --git a/internal/data/model/linuseridentiy_update.go b/internal/data/model/linuseridentiy_update.go index 6033b6b..cbe9d84 100644 --- a/internal/data/model/linuseridentiy_update.go +++ b/internal/data/model/linuseridentiy_update.go @@ -47,6 +47,12 @@ func (luiu *LinUserIdentiyUpdate) SetNillableDeleteTime(t *time.Time) *LinUserId return luiu } +// ClearDeleteTime clears the value of the "delete_time" field. +func (luiu *LinUserIdentiyUpdate) ClearDeleteTime() *LinUserIdentiyUpdate { + luiu.mutation.ClearDeleteTime() + return luiu +} + // SetUserID sets the "user_id" field. func (luiu *LinUserIdentiyUpdate) SetUserID(i int) *LinUserIdentiyUpdate { luiu.mutation.ResetUserID() @@ -178,6 +184,12 @@ func (luiu *LinUserIdentiyUpdate) sqlSave(ctx context.Context) (n int, err error Column: linuseridentiy.FieldDeleteTime, }) } + if luiu.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: linuseridentiy.FieldDeleteTime, + }) + } if value, ok := luiu.mutation.UserID(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt, @@ -252,6 +264,12 @@ func (luiuo *LinUserIdentiyUpdateOne) SetNillableDeleteTime(t *time.Time) *LinUs return luiuo } +// ClearDeleteTime clears the value of the "delete_time" field. +func (luiuo *LinUserIdentiyUpdateOne) ClearDeleteTime() *LinUserIdentiyUpdateOne { + luiuo.mutation.ClearDeleteTime() + return luiuo +} + // SetUserID sets the "user_id" field. func (luiuo *LinUserIdentiyUpdateOne) SetUserID(i int) *LinUserIdentiyUpdateOne { luiuo.mutation.ResetUserID() @@ -407,6 +425,12 @@ func (luiuo *LinUserIdentiyUpdateOne) sqlSave(ctx context.Context) (_node *LinUs Column: linuseridentiy.FieldDeleteTime, }) } + if luiuo.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: linuseridentiy.FieldDeleteTime, + }) + } if value, ok := luiuo.mutation.UserID(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt, diff --git a/internal/data/model/migrate/schema.go b/internal/data/model/migrate/schema.go index d1b25a0..6bf8529 100644 --- a/internal/data/model/migrate/schema.go +++ b/internal/data/model/migrate/schema.go @@ -44,7 +44,7 @@ var ( {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "create_time", Type: field.TypeTime}, {Name: "update_time", Type: field.TypeTime}, - {Name: "delete_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime, Nullable: true}, {Name: "name", Type: field.TypeString, Unique: true}, {Name: "info", Type: field.TypeString}, {Name: "level", Type: field.TypeInt8}, @@ -60,7 +60,7 @@ var ( {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "create_time", Type: field.TypeTime}, {Name: "update_time", Type: field.TypeTime}, - {Name: "delete_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime, Nullable: true}, {Name: "message", Type: field.TypeString}, {Name: "user_id", Type: field.TypeInt}, {Name: "username", Type: field.TypeString}, @@ -93,7 +93,7 @@ var ( {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "create_time", Type: field.TypeTime}, {Name: "update_time", Type: field.TypeTime}, - {Name: "delete_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime, Nullable: true}, {Name: "username", Type: field.TypeString, Unique: true}, {Name: "nickname", Type: field.TypeString}, {Name: "avatar", Type: field.TypeString, Default: ""}, @@ -110,7 +110,7 @@ var ( {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "create_time", Type: field.TypeTime}, {Name: "update_time", Type: field.TypeTime}, - {Name: "delete_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime, Nullable: true}, {Name: "user_id", Type: field.TypeInt}, {Name: "identity_type", Type: field.TypeString}, {Name: "identifier", Type: field.TypeString}, diff --git a/internal/data/model/mutation.go b/internal/data/model/mutation.go index 24559b9..d44077d 100644 --- a/internal/data/model/mutation.go +++ b/internal/data/model/mutation.go @@ -1329,9 +1329,22 @@ func (m *LinGroupMutation) OldDeleteTime(ctx context.Context) (v time.Time, err return oldValue.DeleteTime, nil } +// ClearDeleteTime clears the value of the "delete_time" field. +func (m *LinGroupMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[lingroup.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *LinGroupMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[lingroup.FieldDeleteTime] + return ok +} + // ResetDeleteTime resets all changes to the "delete_time" field. func (m *LinGroupMutation) ResetDeleteTime() { m.delete_time = nil + delete(m.clearedFields, lingroup.FieldDeleteTime) } // SetName sets the "name" field. @@ -1744,7 +1757,11 @@ func (m *LinGroupMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *LinGroupMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(lingroup.FieldDeleteTime) { + fields = append(fields, lingroup.FieldDeleteTime) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -1757,6 +1774,11 @@ func (m *LinGroupMutation) 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 *LinGroupMutation) ClearField(name string) error { + switch name { + case lingroup.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } return fmt.Errorf("unknown LinGroup nullable field %s", name) } @@ -2102,9 +2124,22 @@ func (m *LinLogMutation) OldDeleteTime(ctx context.Context) (v time.Time, err er return oldValue.DeleteTime, nil } +// ClearDeleteTime clears the value of the "delete_time" field. +func (m *LinLogMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[linlog.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *LinLogMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[linlog.FieldDeleteTime] + return ok +} + // ResetDeleteTime resets all changes to the "delete_time" field. func (m *LinLogMutation) ResetDeleteTime() { m.delete_time = nil + delete(m.clearedFields, linlog.FieldDeleteTime) } // SetMessage sets the "message" field. @@ -2641,7 +2676,11 @@ func (m *LinLogMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *LinLogMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(linlog.FieldDeleteTime) { + fields = append(fields, linlog.FieldDeleteTime) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -2654,6 +2693,11 @@ func (m *LinLogMutation) 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 *LinLogMutation) ClearField(name string) error { + switch name { + case linlog.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } return fmt.Errorf("unknown LinLog nullable field %s", name) } @@ -3479,9 +3523,22 @@ func (m *LinUserMutation) OldDeleteTime(ctx context.Context) (v time.Time, err e return oldValue.DeleteTime, nil } +// ClearDeleteTime clears the value of the "delete_time" field. +func (m *LinUserMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[linuser.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *LinUserMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[linuser.FieldDeleteTime] + return ok +} + // ResetDeleteTime resets all changes to the "delete_time" field. func (m *LinUserMutation) ResetDeleteTime() { m.delete_time = nil + delete(m.clearedFields, linuser.FieldDeleteTime) } // SetUsername sets the "username" field. @@ -3909,7 +3966,11 @@ func (m *LinUserMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *LinUserMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(linuser.FieldDeleteTime) { + fields = append(fields, linuser.FieldDeleteTime) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -3922,6 +3983,11 @@ func (m *LinUserMutation) 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 *LinUserMutation) ClearField(name string) error { + switch name { + case linuser.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } return fmt.Errorf("unknown LinUser nullable field %s", name) } @@ -4266,9 +4332,22 @@ func (m *LinUserIdentiyMutation) OldDeleteTime(ctx context.Context) (v time.Time return oldValue.DeleteTime, nil } +// ClearDeleteTime clears the value of the "delete_time" field. +func (m *LinUserIdentiyMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[linuseridentiy.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *LinUserIdentiyMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[linuseridentiy.FieldDeleteTime] + return ok +} + // ResetDeleteTime resets all changes to the "delete_time" field. func (m *LinUserIdentiyMutation) ResetDeleteTime() { m.delete_time = nil + delete(m.clearedFields, linuseridentiy.FieldDeleteTime) } // SetUserID sets the "user_id" field. @@ -4623,7 +4702,11 @@ func (m *LinUserIdentiyMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *LinUserIdentiyMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(linuseridentiy.FieldDeleteTime) { + fields = append(fields, linuseridentiy.FieldDeleteTime) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -4636,6 +4719,11 @@ func (m *LinUserIdentiyMutation) 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 *LinUserIdentiyMutation) ClearField(name string) error { + switch name { + case linuseridentiy.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } return fmt.Errorf("unknown LinUserIdentiy nullable field %s", name) } diff --git a/internal/data/model/runtime.go b/internal/data/model/runtime.go index fbd3038..58d3b54 100644 --- a/internal/data/model/runtime.go +++ b/internal/data/model/runtime.go @@ -30,10 +30,6 @@ func init() { lingroup.DefaultUpdateTime = lingroupDescUpdateTime.Default.(func() time.Time) // lingroup.UpdateDefaultUpdateTime holds the default value on update for the update_time field. lingroup.UpdateDefaultUpdateTime = lingroupDescUpdateTime.UpdateDefault.(func() time.Time) - // lingroupDescDeleteTime is the schema descriptor for delete_time field. - lingroupDescDeleteTime := lingroupMixinFields0[2].Descriptor() - // lingroup.DefaultDeleteTime holds the default value on creation for the delete_time field. - lingroup.DefaultDeleteTime = lingroupDescDeleteTime.Default.(func() time.Time) linlogMixin := schema.LinLog{}.Mixin() linlogMixinFields0 := linlogMixin[0].Fields() _ = linlogMixinFields0 @@ -49,10 +45,6 @@ func init() { linlog.DefaultUpdateTime = linlogDescUpdateTime.Default.(func() time.Time) // linlog.UpdateDefaultUpdateTime holds the default value on update for the update_time field. linlog.UpdateDefaultUpdateTime = linlogDescUpdateTime.UpdateDefault.(func() time.Time) - // linlogDescDeleteTime is the schema descriptor for delete_time field. - linlogDescDeleteTime := linlogMixinFields0[2].Descriptor() - // linlog.DefaultDeleteTime holds the default value on creation for the delete_time field. - linlog.DefaultDeleteTime = linlogDescDeleteTime.Default.(func() time.Time) linuserMixin := schema.LinUser{}.Mixin() linuserMixinFields0 := linuserMixin[0].Fields() _ = linuserMixinFields0 @@ -68,10 +60,6 @@ func init() { linuser.DefaultUpdateTime = linuserDescUpdateTime.Default.(func() time.Time) // linuser.UpdateDefaultUpdateTime holds the default value on update for the update_time field. linuser.UpdateDefaultUpdateTime = linuserDescUpdateTime.UpdateDefault.(func() time.Time) - // linuserDescDeleteTime is the schema descriptor for delete_time field. - linuserDescDeleteTime := linuserMixinFields0[2].Descriptor() - // linuser.DefaultDeleteTime holds the default value on creation for the delete_time field. - linuser.DefaultDeleteTime = linuserDescDeleteTime.Default.(func() time.Time) // linuserDescAvatar is the schema descriptor for avatar field. linuserDescAvatar := linuserFields[2].Descriptor() // linuser.DefaultAvatar holds the default value on creation for the avatar field. @@ -91,8 +79,4 @@ func init() { linuseridentiy.DefaultUpdateTime = linuseridentiyDescUpdateTime.Default.(func() time.Time) // linuseridentiy.UpdateDefaultUpdateTime holds the default value on update for the update_time field. linuseridentiy.UpdateDefaultUpdateTime = linuseridentiyDescUpdateTime.UpdateDefault.(func() time.Time) - // linuseridentiyDescDeleteTime is the schema descriptor for delete_time field. - linuseridentiyDescDeleteTime := linuseridentiyMixinFields0[2].Descriptor() - // linuseridentiy.DefaultDeleteTime holds the default value on creation for the delete_time field. - linuseridentiy.DefaultDeleteTime = linuseridentiyDescDeleteTime.Default.(func() time.Time) } diff --git a/internal/server/http.go b/internal/server/http.go deleted file mode 100644 index 5467242..0000000 --- a/internal/server/http.go +++ /dev/null @@ -1,33 +0,0 @@ -package server - -import ( - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/logger" - "github.com/gofiber/fiber/v2/middleware/recover" - "lin-cms-go/internal/conf" -) - -func NewHTTPServer(c *conf.Server) *fiber.App { - app := fiber.New() - app.Use(logger.New(), recover.New()) - return app -} - -//func httpListen() { -// if err := HttpSrvHandler.ListenAndServe(); err != nil { -// log.Fatalf(" [ERROR] HttpServerRun:%s err:%v\n", port, err) -// } -//} -//func httpsListen() { -// if err := HttpSrvHandler.ListenAndServeTLS("storage/cert.pem", "storage/key.pem"); err != nil { -// log.Fatalf(" [ERROR] HttpServerRun:%s err:%v\n", port, err) -// } -//} -//func HttpServerStop() { -// ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) -// defer cancel() -// if err := HttpSrvHandler.Shutdown(ctx); err != nil { -// log.Fatalf(" [ERROR] HttpServerStop err:%v\n", err) -// } -// log.Printf(" [INFO] HttpServerStop stopped\n") -//} diff --git a/internal/server/middleware.go b/internal/server/middleware.go new file mode 100644 index 0000000..b7056b0 --- /dev/null +++ b/internal/server/middleware.go @@ -0,0 +1,22 @@ +package server + +import ( + "github.com/gofiber/fiber/v2" + "lin-cms-go/internal/biz" + "lin-cms-go/internal/data" +) + +func UserLog(c *fiber.Ctx) error { + + c.Next() + + user := biz.LocalUser(c) + + msg := c.Locals("logMessage") + if msg == nil { + return nil + } + err := data.CreateLog(c.Context(), c.Response().StatusCode(), user.ID, user.Username, user.Username+msg.(string), c.Method(), c.Path(), "") + + return err +} diff --git a/main.go b/main.go index 9830151..ba7def7 100644 --- a/main.go +++ b/main.go @@ -4,7 +4,6 @@ import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/logger" - "github.com/gofiber/fiber/v2/middleware/recover" log "github.com/grestful/logs" "gopkg.in/yaml.v2" "io/ioutil" @@ -12,7 +11,6 @@ import ( "lin-cms-go/internal/data" "lin-cms-go/internal/server" "lin-cms-go/pkg/core" - "os" ) func errorHandler(c *fiber.Ctx, err error) error { @@ -21,7 +19,6 @@ func errorHandler(c *fiber.Ctx, err error) error { if e.Err == nil { return e.HandleHttpError(c) } - } return core.HandleServerError(c, err) @@ -41,11 +38,9 @@ func initLog(c *conf.Config) { } func initApp(c *conf.Config) *fiber.App { app := fiber.New(fiber.Config{ErrorHandler: errorHandler}) - w, _ := os.Create(c.Log.Path + "/access.log") - app.Use(logger.New(logger.Config{ - TimeFormat: "2006-01-02 15:04:05.000", Format: "[${time}] ${method} ${path} - ${status} ${latency} \n ${body} \n ${resBody} \n ${error}", Output: w, - })) - app.Use(recover.New(), cors.New()) + + app.Use(logger.New()) + app.Use(cors.New(), server.UserLog) initLog(c) data.NewDataSource(&c.Data) //TODO clean source @@ -69,5 +64,5 @@ func main() { app := initApp(c) app.Listen(c.Server.Http.Addr) - + } From ee61343f53e725baae5bccc63c3f183c218c224f Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 11 Nov 2021 14:24:31 +0800 Subject: [PATCH 34/44] refactor move core/utils --- api/admin.go | 4 +- api/book.go | 4 +- api/group.go | 4 +- api/log.go | 2 +- api/permission.go | 2 +- api/user.go | 3 +- go.mod | 17 +- go.sum | 90 +++---- internal/biz/biz.go | 2 +- internal/biz/book.go | 2 +- internal/biz/group.go | 2 +- internal/biz/log.go | 2 +- internal/biz/user.go | 4 +- internal/data/init.go | 2 +- internal/server/server.go | 1 - main.go | 2 +- pkg/core/README.md | 44 ---- pkg/core/page.go | 43 ---- pkg/core/response.go | 128 ---------- pkg/core/validate.go | 42 ---- pkg/lib/upload.go | 11 +- pkg/utils/convert.go | 508 -------------------------------------- pkg/utils/crypt.go | 65 ----- pkg/utils/file.go | 34 --- pkg/utils/json.go | 37 --- pkg/utils/random.go | 65 ----- pkg/utils/slice.go | 10 - pkg/utils/string.go | 98 -------- pkg/utils/time.go | 32 --- test/helper.go | 2 +- test/user_test.go | 74 ++++-- 31 files changed, 128 insertions(+), 1208 deletions(-) delete mode 100644 internal/server/server.go delete mode 100644 pkg/core/README.md delete mode 100644 pkg/core/page.go delete mode 100644 pkg/core/response.go delete mode 100644 pkg/core/validate.go delete mode 100644 pkg/utils/convert.go delete mode 100644 pkg/utils/crypt.go delete mode 100644 pkg/utils/file.go delete mode 100644 pkg/utils/json.go delete mode 100644 pkg/utils/random.go delete mode 100644 pkg/utils/slice.go delete mode 100644 pkg/utils/string.go delete mode 100644 pkg/utils/time.go diff --git a/api/admin.go b/api/admin.go index e1cdf36..96fac54 100644 --- a/api/admin.go +++ b/api/admin.go @@ -2,10 +2,10 @@ package api import ( "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" + "github.com/xushuhui/goal/utils" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" - "lin-cms-go/pkg/utils" ) func GetUsers(c *fiber.Ctx) error { diff --git a/api/book.go b/api/book.go index 88d77ee..ae2e7ec 100644 --- a/api/book.go +++ b/api/book.go @@ -2,10 +2,10 @@ package api import ( "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" + "github.com/xushuhui/goal/utils" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" - "lin-cms-go/pkg/utils" ) func GetBooks(c *fiber.Ctx) error { diff --git a/api/group.go b/api/group.go index 86c862e..ed5b05a 100644 --- a/api/group.go +++ b/api/group.go @@ -2,10 +2,10 @@ package api import ( "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" + "github.com/xushuhui/goal/utils" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" - "lin-cms-go/pkg/utils" ) func GetGroups(c *fiber.Ctx) error { diff --git a/api/log.go b/api/log.go index 0d59344..34a3e95 100644 --- a/api/log.go +++ b/api/log.go @@ -2,9 +2,9 @@ package api import ( "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" ) func Upload(c *fiber.Ctx) error { diff --git a/api/permission.go b/api/permission.go index 0648106..7c3897c 100644 --- a/api/permission.go +++ b/api/permission.go @@ -2,9 +2,9 @@ package api import ( "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" ) func GetAllPermissions(c *fiber.Ctx) error { diff --git a/api/user.go b/api/user.go index cc9b85b..9a31748 100644 --- a/api/user.go +++ b/api/user.go @@ -1,14 +1,13 @@ package api import ( + "github.com/xushuhui/goal/core" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" "github.com/gofiber/fiber/v2" ) - func Hello(ctx *fiber.Ctx) error { return ctx.JSON("Hello") } diff --git a/go.mod b/go.mod index d6c4ed3..a436bbf 100644 --- a/go.mod +++ b/go.mod @@ -4,17 +4,20 @@ go 1.14 require ( entgo.io/ent v0.9.1 - github.com/go-playground/locales v0.13.0 - github.com/go-playground/universal-translator v0.17.0 - github.com/go-playground/validator/v10 v10.2.0 + github.com/andybalholm/brotli v1.0.3 // indirect + github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae - github.com/gofiber/fiber/v2 v2.20.2 - github.com/gofiber/jwt/v3 v3.1.2 + github.com/gofiber/fiber/v2 v2.21.0 github.com/golang-jwt/jwt/v4 v4.1.0 github.com/grestful/logs v1.0.7 - github.com/pkg/errors v0.8.1 + github.com/klauspost/compress v1.13.5 // indirect + github.com/pkg/errors v0.9.1 + github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/stretchr/testify v1.7.0 - golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a + github.com/xushuhui/goal v0.0.0-20211111060939-51802987d271 + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 + golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect + golang.org/x/text v0.3.7 // indirect gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index 25b5195..e4550de 100644 --- a/go.sum +++ b/go.sum @@ -20,8 +20,9 @@ github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/andybalholm/brotli v1.0.2 h1:JKnhI/XQ75uFBTiuzXpzFrUriDPiZjlOSzh6wXogP0E= github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/andybalholm/brotli v1.0.3 h1:fpcw+r1N1h0Poc1F/pHbW40cUm/lMEQslZtCkBQ0UnM= +github.com/andybalholm/brotli v1.0.3/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= @@ -39,6 +40,7 @@ github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3Ee github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -56,25 +58,20 @@ github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9 github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= -github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= +github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= +github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= +github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= +github.com/go-playground/validator/v10 v10.9.0 h1:NgTtmN58D0m8+UuxtYmGztBJB7VnPgjj221I1QHci2A= +github.com/go-playground/validator/v10 v10.9.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae h1:L6V0ANsMIMdLgXly241UXhXNFWYgXbgjHupTAAURrV0= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gofiber/fiber/v2 v2.20.1 h1:p463gd/RI8YeYxP4WMGS+u1UtBS88yk8oLiPkEiDYx4= -github.com/gofiber/fiber/v2 v2.20.1/go.mod h1:/LdZHMUXZvTTo7gU4+b1hclqCAdoQphNQ9bi9gutPyI= -github.com/gofiber/fiber/v2 v2.20.2 h1:dqizbjO1pCmH6K+b+kBk7TCJK4rmgjJXvX8/MZDbK60= -github.com/gofiber/fiber/v2 v2.20.2/go.mod h1:/LdZHMUXZvTTo7gU4+b1hclqCAdoQphNQ9bi9gutPyI= -github.com/gofiber/jwt/v3 v3.1.2 h1:Gsp1BgkUWo3ZbZZSSBJs+IVE1t89m1n/pOe0P9sIG/c= -github.com/gofiber/jwt/v3 v3.1.2/go.mod h1:Z05kGvvdRqbWMvb3uYmAPwfFyCV8/n/QVorzq4XjwvU= +github.com/gofiber/fiber/v2 v2.21.0 h1:tdRNrgqWqcHWBwE3o51oAleEVsil4Ro02zd2vMEuP4Q= +github.com/gofiber/fiber/v2 v2.21.0/go.mod h1:MR1usVH3JHYRyQwMe2eZXRSZHRX38fkV+A7CPB+DlDQ= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/golang-jwt/jwt/v4 v4.1.0 h1:XUgk2Ex5veyVFVeLm0xhusUTQybEbexJXrvPNOKkSY0= @@ -94,7 +91,6 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -104,7 +100,6 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3 h1:x95R7cp+rSeeqAMI2knLtQ0DKlaBhv2NrtrOvafPHRo= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= @@ -143,34 +138,37 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.13.4 h1:0zhec2I8zGnjWcKyLl6i3gPqKANCCn5e9xmviEEeX6s= github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/klauspost/compress v1.13.5 h1:9O69jUPDcsT9fEm74W92rZL9FQY7rCdaXVneq+yyzl4= +github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -190,13 +188,14 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= @@ -212,6 +211,10 @@ github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7z github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 h1:Ha8xCaq6ln1a+R91Km45Oq6lPXj2Mla6CRJYcuV2h1w= +github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= @@ -223,11 +226,9 @@ github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4k github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -235,7 +236,6 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -245,21 +245,20 @@ github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07 h1:d/VUIMNTk65Xz69ht github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07/go.mod h1:FbXpUxsx5in7z/OrWFDdhYetOy3/VGIJsVHN9G7RUPA= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.29.0 h1:F5GKpytwFk5OhCuRh6H+d4vZAcEeNAwPTdwQnm6IERY= -github.com/valyala/fasthttp v1.29.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= +github.com/valyala/fasthttp v1.31.0 h1:lrauRLII19afgCs2fnWRJ4M5IkV0lo2FqA61uGkNBfE= +github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xushuhui/goal v0.0.0-20211111060939-51802987d271 h1:pHGbLxUfGwchgvTYd6/wTn1HLkVzjf/2H+2LR2olVBQ= +github.com/xushuhui/goal v0.0.0-20211111060939-51802987d271/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= @@ -268,8 +267,10 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a h1:kr2P4QFmQr29mSLA43kwrOcgcReGTfbE9N577tCTuBc= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -283,13 +284,11 @@ golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -308,7 +307,6 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210510120150-4163338589ed h1:p9UgmWI9wKpfYmgaV/IZKGdXc5qEK45tDwwwDyjS26I= golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -338,15 +336,19 @@ golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ= +golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -369,12 +371,10 @@ golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= @@ -410,23 +410,23 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/internal/biz/biz.go b/internal/biz/biz.go index a7a73f0..c81785e 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -3,8 +3,8 @@ package biz import ( "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v4" + "github.com/xushuhui/goal/utils" "lin-cms-go/internal/data/model" - "lin-cms-go/pkg/utils" ) func LocalUser(c *fiber.Ctx) (user model.LinUser) { diff --git a/internal/biz/book.go b/internal/biz/book.go index 69be703..ee78f98 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -2,10 +2,10 @@ package biz import ( "context" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" "lin-cms-go/pkg/errcode" ) diff --git a/internal/biz/group.go b/internal/biz/group.go index 114edfd..db7250c 100644 --- a/internal/biz/group.go +++ b/internal/biz/group.go @@ -2,10 +2,10 @@ package biz import ( "context" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" "lin-cms-go/pkg/enum" "lin-cms-go/pkg/errcode" ) diff --git a/internal/biz/log.go b/internal/biz/log.go index f416522..d6a4f34 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -2,12 +2,12 @@ package biz import ( "context" + "github.com/xushuhui/goal/utils" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/linlog" "lin-cms-go/internal/data/model/predicate" "lin-cms-go/internal/request" - "lin-cms-go/pkg/utils" ) func GetLogs(ctx context.Context, req request.GetLogs, page int, size int) (res interface{}, total int, err error) { diff --git a/internal/biz/user.go b/internal/biz/user.go index 9313b1c..8e238ec 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -6,8 +6,8 @@ import ( "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" "lin-cms-go/pkg/errcode" "lin-cms-go/pkg/lib" "time" @@ -125,9 +125,11 @@ func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, //data["permissions"] = permissions return } + type LinUser struct { model.LinUser } + func GetMyInfomation(ctx context.Context, uid int) (res LinUser, err error) { usermodel, err := data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { diff --git a/internal/data/init.go b/internal/data/init.go index b6f3c0d..f1e5a28 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -5,8 +5,8 @@ import ( "github.com/pkg/errors" "lin-cms-go/internal/conf" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/data/model" - "lin-cms-go/pkg/core" "sync" _ "github.com/go-sql-driver/mysql" diff --git a/internal/server/server.go b/internal/server/server.go deleted file mode 100644 index abb4e43..0000000 --- a/internal/server/server.go +++ /dev/null @@ -1 +0,0 @@ -package server diff --git a/main.go b/main.go index ba7def7..23fcbc6 100644 --- a/main.go +++ b/main.go @@ -5,12 +5,12 @@ import ( "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/logger" log "github.com/grestful/logs" + "github.com/xushuhui/goal/core" "gopkg.in/yaml.v2" "io/ioutil" "lin-cms-go/internal/conf" "lin-cms-go/internal/data" "lin-cms-go/internal/server" - "lin-cms-go/pkg/core" ) func errorHandler(c *fiber.Ctx, err error) error { diff --git a/pkg/core/README.md b/pkg/core/README.md deleted file mode 100644 index 4fa8c73..0000000 --- a/pkg/core/README.md +++ /dev/null @@ -1,44 +0,0 @@ - -gin 验证 -```go - v, ok := binding.Validator.Engine().(*validator.Validate) - if ok { - // 注册一个获取json tag的自定义方法 - //v.RegisterTagNameFunc(jsonTag) - // 验证器注册翻译器 - e = zhtranslations.RegisterDefaultTranslations(v, trans) - if e != nil { - return - } - - // 自定义验证方法 - e = v.RegisterValidation("mobile", mobileValidate) - if e != nil { - return - } - e = v.RegisterTranslation("mobile", trans, mobileRegister, mobileTranslation) - if e != nil { - return - } - - } -``` - -自定义验证 - -```go -func mobileValidate(fl validator.FieldLevel) bool { - mobile := fl.Field().String() - re := `^1[3456789]\d{9}$` - r := regexp.MustCompile(re) - return r.MatchString(mobile) - -} -func mobileRegister(ut ut.Translator) error { - return ut.Add("mobile", "{0}填写不正确哦", true) -} -func mobileTranslation(ut ut.Translator, fe validator.FieldError) string { - t, _ := ut.T("mobile", fe.Field()) - return t -} -``` \ No newline at end of file diff --git a/pkg/core/page.go b/pkg/core/page.go deleted file mode 100644 index dd35ae2..0000000 --- a/pkg/core/page.go +++ /dev/null @@ -1,43 +0,0 @@ -package core - -import ( - "github.com/gofiber/fiber/v2" - "lin-cms-go/pkg/utils" -) - -type Pager struct { - Items interface{} `json:"items"` - // 页码 - Page int `json:"page"` - // 每页数量 - Size int `json:"size"` - // 总行数 - Total int `json:"total"` - TotalPage int `json:"total_page"` -} - -func GetPage(c *fiber.Ctx) int { - page, _ := utils.StringToInt(c.Query("page")) - if page <= 0 { - return 1 - } - - return page -} - -func GetSize(c *fiber.Ctx) int { - pageSize, _ := utils.StringToInt(c.Query("count")) - if pageSize <= 0 { - return 10 - } - - return pageSize -} - -func GetPageOffset(page, pageSize int) int { - result := 0 - if page > 0 { - result = (page - 1) * pageSize - } - return result -} diff --git a/pkg/core/response.go b/pkg/core/response.go deleted file mode 100644 index 2c1c989..0000000 --- a/pkg/core/response.go +++ /dev/null @@ -1,128 +0,0 @@ -package core - -import ( - "fmt" - "github.com/go-playground/validator/v10" - "github.com/gofiber/fiber/v2" - "lin-cms-go/pkg/errcode" -) - -// Error 数据返回通用 JSON 数据结构 -type IError struct { - Code int `json:"code"` // 错误码 ((0: 成功,1: 失败,>1: 错误码)) - Message string `json:"message"` // 提示信息 - Data interface{} `json:"data"` // 返回数据 (业务接口定义具体数据结构) - Err error `json:"-"` -} -type HttpError struct { - IError - Status int -} - -func (err IError) Error() (re string) { - return fmt.Sprintf("code=%v, Message=%v,Err=%v", err.Code, err.Message, err.Err) -} - -func NewErrorCode(code int) (err error) { - err = HttpError{ - NewIError(code, errcode.GetMsg(code)), - fiber.StatusBadRequest, - } - return -} -func NewErrorMessage(code int, message string) (err error) { - err = HttpError{ - NewIError(code, message), - fiber.StatusBadRequest, - } - return -} -func NewInvalidParamsError(message string) (err error) { - return NewErrorMessage(errcode.InvalidParams, message) -} - -func ValidateRequest(obj interface{}) error { - - err := validate.Struct(obj) - - if err != nil { - s := Translate(err.(validator.ValidationErrors)) - return NewInvalidParamsError(s) - } - return nil -} -func ParseQuery(c *fiber.Ctx, request interface{}) (err error) { - err = c.QueryParser(request) - - if err != nil { - return err - } - - err = ValidateRequest(request) - return -} -func ParseRequest(c *fiber.Ctx, request interface{}) (err error) { - err = c.BodyParser(request) - - if err != nil { - return err - } - err = ValidateRequest(request) - return -} - -func NewIError(code int, message string) IError { - return IError{ - Code: code, - Message: message, - } -} - -func NotFoundError(code int) error { - - return HttpError{ - NewIError(code, errcode.GetMsg(code)), - fiber.StatusNotFound, - } - -} -func SuccessResp(c *fiber.Ctx) error { - return c.JSON(IError{ - Code: 0, - Message: errcode.GetMsg(0), - }) -} -func SetData(c *fiber.Ctx, data interface{}) error { - return c.JSON(IError{ - Code: 0, - Message: errcode.GetMsg(0), - Data: data, - }) -} - -func SetPage(c *fiber.Ctx, list interface{}, totalRows int) error { - return c.JSON(IError{ - Code: 0, - Message: errcode.GetMsg(0), - Data: Pager{ - Page: GetPage(c), - Size: GetSize(c), - Total: totalRows, - Items: list, - }, - }) -} -func HandleServerError(c *fiber.Ctx, err error) error { - - return c.JSON(IError{ - Code: errcode.ServerError, - Message: errcode.GetMsg(errcode.ServerError), - Err: err, - }) -} -func (err *HttpError) HandleHttpError(c *fiber.Ctx) error { - - return c.Status(err.Status).JSON(IError{ - Code: err.Code, Message: err.Message, - }) -} diff --git a/pkg/core/validate.go b/pkg/core/validate.go deleted file mode 100644 index eb9f8d7..0000000 --- a/pkg/core/validate.go +++ /dev/null @@ -1,42 +0,0 @@ -package core - -import ( - zh2 "github.com/go-playground/locales/zh" - ut "github.com/go-playground/universal-translator" - "github.com/go-playground/validator/v10" - zhtranslations "github.com/go-playground/validator/v10/translations/zh" - "reflect" - "strings" -) - -var ( - validate *validator.Validate - trans ut.Translator -) - -func InitValidate() { - validate = validator.New() - // 中文翻译 - zh := zh2.New() - uni := ut.New(zh, zh) - trans, _ = uni.GetTranslator("zh") - e := zhtranslations.RegisterDefaultTranslations(validate, trans) - if e != nil { - panic(e) - } - validate.RegisterTagNameFunc(func(fld reflect.StructField) string { - return fld.Tag.Get("comment") - }) - - return -} - -func Translate(errs validator.ValidationErrors) string { - var errList []string - - for _, e := range errs { - // can translate each error one at a time. - errList = append(errList, e.Translate(trans)) - } - return strings.Join(errList, "|") -} diff --git a/pkg/lib/upload.go b/pkg/lib/upload.go index 51f63da..4eeb921 100644 --- a/pkg/lib/upload.go +++ b/pkg/lib/upload.go @@ -4,7 +4,6 @@ import ( "io" "io/ioutil" - "lin-cms-go/pkg/utils" "mime/multipart" "os" "path" @@ -21,7 +20,7 @@ const ( func GetFileName(name string) string { ext := GetFileExt(name) fileName := strings.TrimSuffix(name, ext) - fileName = utils.EncodeMD5(fileName) + //fileName = utils.EncodeMD5(fileName) return fileName + ext } @@ -29,14 +28,6 @@ func GetFileExt(name string) string { return path.Ext(name) } -func GetSavePath() string { - return "" -} - -func GetServerUrl() string { - return "" -} - func CheckSavePath(dst string) bool { _, err := os.Stat(dst) return os.IsNotExist(err) diff --git a/pkg/utils/convert.go b/pkg/utils/convert.go deleted file mode 100644 index 09441cb..0000000 --- a/pkg/utils/convert.go +++ /dev/null @@ -1,508 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "reflect" - "strconv" - "strings" -) - -//要求to必须已经分配好空间 -func Uint32ToBytes(from uint32) (to []byte) { - to = make([]byte, 4) - buffer := new(bytes.Buffer) - binary.Write(buffer, binary.BigEndian, from) - copy(to, buffer.Bytes()[0:4]) - return -} - -func BytesToUint32(from []byte) (to uint32) { - buffer := bytes.NewBuffer(from) - binary.Read(buffer, binary.BigEndian, &to) - return -} -func StringToInt(v string) (d int, err error) { - tmp, err := strconv.ParseInt(v, 10, 32) - if err != nil { - return - } - return int(tmp), err -} -func StringToUint(v string) (d uint, err error) { - tmp, err := strconv.ParseUint(v, 10, 32) - if err != nil { - return - } - return uint(tmp), err -} -func StringToUint32(v string) (d uint32, err error) { - tmp, err := strconv.ParseUint(v, 10, 32) - if err != nil { - return - } - return uint32(tmp), err -} -func StringToUint8(v string) (d uint8, err error) { - tmp, err := strconv.ParseUint(v, 10, 8) - if err != nil { - return - } - return uint8(tmp), err -} -func StringToUint64(v string) (d uint64, err error) { - d, err = strconv.ParseUint(v, 10, 64) - return -} - -func Uint64ToString(from uint64) (to string) { - to = strconv.FormatUint(from, 10) - return -} - -func Float64ToString(from float64) (to string) { - to = strconv.FormatFloat(from, 'f', -1, 64) - return -} -func StringToFloat(v string) (d float32, err error) { - tmp, err := strconv.ParseFloat(v, 10) - d = float32(tmp) - return -} -func StringToFloat64(v string) (d float64, err error) { - d, err = strconv.ParseFloat(v, 10) - return -} - -func StringToInt64(v string) (d int64, err error) { - d, err = strconv.ParseInt(v, 10, 64) - return -} - -func Int64ToString(from int64) (to string) { - to = strconv.FormatInt(from, 10) - return -} -func IntToString(from int) (to string) { - to = strconv.FormatInt(int64(from), 10) - return -} -func Uint32ToString(from uint32) (to string) { - to = strconv.FormatInt(int64(from), 10) - return -} - -func ToBool(v interface{}) (bool, error) { - switch value := v.(type) { - case bool: - return value, nil - case string: - switch value { - case "true", "True": - return true, nil - case "false", "False": - return false, nil - default: - return false, errors.New("cannot convert " + value + " to bool") - } - case float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - return value != 0, nil - - default: - return false, errors.New(fmt.Sprintf("cannot convert %v(%v) to bool", v, reflect.TypeOf(v))) - } -} -func ToFloat64(v interface{}) (float64, error) { - switch value := v.(type) { - case string: - return StringToFloat64(v.(string)) - case float32: - return float64(value), nil - case float64: - return value, nil - case int8: - return float64(value), nil - case int16: - return float64(value), nil - case int32: - return float64(value), nil - case int: - return float64(value), nil - case int64: - return float64(value), nil - case uint8: - return float64(value), nil - case uint16: - return float64(value), nil - case uint32: - return float64(value), nil - case uint: - return float64(value), nil - case uint64: - return float64(value), nil - case json.Number: - return value.Float64() - default: - return 0, errors.New(fmt.Sprintf("cannot convert %v(%v) to float64", v, reflect.TypeOf(v))) - } -} - -func ToInt64(v interface{}) (int64, error) { - switch value := v.(type) { - case string: - return StringToInt64(v.(string)) - case float32: - return int64(value), nil - case float64: - return int64(value), nil - case int8: - return int64(value), nil - case int16: - return int64(value), nil - case int32: - return int64(value), nil - case int: - return int64(value), nil - case int64: - return value, nil - case uint8: - return int64(value), nil - case uint16: - return int64(value), nil - case uint32: - return int64(value), nil - case uint: - return int64(value), nil - case uint64: - return int64(value), nil - case json.Number: - return value.Int64() - default: - return 0, errors.New(fmt.Sprintf("cannot convert %v(%v) to float64", v, reflect.TypeOf(v))) - } -} - -func ToUint8(v interface{}) (uint8, error) { - i, e := ToInt64(v) - return uint8(i), e -} -func ToUint16(v interface{}) (uint16, error) { - i, e := ToInt64(v) - return uint16(i), e -} -func ToUint32(v interface{}) (uint32, error) { - i, e := ToInt64(v) - return uint32(i), e -} -func ToUint(v interface{}) (uint, error) { - i, e := ToInt64(v) - return uint(i), e -} -func ToUint64(v interface{}) (uint64, error) { - i, e := ToInt64(v) - return uint64(i), e -} -func ToInt8(v interface{}) (int8, error) { - i, e := ToInt64(v) - return int8(i), e -} -func ToInt16(v interface{}) (int16, error) { - i, e := ToInt64(v) - return int16(i), e -} -func ToInt(v interface{}) (int, error) { - i, e := ToInt64(v) - return int(i), e -} -func ToInt32(v interface{}) (int32, error) { - i, e := ToInt64(v) - return int32(i), e -} - -func ToFloat32(v interface{}) (float32, error) { - i, e := ToFloat64(v) - return float32(i), e -} -func ToStringSlice(v interface{}) ([]string, error) { - switch slice := v.(type) { - case []string: - return slice, nil - case []interface{}: - r := make([]string, 0, len(slice)) - for _, item := range slice { - r = append(r, fmt.Sprintf("%v", item)) - } - return r, nil - case []uint64: - r := make([]string, 0, len(slice)) - for _, item := range slice { - r = append(r, fmt.Sprintf("%v", item)) - } - return r, nil - default: - return nil, errors.New(fmt.Sprintf("cannot convert %v(%v) to []string", v, reflect.TypeOf(v))) - } -} - -func ToUint32Slice(v interface{}) ([]uint32, error) { - switch slice := v.(type) { - case []uint32: - return slice, nil - case []float64: - r := make([]uint32, 0, len(slice)) - for _, item := range slice { - if i, e := ToUint32(item); e != nil { - return nil, e - } else { - r = append(r, i) - - } - // r = append(r, fmt.Sprintf("%v", item)) - } - return r, nil - case []string: - r := make([]uint32, 0, len(slice)) - for _, item := range slice { - if i, e := ToUint32(item); e != nil { - return nil, e - } else { - r = append(r, i) - } - // r = append(r, fmt.Sprintf("%v", item)) - } - return r, nil - case []interface{}: - r := make([]uint32, 0, len(slice)) - for _, item := range slice { - if i, e := ToUint32(item); e != nil { - return nil, e - } else { - r = append(r, i) - } - // r = append(r, fmt.Sprintf("%v", item)) - } - return r, nil - default: - return nil, errors.New(fmt.Sprintf("cannot convert %v(%v) to []string", v, reflect.TypeOf(v))) - } -} - -func ToUint64Slice(v interface{}) ([]uint64, error) { - switch slice := v.(type) { - case []uint64: - return slice, nil - case []float64: - r := make([]uint64, 0, len(slice)) - for _, item := range slice { - if i, e := ToUint64(item); e != nil { - return nil, e - } else { - r = append(r, i) - - } - // r = append(r, fmt.Sprintf("%v", item)) - } - return r, nil - case []string: - r := make([]uint64, 0, len(slice)) - for _, item := range slice { - if i, e := ToUint64(item); e != nil { - return nil, e - } else { - r = append(r, i) - } - } - return r, nil - case []interface{}: - r := make([]uint64, 0, len(slice)) - for _, item := range slice { - if i, e := ToUint64(item); e != nil { - return nil, e - } else { - r = append(r, i) - } - } - return r, nil - default: - return nil, errors.New(fmt.Sprintf("cannot convert %v(%v) to []string", v, reflect.TypeOf(v))) - } -} - -func ToInt64Slice(v interface{}) ([]int64, error) { - switch slice := v.(type) { - case []int64: - return slice, nil - case []float64: - r := make([]int64, 0, len(slice)) - for _, item := range slice { - if i, e := ToInt64(item); e != nil { - return nil, e - } else { - r = append(r, i) - - } - } - return r, nil - case []string: - r := make([]int64, 0, len(slice)) - for _, item := range slice { - if i, e := ToInt64(item); e != nil { - return nil, e - } else { - r = append(r, i) - } - } - return r, nil - case []interface{}: - r := make([]int64, 0, len(slice)) - for _, item := range slice { - if i, e := ToInt64(item); e != nil { - return nil, e - } else { - r = append(r, i) - } - } - return r, nil - default: - return nil, errors.New(fmt.Sprintf("cannot convert %v(%v) to []string", v, reflect.TypeOf(v))) - } -} - -func Join(v interface{}, sep string) (string, error) { - switch slice := v.(type) { - case []string: - return strings.Join(slice, sep), nil - case []uint32: - if len(slice) == 0 { - return "", nil - } - var buf bytes.Buffer - _, _ = fmt.Fprintf(&buf, "%v", slice[0]) - for i := 1; i < len(slice); i++ { - _, _ = fmt.Fprintf(&buf, "%s%v", sep, slice[i]) - } - return buf.String(), nil - case []uint64: - if len(slice) == 0 { - return "", nil - } - var buf bytes.Buffer - _, _ = fmt.Fprintf(&buf, "%v", slice[0]) - for i := 1; i < len(slice); i++ { - _, _ = fmt.Fprintf(&buf, "%s%v", sep, slice[i]) - } - return buf.String(), nil - case []interface{}: - if len(slice) == 0 { - return "", nil - } - var buf bytes.Buffer - _, _ = fmt.Fprintf(&buf, "%v", slice[0]) - for i := 1; i < len(slice); i++ { - _, _ = fmt.Fprintf(&buf, "%s%v", sep, slice[i]) - } - return buf.String(), nil - default: - return "", errors.New(fmt.Sprintf("cannot convert %v(%v) to Slice", v, reflect.TypeOf(v))) - } -} - -//结构->MAP -func Struct2Map(obj interface{}) map[string]interface{} { - t := reflect.TypeOf(obj) - if t.Kind() != reflect.Struct { - return nil - } - v := reflect.ValueOf(obj) - var data = make(map[string]interface{}) - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - name := f.Tag.Get("json") - if name == "" { - name = f.Name - } - data[t.Field(i).Name] = v.Field(i).Interface() - } - return data -} - -func Struct2MapJson(obj interface{}) map[string]interface{} { - t := reflect.TypeOf(obj) - if t.Kind() != reflect.Struct { - return nil - } - v := reflect.ValueOf(obj) - var data = make(map[string]interface{}) - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - name := f.Tag.Get("json") - if name == "" { - name = f.Name - } - data[t.Field(i).Tag.Get("json")] = v.Field(i).Interface() - } - return data -} - -func Bool2Int(b bool) int { - if b { - return 1 - } - return 0 -} - -func MakeKey(keys ...interface{}) string { - if len(keys) == 0 { - return "" - } - var buf bytes.Buffer - buf.WriteString(fmt.Sprintf("%v", keys[0])) - for i := 1; i < len(keys); i++ { - buf.WriteString(fmt.Sprintf("_%v", keys[i])) - } - return buf.String() -} - -func MakeKey2(keys ...interface{}) string { - if len(keys) == 0 { - return "" - } - var buf bytes.Buffer - buf.WriteString(fmt.Sprintf("%v", keys[0])) - for i := 1; i < len(keys); i++ { - buf.WriteString(fmt.Sprintf("|%v", keys[i])) - } - return buf.String() -} - -func SplitKey(key string) []string { - return strings.Split(key, "_") -} - -func SplitKey2(key string) []string { - return strings.Split(key, "|") -} - -func JSONMarshal(v interface{}, safeEncoding bool) ([]byte, error) { - b, err := json.Marshal(v) - if safeEncoding { - b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1) - b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1) - b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1) - } - return b, err -} - -func XmlMarshal(v interface{}, safeEncoding bool) ([]byte, error) { - b, err := xml.Marshal(v) - if safeEncoding { - b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1) - b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1) - b = bytes.Replace(b, []byte("&"), []byte("&"), -1) - } - return b, err -} diff --git a/pkg/utils/crypt.go b/pkg/utils/crypt.go deleted file mode 100644 index 1eaa60f..0000000 --- a/pkg/utils/crypt.go +++ /dev/null @@ -1,65 +0,0 @@ -package utils - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/md5" - "encoding/base64" - "encoding/hex" -) - -// 加密 aes_128_cbc -func AesEncrypt(encryptStr string, key []byte, iv string) (string, error) { - encryptBytes := []byte(encryptStr) - block, err := aes.NewCipher(key) - if err != nil { - return "", err - } - - blockSize := block.BlockSize() - encryptBytes = pkcs5Padding(encryptBytes, blockSize) - - blockMode := cipher.NewCBCEncrypter(block, []byte(iv)) - encrypted := make([]byte, len(encryptBytes)) - blockMode.CryptBlocks(encrypted, encryptBytes) - return base64.URLEncoding.EncodeToString(encrypted), nil -} - -// 解密 -func AesDecrypt(decryptStr string, key []byte, iv string) (string, error) { - decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr) - if err != nil { - return "", err - } - - block, err := aes.NewCipher(key) - if err != nil { - return "", err - } - - blockMode := cipher.NewCBCDecrypter(block, []byte(iv)) - decrypted := make([]byte, len(decryptBytes)) - - blockMode.CryptBlocks(decrypted, decryptBytes) - decrypted = pkcs5UnPadding(decrypted) - return string(decrypted), nil -} - -func pkcs5Padding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(cipherText, padText...) -} - -func pkcs5UnPadding(decrypted []byte) []byte { - length := len(decrypted) - unPadding := int(decrypted[length-1]) - return decrypted[:(length - unPadding)] -} -func EncodeMD5(value string) string { - m := md5.New() - m.Write([]byte(value)) - - return hex.EncodeToString(m.Sum(nil)) -} diff --git a/pkg/utils/file.go b/pkg/utils/file.go deleted file mode 100644 index 3feee8d..0000000 --- a/pkg/utils/file.go +++ /dev/null @@ -1,34 +0,0 @@ -package utils - -import "os" - -func PathExists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} -func CreateFile(fileName string) (f *os.File, err error) { - exist, e := PathExists(fileName) - if e != nil { - return - } - if exist == false { - f, e := os.Create(fileName) - if e != nil { - return f, e - } - } - f, e = os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0777) - if e != nil { - return - } - return -} -func LogDir(savePath string) string { - return savePath + "/" + GetCurrentDate() + "/" -} diff --git a/pkg/utils/json.go b/pkg/utils/json.go deleted file mode 100644 index 6b9199f..0000000 --- a/pkg/utils/json.go +++ /dev/null @@ -1,37 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/json" -) - -/// -/// Json序列化对象成[]byte -/// -/// 被序列化的对象 -/// 序列化后的字节数组 -func JSONEncode(v interface{}) ([]byte, error) { - buffer := &bytes.Buffer{} - - e := json.NewEncoder(buffer).Encode(v) - if e != nil { - return nil, e - } - byteSlice := buffer.Bytes() - - return byteSlice, nil -} - -/// -/// Json反序列化[]byte到对象,解决Marshal解码科学计数法的问题(float->科学计数法) -/// -/// 被反序列化的字节数组 -/// 被反序列化的对象,必须是对象指针 -/// -func JSONDecode(b []byte, v interface{}) (err error) { - d := json.NewDecoder(bytes.NewReader(b)) - d.UseNumber() - err = d.Decode(v) - - return -} diff --git a/pkg/utils/random.go b/pkg/utils/random.go deleted file mode 100644 index 224304a..0000000 --- a/pkg/utils/random.go +++ /dev/null @@ -1,65 +0,0 @@ -package utils - -import ( - "math/rand" - "time" -) - -var r = rand.New(rand.NewSource(time.Now().UnixNano())) - -func GetRandom(min, max int) int { - return rand.Intn(max-min) + min + 1 //r.Intn(max-min) + min + 1 -} - -func GetRandomMax(max int) int { - return GetRandom(0, max) - 1 -} - -const ( - KC_RAND_KIND_NUM = 0 // 纯数字 - KC_RAND_KIND_LOWER = 1 // 小写字母 - KC_RAND_KIND_UPPER = 2 // 大写字母 - KC_RAND_KIND_ALL = 3 // 数字、大小写字母 -) - -// 随机字符串 -func RandStrCommon(size int, kind int) []byte { - kinds, result := [][]int{{10, 48}, {26, 97}, {26, 65}}, make([]byte, size) - isAll := kind > 2 || kind < 0 - rand.Seed(time.Now().UnixNano()) - for i := 0; i < size; i++ { - if isAll { // random kind - kind = rand.Intn(3) - } - scope, base := kinds[kind][0], kinds[kind][1] - result[i] = uint8(base + rand.Intn(scope)) - } - return result -} - -func RandStr(size int) string { - kind := 3 - kinds, result := [][]int{{10, 48}, {26, 97}, {26, 65}}, make([]byte, size) - - rand.Seed(time.Now().UnixNano()) - for i := 0; i < size; i++ { - kind = rand.Intn(3) - scope, base := kinds[kind][0], kinds[kind][1] - result[i] = uint8(base + rand.Intn(scope)) - } - return string(result) -} -func RandInt(i int64) int64 { - if i == 0 { - return 0 - } - r := rand.New(rand.NewSource(time.Now().UnixNano())) - return r.Int63n(i) -} -func RandInt2(i int) int { - if i == 0 { - return 0 - } - r := rand.New(rand.NewSource(time.Now().UnixNano())) - return r.Intn(i) -} diff --git a/pkg/utils/slice.go b/pkg/utils/slice.go deleted file mode 100644 index 2169571..0000000 --- a/pkg/utils/slice.go +++ /dev/null @@ -1,10 +0,0 @@ -package utils - -func InArray(s []interface{}, element interface{}) bool { - for _, v := range s { - if v == element { - return true - } - } - return false -} diff --git a/pkg/utils/string.go b/pkg/utils/string.go deleted file mode 100644 index c2e1517..0000000 --- a/pkg/utils/string.go +++ /dev/null @@ -1,98 +0,0 @@ -package utils - -import ( - cr "crypto/rand" - "fmt" - "io" - "unicode/utf8" -) - -/* -字符串截取函数 - -参数: - str:带截取字符串 - begin:开始截取位置 - length:截取长度 -*/ -func SubString(str string, begin, length int) (substr string) { - // 将字符串的转换成[]rune - rs := []rune(str) - lth := len(rs) - // 简单的越界判断 - if begin < 0 { - begin = 0 - } - if begin >= lth { - begin = lth - } - end := begin + length - if end > lth { - end = lth - } - // 返回子串 - return string(rs[begin:end]) -} - -// 生成一个随机int64 - -func MinInt64(a, b int64) (r int64) { - if a > b { - r = b - } else { - r = a - } - return -} - -func MaxInt64(a, b int64) (r int64) { - if a > b { - r = a - } else { - r = b - } - return -} - -const ( - snum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" -) - -func FilterEmoji(content string) string { - added := false - newContent := "" - for _, value := range content { - _, size := utf8.DecodeRuneInString(string(value)) - if size <= 3 { - newContent += string(value) - } else { - if !added { - newContent += "{emoji表情}" - added = true - } - } - } - return newContent -} - -func UUID() (string, error) { - uuid := make([]byte, 16) - n, err := io.ReadFull(cr.Reader, uuid) - if n != len(uuid) || err != nil { - return "", err - } - // variant bits; see section 4.1.1 - uuid[8] = uuid[8]&^0xc0 | 0x80 - // version 4 (pseudo-random); see section 4.1.3 - uuid[6] = uuid[6]&^0xf0 | 0x40 - return fmt.Sprintf("%x%x%x%x%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil -} - -// Reverse 将其实参字符串以符文为单位左右反转。 -func Reverse(s string) string { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r) -} diff --git a/pkg/utils/time.go b/pkg/utils/time.go deleted file mode 100644 index 6690f5a..0000000 --- a/pkg/utils/time.go +++ /dev/null @@ -1,32 +0,0 @@ -package utils - -import "time" - -// 获取当前的时间 - 字符串 -func GetCurrentTime() string { - return time.Now().Format("2006/01/02 15:04:05") -} - -func GetCurrentDate() string { - return time.Now().Format("2006/01/02") -} - -// 获取当前的时间 - Unix时间戳 -func GetCurrentUnix() int64 { - return time.Now().Unix() -} - -// 获取当前的时间 - 毫秒级时间戳 -func GetCurrentMilliUnix() int64 { - return time.Now().UnixNano() / 1000000 -} - -// 获取当前的时间 - 纳秒级时间戳 -func GetCurrentNanoUnix() int64 { - return time.Now().UnixNano() -} - -func String2time(dateString string) time.Time { - date, _ := time.Parse("2006-01-02 15:04:05", dateString) - return date -} diff --git a/test/helper.go b/test/helper.go index 908d9bc..f1eb15d 100644 --- a/test/helper.go +++ b/test/helper.go @@ -4,7 +4,7 @@ import ( "encoding/json" "io" - "lin-cms-go/pkg/core" + "github.com/xushuhui/goal/core" "net/http" "net/http/httptest" diff --git a/test/user_test.go b/test/user_test.go index 1f9e229..ee3996f 100644 --- a/test/user_test.go +++ b/test/user_test.go @@ -1,39 +1,71 @@ package test import ( + "encoding/json" "fmt" + "github.com/xushuhui/goal/utils" + "io/ioutil" + "net/http" "testing" ) -type I interface{ - F() -} -type T struct { -} +func TestAddUsers(t *testing.T) { + m := make(map[int64]AlbumResponse) + for i := 1; i <= 501; i = i + 10 { + url := `http://localhost:4455/api/albums?offset=` + utils.IntToString(i) + `&limit=10&app_id=8456804462776431` + fmt.Println(url) + items := do(url) + fmt.Println(items) + for _, v := range items { -func (t *T) F() { -} + _, ok := m[v.Id] + + if ok { + fmt.Println("------------------------------------------------------------------------------------------") + fmt.Println("repeat ", i, m[v.Id]) + } else { + m[v.Id] = v + } + } + + } -func makeI() I { - var r *T - if r == nil { - fmt.Println("I am nil at makeI") - } - return r } +type AlbumResponse struct { + Id int64 `json:"id"` + Name string `json:"name"` + IssueDate string `json:"issue_date"` + IssueTime string `json:"issue_time"` +} +type Response struct { + Code int `json:"code"` + Message string `json:"message"` + Data PageResponse `json:"data"` +} +type PageResponse struct { + Items []AlbumResponse `json:"items"` + Total int64 `json:"total"` +} -func TestAddUsers(t *testing.T) { - i := makeI() - - if i != nil { - fmt.Println("I am not nil at main") +func do(url string) []AlbumResponse { + rsps, err := http.Get(url) + if err != nil { + fmt.Println("Request failed:", err) + return nil } + defer rsps.Body.Close() + body, err := ioutil.ReadAll(rsps.Body) + if err != nil { + fmt.Println("Read body failed:", err) + return nil + } + var resp Response + json.Unmarshal(body, &resp) + return resp.Data.Items } func TestUserAll(t *testing.T) { - - //t.Run("TestEditUsers", testEditUsers) - //t.Run("TestDeleteUsers", testDeleteUsers) + } From 7fe1e4f278204943c177fc6770b09be6f59c038b Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Thu, 11 Nov 2021 16:11:43 +0800 Subject: [PATCH 35/44] middleware error --- go.mod | 3 +- go.sum | 4 +- internal/server/middleware.go | 8 ++-- pkg/errcode/message.go | 76 ++++++++++++++--------------------- 4 files changed, 39 insertions(+), 52 deletions(-) diff --git a/go.mod b/go.mod index a436bbf..edf050f 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,6 @@ go 1.14 require ( entgo.io/ent v0.9.1 github.com/andybalholm/brotli v1.0.3 // indirect - github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae github.com/gofiber/fiber/v2 v2.21.0 github.com/golang-jwt/jwt/v4 v4.1.0 @@ -14,7 +13,7 @@ require ( github.com/pkg/errors v0.9.1 github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/stretchr/testify v1.7.0 - github.com/xushuhui/goal v0.0.0-20211111060939-51802987d271 + github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d // indirect golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect golang.org/x/text v0.3.7 // indirect diff --git a/go.sum b/go.sum index e4550de..e895c01 100644 --- a/go.sum +++ b/go.sum @@ -250,8 +250,8 @@ github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xushuhui/goal v0.0.0-20211111060939-51802987d271 h1:pHGbLxUfGwchgvTYd6/wTn1HLkVzjf/2H+2LR2olVBQ= -github.com/xushuhui/goal v0.0.0-20211111060939-51802987d271/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= +github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d h1:p9VAqF9oQ3PMFeOgYvHf0ooX/PkyCAN6G+O9DEEILCQ= +github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= diff --git a/internal/server/middleware.go b/internal/server/middleware.go index b7056b0..61ad116 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -8,15 +8,17 @@ import ( func UserLog(c *fiber.Ctx) error { - c.Next() - + err := c.Next() + if err != nil { + return err + } user := biz.LocalUser(c) msg := c.Locals("logMessage") if msg == nil { return nil } - err := data.CreateLog(c.Context(), c.Response().StatusCode(), user.ID, user.Username, user.Username+msg.(string), c.Method(), c.Path(), "") + err = data.CreateLog(c.Context(), c.Response().StatusCode(), user.ID, user.Username, user.Username+msg.(string), c.Method(), c.Path(), "") return err } diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index 2e155ab..60fc23c 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -1,52 +1,38 @@ package errcode -const ( - SUCCESS = iota - InvalidParams - DBError - ServerError - AuthCheckTokenFail - AuthCheckTokenTimeout - ErrorAuthToken - TimeoutAuthToken - ErrorPassWord - UserFound - UserNotFound - BookNotFound - BookTitleRepetition - GroupNotFound - GroupFound - RootGroupNotAllowDelete - GuestGroupNotAllowDelete +import "github.com/xushuhui/goal/core" - PermissionNotFound +const ( + AuthCheckTokenFail = 10000 + AuthCheckTokenTimeout = 10001 + ErrorAuthToken = 10002 + TimeoutAuthToken = 10003 + ErrorPassWord = 10004 + UserFound = 10005 + UserNotFound = 10006 + BookNotFound = 20000 + BookTitleRepetition = 20001 + GroupNotFound = 30000 + GroupFound = 30001 + RootGroupNotAllowDelete = 30002 + GuestGroupNotAllowDelete = 30003 + PermissionNotFound = 30004 ) -var MsgFlags = map[int]string{ - SUCCESS: "ok", - InvalidParams: "请求参数错误", - DBError: "数据库错误", - ServerError: "系统异常,请联系管理员!", - AuthCheckTokenFail: "Token鉴权失败", - AuthCheckTokenTimeout: "Token已超时", - ErrorAuthToken: "Token错误", - ErrorPassWord: "密码错误", - UserFound: "用户已存在", - UserNotFound: "用户不存在", - BookNotFound: "书籍不存在", - BookTitleRepetition: "书籍标题重复", - GroupNotFound: "分组不存在", - RootGroupNotAllowDelete: "root分组不允许删除", - GuestGroupNotAllowDelete: "guest分组不允许删除", - GroupFound: "分组已存在", - PermissionNotFound: "权限不存在", -} - -func GetMsg(code int) string { - msg, ok := MsgFlags[code] - if ok { - return msg +func init() { + core.CodeMapping = map[int]string{ + AuthCheckTokenFail: "Token鉴权失败", + AuthCheckTokenTimeout: "Token已超时", + ErrorAuthToken: "Token错误", + ErrorPassWord: "密码错误", + UserFound: "用户已存在", + UserNotFound: "用户不存在", + BookNotFound: "书籍不存在", + BookTitleRepetition: "书籍标题重复", + GroupNotFound: "分组不存在", + RootGroupNotAllowDelete: "root分组不允许删除", + GuestGroupNotAllowDelete: "guest分组不允许删除", + GroupFound: "分组已存在", + PermissionNotFound: "权限不存在", } - - return MsgFlags[InvalidParams] } From bba5ff2e9de94c0c5f0d73359eadae3079aad194 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 15 Nov 2021 18:33:49 +0800 Subject: [PATCH 36/44] feat : permission --- api/book.go | 6 +- go.mod | 3 +- go.sum | 4 + internal/biz/biz.go | 23 ++- internal/biz/book.go | 5 +- internal/data/book.go | 5 +- internal/data/ent/schema/book.go | 7 + internal/data/model/book.go | 33 ++++ internal/data/model/book/book.go | 22 +++ internal/data/model/book/where.go | 264 ++++++++++++++++++++++++++ internal/data/model/book_create.go | 87 +++++++++ internal/data/model/book_query.go | 8 +- internal/data/model/book_update.go | 111 +++++++++++ internal/data/model/migrate/schema.go | 3 + internal/data/model/mutation.go | 188 +++++++++++++++++- internal/data/model/runtime.go | 16 ++ internal/data/user.go | 12 +- internal/server/middleware.go | 145 +++++++++++++- internal/server/routes.go | 38 ++-- pkg/errcode/message.go | 2 + test/user_test.go | 66 +++++-- 21 files changed, 993 insertions(+), 55 deletions(-) diff --git a/api/book.go b/api/book.go index ae2e7ec..26bef78 100644 --- a/api/book.go +++ b/api/book.go @@ -1,11 +1,12 @@ package api import ( + "lin-cms-go/internal/biz" + "lin-cms-go/internal/request" + "github.com/gofiber/fiber/v2" "github.com/xushuhui/goal/core" "github.com/xushuhui/goal/utils" - "lin-cms-go/internal/biz" - "lin-cms-go/internal/request" ) func GetBooks(c *fiber.Ctx) error { @@ -55,7 +56,6 @@ func CreateBook(c *fiber.Ctx) error { } func DeleteBook(c *fiber.Ctx) error { - // TODO 没有软删除,ent默认没有软删除待加强 id, err := utils.StringToInt(c.Params("id")) if err != nil { return err diff --git a/go.mod b/go.mod index edf050f..8547de9 100644 --- a/go.mod +++ b/go.mod @@ -7,13 +7,14 @@ require ( github.com/andybalholm/brotli v1.0.3 // indirect github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae github.com/gofiber/fiber/v2 v2.21.0 + github.com/gofiber/jwt/v3 v3.2.0 github.com/golang-jwt/jwt/v4 v4.1.0 github.com/grestful/logs v1.0.7 github.com/klauspost/compress v1.13.5 // indirect github.com/pkg/errors v0.9.1 github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/stretchr/testify v1.7.0 - github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d // indirect + github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect golang.org/x/text v0.3.7 // indirect diff --git a/go.sum b/go.sum index e895c01..f43b26a 100644 --- a/go.sum +++ b/go.sum @@ -70,8 +70,11 @@ github.com/go-playground/validator/v10 v10.9.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSG github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae h1:L6V0ANsMIMdLgXly241UXhXNFWYgXbgjHupTAAURrV0= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gofiber/fiber/v2 v2.20.1/go.mod h1:/LdZHMUXZvTTo7gU4+b1hclqCAdoQphNQ9bi9gutPyI= github.com/gofiber/fiber/v2 v2.21.0 h1:tdRNrgqWqcHWBwE3o51oAleEVsil4Ro02zd2vMEuP4Q= github.com/gofiber/fiber/v2 v2.21.0/go.mod h1:MR1usVH3JHYRyQwMe2eZXRSZHRX38fkV+A7CPB+DlDQ= +github.com/gofiber/jwt/v3 v3.2.0 h1:brHGfuuAJI2NxdPQO0Yoa7L01I0Uc/CKZ3Z2lYE5W30= +github.com/gofiber/jwt/v3 v3.2.0/go.mod h1:Z05kGvvdRqbWMvb3uYmAPwfFyCV8/n/QVorzq4XjwvU= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/golang-jwt/jwt/v4 v4.1.0 h1:XUgk2Ex5veyVFVeLm0xhusUTQybEbexJXrvPNOKkSY0= @@ -245,6 +248,7 @@ github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07 h1:d/VUIMNTk65Xz69ht github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07/go.mod h1:FbXpUxsx5in7z/OrWFDdhYetOy3/VGIJsVHN9G7RUPA= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.29.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= github.com/valyala/fasthttp v1.31.0 h1:lrauRLII19afgCs2fnWRJ4M5IkV0lo2FqA61uGkNBfE= github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= diff --git a/internal/biz/biz.go b/internal/biz/biz.go index c81785e..0383618 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -1,10 +1,13 @@ package biz import ( + "lin-cms-go/internal/data" + "lin-cms-go/internal/data/model" + "lin-cms-go/pkg/enum" + "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v4" "github.com/xushuhui/goal/utils" - "lin-cms-go/internal/data/model" ) func LocalUser(c *fiber.Ctx) (user model.LinUser) { @@ -18,3 +21,21 @@ func LocalUser(c *fiber.Ctx) (user model.LinUser) { utils.JSONDecode(bytes, &user) return } + +func IsAdmin(c *fiber.Ctx) (is bool, err error) { + user := LocalUser(c) + + u, err := data.GetLinUserWithGroupById(c.Context(), user.ID) + if err != nil { + return + } + for _, v := range u.Edges.LinGroup { + if v.Level == enum.ROOT { + is = true + } + } + return +} + +func UserHasPermission(userId int) { +} diff --git a/internal/biz/book.go b/internal/biz/book.go index ee78f98..97e774d 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -2,11 +2,12 @@ package biz import ( "context" - "github.com/xushuhui/goal/core" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" "lin-cms-go/pkg/errcode" + + "github.com/xushuhui/goal/core" ) func GetBookAll(ctx context.Context, page int, size int) (res interface{}, err error) { @@ -55,7 +56,7 @@ func DeleteBook(ctx context.Context, id int) (err error) { err = core.NewErrorCode(errcode.BookNotFound) return } - err = data.DeleteBook(ctx, id) + err = data.SoftDeleteBook(ctx, id) return } diff --git a/internal/data/book.go b/internal/data/book.go index 5e41533..91736e2 100644 --- a/internal/data/book.go +++ b/internal/data/book.go @@ -4,6 +4,7 @@ import ( "context" "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/book" + "time" ) func GetBookById(ctx context.Context, id int) (model *model.Book, err error) { @@ -26,8 +27,8 @@ func CreateBook(ctx context.Context, title string, author string, summary string return } -func DeleteBook(ctx context.Context, id int) (err error) { - err = GetDB().Book.DeleteOneID(id).Exec(ctx) +func SoftDeleteBook(ctx context.Context, id int) (err error) { + _, err = GetDB().Book.Update().Where(book.ID(id)).SetDeleteTime(time.Now()).Save(ctx) return } diff --git a/internal/data/ent/schema/book.go b/internal/data/ent/schema/book.go index 0a8a166..7f72013 100644 --- a/internal/data/ent/schema/book.go +++ b/internal/data/ent/schema/book.go @@ -16,6 +16,7 @@ func (Book) Annotations() []schema.Annotation { entsql.Annotation{Table: "book"}, } } + func (Book) Fields() []ent.Field { return []ent.Field{ field.String("title").Comment(""), @@ -24,3 +25,9 @@ func (Book) Fields() []ent.Field { field.String("image").Comment(""), } } + +func (Book) Mixin() []ent.Mixin { + return []ent.Mixin{ + TimeMixin{}, + } +} diff --git a/internal/data/model/book.go b/internal/data/model/book.go index 7714ba0..724ccd0 100644 --- a/internal/data/model/book.go +++ b/internal/data/model/book.go @@ -6,6 +6,7 @@ import ( "fmt" "lin-cms-go/internal/data/model/book" "strings" + "time" "entgo.io/ent/dialect/sql" ) @@ -15,6 +16,12 @@ type Book struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` // Title holds the value of the "title" field. Title string `json:"title,omitempty"` // Author holds the value of the "author" field. @@ -34,6 +41,8 @@ func (*Book) scanValues(columns []string) ([]interface{}, error) { values[i] = new(sql.NullInt64) case book.FieldTitle, book.FieldAuthor, book.FieldSummary, book.FieldImage: values[i] = new(sql.NullString) + case book.FieldCreateTime, book.FieldUpdateTime, book.FieldDeleteTime: + values[i] = new(sql.NullTime) default: return nil, fmt.Errorf("unexpected column %q for type Book", columns[i]) } @@ -55,6 +64,24 @@ func (b *Book) assignValues(columns []string, values []interface{}) error { return fmt.Errorf("unexpected type %T for field id", value) } b.ID = int(value.Int64) + case book.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + b.CreateTime = value.Time + } + case book.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + b.UpdateTime = value.Time + } + case book.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + b.DeleteTime = value.Time + } case book.FieldTitle: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field title", values[i]) @@ -107,6 +134,12 @@ func (b *Book) String() string { var builder strings.Builder builder.WriteString("Book(") builder.WriteString(fmt.Sprintf("id=%v", b.ID)) + builder.WriteString(", create_time=") + builder.WriteString(b.CreateTime.Format(time.ANSIC)) + builder.WriteString(", update_time=") + builder.WriteString(b.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", delete_time=") + builder.WriteString(b.DeleteTime.Format(time.ANSIC)) builder.WriteString(", title=") builder.WriteString(b.Title) builder.WriteString(", author=") diff --git a/internal/data/model/book/book.go b/internal/data/model/book/book.go index 040d81c..312a479 100644 --- a/internal/data/model/book/book.go +++ b/internal/data/model/book/book.go @@ -2,11 +2,21 @@ package book +import ( + "time" +) + const ( // Label holds the string label denoting the book type in the database. Label = "book" // FieldID holds the string denoting the id field in the database. FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" // FieldTitle holds the string denoting the title field in the database. FieldTitle = "title" // FieldAuthor holds the string denoting the author field in the database. @@ -22,6 +32,9 @@ const ( // Columns holds all SQL columns for book fields. var Columns = []string{ FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, FieldTitle, FieldAuthor, FieldSummary, @@ -37,3 +50,12 @@ func ValidColumn(column string) bool { } return false } + +var ( + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time +) diff --git a/internal/data/model/book/where.go b/internal/data/model/book/where.go index 7812ed5..5b395c3 100644 --- a/internal/data/model/book/where.go +++ b/internal/data/model/book/where.go @@ -4,6 +4,7 @@ package book import ( "lin-cms-go/internal/data/model/predicate" + "time" "entgo.io/ent/dialect/sql" ) @@ -91,6 +92,27 @@ func IDLTE(id int) predicate.Book { }) } +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + // Title applies equality check predicate on the "title" field. It's identical to TitleEQ. func Title(v string) predicate.Book { return predicate.Book(func(s *sql.Selector) { @@ -119,6 +141,248 @@ func Image(v string) predicate.Book { }) } +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldCreateTime), v...)) + }) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreateTime), v)) + }) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreateTime), v)) + }) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldUpdateTime), v...)) + }) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdateTime), v)) + }) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdateTime), v)) + }) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.Book { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Book(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDeleteTime), v...)) + }) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDeleteTime), v)) + }) +} + +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDeleteTime))) + }) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.Book { + return predicate.Book(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDeleteTime))) + }) +} + // TitleEQ applies the EQ predicate on the "title" field. func TitleEQ(v string) predicate.Book { return predicate.Book(func(s *sql.Selector) { diff --git a/internal/data/model/book_create.go b/internal/data/model/book_create.go index ba2bd4a..cfad8b4 100644 --- a/internal/data/model/book_create.go +++ b/internal/data/model/book_create.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "lin-cms-go/internal/data/model/book" + "time" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -19,6 +20,48 @@ type BookCreate struct { hooks []Hook } +// SetCreateTime sets the "create_time" field. +func (bc *BookCreate) SetCreateTime(t time.Time) *BookCreate { + bc.mutation.SetCreateTime(t) + return bc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (bc *BookCreate) SetNillableCreateTime(t *time.Time) *BookCreate { + if t != nil { + bc.SetCreateTime(*t) + } + return bc +} + +// SetUpdateTime sets the "update_time" field. +func (bc *BookCreate) SetUpdateTime(t time.Time) *BookCreate { + bc.mutation.SetUpdateTime(t) + return bc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (bc *BookCreate) SetNillableUpdateTime(t *time.Time) *BookCreate { + if t != nil { + bc.SetUpdateTime(*t) + } + return bc +} + +// SetDeleteTime sets the "delete_time" field. +func (bc *BookCreate) SetDeleteTime(t time.Time) *BookCreate { + bc.mutation.SetDeleteTime(t) + return bc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (bc *BookCreate) SetNillableDeleteTime(t *time.Time) *BookCreate { + if t != nil { + bc.SetDeleteTime(*t) + } + return bc +} + // SetTitle sets the "title" field. func (bc *BookCreate) SetTitle(s string) *BookCreate { bc.mutation.SetTitle(s) @@ -54,6 +97,7 @@ func (bc *BookCreate) Save(ctx context.Context) (*Book, error) { err error node *Book ) + bc.defaults() if len(bc.hooks) == 0 { if err = bc.check(); err != nil { return nil, err @@ -111,8 +155,26 @@ func (bc *BookCreate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (bc *BookCreate) defaults() { + if _, ok := bc.mutation.CreateTime(); !ok { + v := book.DefaultCreateTime() + bc.mutation.SetCreateTime(v) + } + if _, ok := bc.mutation.UpdateTime(); !ok { + v := book.DefaultUpdateTime() + bc.mutation.SetUpdateTime(v) + } +} + // check runs all checks and user-defined validators on the builder. func (bc *BookCreate) check() error { + if _, ok := bc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`model: missing required field "create_time"`)} + } + if _, ok := bc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`model: missing required field "update_time"`)} + } if _, ok := bc.mutation.Title(); !ok { return &ValidationError{Name: "title", err: errors.New(`model: missing required field "title"`)} } @@ -152,6 +214,30 @@ func (bc *BookCreate) createSpec() (*Book, *sqlgraph.CreateSpec) { }, } ) + if value, ok := bc.mutation.CreateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldCreateTime, + }) + _node.CreateTime = value + } + if value, ok := bc.mutation.UpdateTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldUpdateTime, + }) + _node.UpdateTime = value + } + if value, ok := bc.mutation.DeleteTime(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldDeleteTime, + }) + _node.DeleteTime = value + } if value, ok := bc.mutation.Title(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -201,6 +287,7 @@ func (bcb *BookCreateBulk) Save(ctx context.Context) ([]*Book, error) { for i := range bcb.builders { func(i int, root context.Context) { builder := bcb.builders[i] + builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*BookMutation) if !ok { diff --git a/internal/data/model/book_query.go b/internal/data/model/book_query.go index d27c9e7..bf4f39a 100644 --- a/internal/data/model/book_query.go +++ b/internal/data/model/book_query.go @@ -298,12 +298,12 @@ func (bq *BookQuery) Clone() *BookQuery { // Example: // // var v []struct { -// Title string `json:"title,omitempty"` +// CreateTime time.Time `json:"create_time,omitempty"` // Count int `json:"count,omitempty"` // } // // client.Book.Query(). -// GroupBy(book.FieldTitle). +// GroupBy(book.FieldCreateTime). // Aggregate(model.Count()). // Scan(ctx, &v) // @@ -325,11 +325,11 @@ func (bq *BookQuery) GroupBy(field string, fields ...string) *BookGroupBy { // Example: // // var v []struct { -// Title string `json:"title,omitempty"` +// CreateTime time.Time `json:"create_time,omitempty"` // } // // client.Book.Query(). -// Select(book.FieldTitle). +// Select(book.FieldCreateTime). // Scan(ctx, &v) // func (bq *BookQuery) Select(fields ...string) *BookSelect { diff --git a/internal/data/model/book_update.go b/internal/data/model/book_update.go index 1d409aa..341baa1 100644 --- a/internal/data/model/book_update.go +++ b/internal/data/model/book_update.go @@ -7,6 +7,7 @@ import ( "fmt" "lin-cms-go/internal/data/model/book" "lin-cms-go/internal/data/model/predicate" + "time" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -26,6 +27,32 @@ func (bu *BookUpdate) Where(ps ...predicate.Book) *BookUpdate { return bu } +// SetUpdateTime sets the "update_time" field. +func (bu *BookUpdate) SetUpdateTime(t time.Time) *BookUpdate { + bu.mutation.SetUpdateTime(t) + return bu +} + +// SetDeleteTime sets the "delete_time" field. +func (bu *BookUpdate) SetDeleteTime(t time.Time) *BookUpdate { + bu.mutation.SetDeleteTime(t) + return bu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (bu *BookUpdate) SetNillableDeleteTime(t *time.Time) *BookUpdate { + if t != nil { + bu.SetDeleteTime(*t) + } + return bu +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (bu *BookUpdate) ClearDeleteTime() *BookUpdate { + bu.mutation.ClearDeleteTime() + return bu +} + // SetTitle sets the "title" field. func (bu *BookUpdate) SetTitle(s string) *BookUpdate { bu.mutation.SetTitle(s) @@ -61,6 +88,7 @@ func (bu *BookUpdate) Save(ctx context.Context) (int, error) { err error affected int ) + bu.defaults() if len(bu.hooks) == 0 { affected, err = bu.sqlSave(ctx) } else { @@ -109,6 +137,14 @@ func (bu *BookUpdate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (bu *BookUpdate) defaults() { + if _, ok := bu.mutation.UpdateTime(); !ok { + v := book.UpdateDefaultUpdateTime() + bu.mutation.SetUpdateTime(v) + } +} + func (bu *BookUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -127,6 +163,26 @@ func (bu *BookUpdate) sqlSave(ctx context.Context) (n int, err error) { } } } + if value, ok := bu.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldUpdateTime, + }) + } + if value, ok := bu.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldDeleteTime, + }) + } + if bu.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: book.FieldDeleteTime, + }) + } if value, ok := bu.mutation.Title(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, @@ -174,6 +230,32 @@ type BookUpdateOne struct { mutation *BookMutation } +// SetUpdateTime sets the "update_time" field. +func (buo *BookUpdateOne) SetUpdateTime(t time.Time) *BookUpdateOne { + buo.mutation.SetUpdateTime(t) + return buo +} + +// SetDeleteTime sets the "delete_time" field. +func (buo *BookUpdateOne) SetDeleteTime(t time.Time) *BookUpdateOne { + buo.mutation.SetDeleteTime(t) + return buo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (buo *BookUpdateOne) SetNillableDeleteTime(t *time.Time) *BookUpdateOne { + if t != nil { + buo.SetDeleteTime(*t) + } + return buo +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (buo *BookUpdateOne) ClearDeleteTime() *BookUpdateOne { + buo.mutation.ClearDeleteTime() + return buo +} + // SetTitle sets the "title" field. func (buo *BookUpdateOne) SetTitle(s string) *BookUpdateOne { buo.mutation.SetTitle(s) @@ -216,6 +298,7 @@ func (buo *BookUpdateOne) Save(ctx context.Context) (*Book, error) { err error node *Book ) + buo.defaults() if len(buo.hooks) == 0 { node, err = buo.sqlSave(ctx) } else { @@ -264,6 +347,14 @@ func (buo *BookUpdateOne) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (buo *BookUpdateOne) defaults() { + if _, ok := buo.mutation.UpdateTime(); !ok { + v := book.UpdateDefaultUpdateTime() + buo.mutation.SetUpdateTime(v) + } +} + func (buo *BookUpdateOne) sqlSave(ctx context.Context) (_node *Book, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -299,6 +390,26 @@ func (buo *BookUpdateOne) sqlSave(ctx context.Context) (_node *Book, err error) } } } + if value, ok := buo.mutation.UpdateTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldUpdateTime, + }) + } + if value, ok := buo.mutation.DeleteTime(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: book.FieldDeleteTime, + }) + } + if buo.mutation.DeleteTimeCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Column: book.FieldDeleteTime, + }) + } if value, ok := buo.mutation.Title(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, diff --git a/internal/data/model/migrate/schema.go b/internal/data/model/migrate/schema.go index 6bf8529..e302af7 100644 --- a/internal/data/model/migrate/schema.go +++ b/internal/data/model/migrate/schema.go @@ -12,6 +12,9 @@ var ( // BookColumns holds the columns for the "book" table. BookColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime, Nullable: true}, {Name: "title", Type: field.TypeString}, {Name: "author", Type: field.TypeString}, {Name: "summary", Type: field.TypeString}, diff --git a/internal/data/model/mutation.go b/internal/data/model/mutation.go index d44077d..9a8cbcb 100644 --- a/internal/data/model/mutation.go +++ b/internal/data/model/mutation.go @@ -43,6 +43,9 @@ type BookMutation struct { op Op typ string id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time title *string author *string summary *string @@ -132,6 +135,127 @@ func (m *BookMutation) ID() (id int, exists bool) { return *m.id, true } +// SetCreateTime sets the "create_time" field. +func (m *BookMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *BookMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the Book entity. +// If the Book 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 *BookMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *BookMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *BookMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *BookMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the Book entity. +// If the Book 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 *BookMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *BookMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *BookMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *BookMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the Book entity. +// If the Book 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 *BookMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (m *BookMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[book.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *BookMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[book.FieldDeleteTime] + return ok +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *BookMutation) ResetDeleteTime() { + m.delete_time = nil + delete(m.clearedFields, book.FieldDeleteTime) +} + // SetTitle sets the "title" field. func (m *BookMutation) SetTitle(s string) { m.title = &s @@ -295,7 +419,16 @@ func (m *BookMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *BookMutation) Fields() []string { - fields := make([]string, 0, 4) + fields := make([]string, 0, 7) + if m.create_time != nil { + fields = append(fields, book.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, book.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, book.FieldDeleteTime) + } if m.title != nil { fields = append(fields, book.FieldTitle) } @@ -316,6 +449,12 @@ func (m *BookMutation) Fields() []string { // schema. func (m *BookMutation) Field(name string) (ent.Value, bool) { switch name { + case book.FieldCreateTime: + return m.CreateTime() + case book.FieldUpdateTime: + return m.UpdateTime() + case book.FieldDeleteTime: + return m.DeleteTime() case book.FieldTitle: return m.Title() case book.FieldAuthor: @@ -333,6 +472,12 @@ func (m *BookMutation) Field(name string) (ent.Value, bool) { // database failed. func (m *BookMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { + case book.FieldCreateTime: + return m.OldCreateTime(ctx) + case book.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case book.FieldDeleteTime: + return m.OldDeleteTime(ctx) case book.FieldTitle: return m.OldTitle(ctx) case book.FieldAuthor: @@ -350,6 +495,27 @@ func (m *BookMutation) OldField(ctx context.Context, name string) (ent.Value, er // type. func (m *BookMutation) SetField(name string, value ent.Value) error { switch name { + case book.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case book.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case book.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil case book.FieldTitle: v, ok := value.(string) if !ok { @@ -407,7 +573,11 @@ func (m *BookMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *BookMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(book.FieldDeleteTime) { + fields = append(fields, book.FieldDeleteTime) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -420,6 +590,11 @@ func (m *BookMutation) 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 *BookMutation) ClearField(name string) error { + switch name { + case book.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } return fmt.Errorf("unknown Book nullable field %s", name) } @@ -427,6 +602,15 @@ func (m *BookMutation) ClearField(name string) error { // It returns an error if the field is not defined in the schema. func (m *BookMutation) ResetField(name string) error { switch name { + case book.FieldCreateTime: + m.ResetCreateTime() + return nil + case book.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case book.FieldDeleteTime: + m.ResetDeleteTime() + return nil case book.FieldTitle: m.ResetTitle() return nil diff --git a/internal/data/model/runtime.go b/internal/data/model/runtime.go index 58d3b54..15df6fb 100644 --- a/internal/data/model/runtime.go +++ b/internal/data/model/runtime.go @@ -4,6 +4,7 @@ package model import ( "lin-cms-go/internal/data/ent/schema" + "lin-cms-go/internal/data/model/book" "lin-cms-go/internal/data/model/lingroup" "lin-cms-go/internal/data/model/linlog" "lin-cms-go/internal/data/model/linuser" @@ -15,6 +16,21 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + bookMixin := schema.Book{}.Mixin() + bookMixinFields0 := bookMixin[0].Fields() + _ = bookMixinFields0 + bookFields := schema.Book{}.Fields() + _ = bookFields + // bookDescCreateTime is the schema descriptor for create_time field. + bookDescCreateTime := bookMixinFields0[0].Descriptor() + // book.DefaultCreateTime holds the default value on creation for the create_time field. + book.DefaultCreateTime = bookDescCreateTime.Default.(func() time.Time) + // bookDescUpdateTime is the schema descriptor for update_time field. + bookDescUpdateTime := bookMixinFields0[1].Descriptor() + // book.DefaultUpdateTime holds the default value on creation for the update_time field. + book.DefaultUpdateTime = bookDescUpdateTime.Default.(func() time.Time) + // book.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + book.UpdateDefaultUpdateTime = bookDescUpdateTime.UpdateDefault.(func() time.Time) lingroupMixin := schema.LinGroup{}.Mixin() lingroupMixinFields0 := lingroupMixin[0].Fields() _ = lingroupMixinFields0 diff --git a/internal/data/user.go b/internal/data/user.go index b044c5f..ca2484e 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -8,18 +8,16 @@ import ( ) func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (model *model.LinUserIdentiy, err error) { - model, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.Identifier(identifier)).First(ctx) return } func GetLinUserIdentityByUserId(ctx context.Context, userId int) (model *model.LinUserIdentiy, err error) { - model, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.UserID(userId)).First(ctx) return } -func CreateLinUser(ctx context.Context, username, password, email string, groupId int) (err error) { +func CreateLinUser(ctx context.Context, username, password, email string, groupId int) (err error) { userModel, err := GetDB().LinUser.Create(). SetUsername(username). SetNickname(username). @@ -38,18 +36,26 @@ func CreateLinUser(ctx context.Context, username, password, email string, groupI return } + func GetLinUserById(ctx context.Context, uid int) (model *model.LinUser, err error) { model, err = GetDB().LinUser.Query().Where(linuser.ID(uid)).First(ctx) return } +func GetLinUserWithGroupById(ctx context.Context, uid int) (model *model.LinUser, err error) { + model, err = GetDB().LinUser.Query().Where(linuser.ID(uid)).WithLinGroup().First(ctx) + + return +} + func UpdateLinUser(ctx context.Context, uid int, avatar, nickname, email string) (err error) { _, err = GetDB().LinUser.Update().Where(linuser.ID(uid)).SetEmail(email).SetAvatar(avatar).SetNickname(nickname). Save(ctx) return } + func UpdateLinUserIdentityPassword(ctx context.Context, username, password string) (err error) { _, err = GetDB().LinUserIdentiy.Update().Where(linuseridentiy.Identifier(username)). SetCredential(password).Save(ctx) diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 61ad116..e313202 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -1,13 +1,18 @@ package server import ( - "github.com/gofiber/fiber/v2" + "fmt" "lin-cms-go/internal/biz" "lin-cms-go/internal/data" + "lin-cms-go/pkg/errcode" + + jwtware "github.com/gofiber/jwt/v3" + "github.com/xushuhui/goal/core" + + "github.com/gofiber/fiber/v2" ) func UserLog(c *fiber.Ctx) error { - err := c.Next() if err != nil { return err @@ -22,3 +27,139 @@ func UserLog(c *fiber.Ctx) error { return err } + +type Permission struct { + Name string `json:"name"` + Module string `json:"module"` +} + +func SetPermission(name, module string) fiber.Handler { + return func(c *fiber.Ctx) error { + c.Locals("permission", Permission{Name: name, Module: module}) + return c.Next() + } +} + +func AdminRequired(c *fiber.Ctx) error { + fmt.Println("-------------------admin require middle+") + fmt.Println(c.Locals("permission")) + return c.Next() +} + +func LoginRequired(c *fiber.Ctx) error { + if c.Method() != fiber.MethodOptions { + jwtware.New(jwtware.Config{ + SigningKey: []byte("secret"), + }) + return c.Next() + } + return c.Next() +} + +func GroupRequired(c *fiber.Ctx) error { + isAdmin, err := biz.IsAdmin(c) + if err != nil { + return err + } + if isAdmin { + return c.Next() + } + + local := c.Locals("permission") + if local == nil { + return core.NewErrorCode(errcode.UserPermissionRequired) + } + p := local.(Permission) + fmt.Println(p) + return c.Next() +} + +// +//func (a *Auth) GroupRequired(c *gin.Context) { +// user, _ := c.Get("currentUser") +// userId := user.(model.User).ID +// // admin直接通过 +// admin, _ := a.UserService.IsAdmin(userId) +// if admin { +// c.Next() +// } else { +// meta, ok := c.Get("meta") +// if !ok { +// return +// } +// routeMeta := meta.(router.Meta) +// if !routeMeta.Mount { +// c.Next() +// } else { +// hasPermission := a.GroupService.GetUserHasPermission(userId, routeMeta) +// if !hasPermission { +// _ = c.Error(response.UnifyResponse(10001, c)) +// c.Abort() +// return +// } else { +// c.Next() +// } +// } +// } +//} + +// +//func (a *Auth) AdminRequired(c *gin.Context) { +// if err := a.mountUser(c); err != nil { +// _ = c.Error(err) +// c.Abort() +// return +// } +// user, _ := c.Get("currentUser") +// currentUser := user.(model.User) +// admin, err := a.UserService.IsAdmin(currentUser.ID) +// if err != nil { +// _ = c.Error(response.UnifyResponse(10021, c)) +// c.Abort() +// return +// } +// if admin { +// c.Next() +// } else { +// _ = c.Error(response.UnifyResponse(10001, c)) +// c.Abort() +// return +// } +//} +// +//func (a *Auth) RefreshRequired(ctx *gin.Context) { +// refreshToken, tokenErr := getHeaderToken(ctx) +// if tokenErr != nil { +// ctx.Error(tokenErr) +// ctx.Abort() +// return +// } +// payload, err := a.JWT.VerifyRefreshToken(refreshToken) +// if err != nil { +// ctx.Error(err) +// ctx.Abort() +// } else { +// userId := payload.Identity +// user, errs := a.UserService.GetUserById(userId) +// if errs != nil { +// ctx.Error(response.UnifyResponse(10021, ctx)) +// ctx.Abort() +// } else { +// ctx.Set("currentUser", user) +// ctx.Next() +// } +// } +//} + +//func getHeaderToken(ctx *gin.Context) (string, error) { +// authorizationHeader := ctx.GetHeader(AuthorizationHeaderKey) +// if authorizationHeader == "" { +// return "", response.UnifyResponse(10012, ctx) +// } +// fields := strings.Fields(authorizationHeader) +// if fields[0] != AuthorizationTypeBearer { +// return "", response.UnifyResponse(10013, ctx) +// } +// tokenString := fields[1] +// return tokenString, nil +//} diff --git a/internal/server/routes.go b/internal/server/routes.go index 339ee20..7aeef5c 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -1,33 +1,41 @@ package server import ( - "github.com/gofiber/fiber/v2" "lin-cms-go/api" + + "github.com/gofiber/fiber/v2" ) func InitRoute(app *fiber.App) { - //加载静态资源,一般是上传的资源,例如用户上传的图片 + // 加载静态资源,一般是上传的资源,例如用户上传的图片 app.Static("/upload", "storage/upload") app.Get("/", api.Hello) cms := app.Group("/cms") - v1 := app.Group("/v1") + // v1 := app.Group("/v1") + cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) - cms.Post("/user/register", api.Register) + // FIXME 开发阶段先注释jwt - //cms.Use(jwtware.New(jwtware.Config{ - // SigningKey: []byte("secret"), - //})) + cms.Use(LoginRequired) //v1.Use(jwtware.New(jwtware.Config{ // SigningKey: []byte("secret"), //})) - { - userRouter := cms.Group("/user") - adminRouter := cms.Group("/admin") - logRouter := cms.Group("/log") - bookRouter := v1.Group("/book") + userRouter := cms.Group("/user") + adminRouter := cms.Group("/admin") + logRouter := cms.Group("/log") + bookRouter := app.Group("/v1/book").Use(GroupRequired) + { + bookRouter.Use(SetPermission("book", "图书")).Get("/", api.GetBooks) + bookRouter.Get("/:id", api.GetBook) + bookRouter.Put("/:id", api.UpdateBook) + bookRouter.Post("/", api.CreateBook) + bookRouter.Delete("/:id", api.DeleteBook) + } + { + userRouter.Use(AdminRequired).Post("/register", api.Register) userRouter.Put("/", api.UpdateMe) userRouter.Put("/change_password", api.ChangeMyPassword) userRouter.Get("/permissions", api.GetMyPermissions) @@ -53,11 +61,5 @@ func InitRoute(app *fiber.App) { logRouter.Get("/search", api.SearchLogs) logRouter.Get("/users", api.GetLogUsers) - bookRouter.Get("/", api.GetBooks) - bookRouter.Get("/:id", api.GetBook) - bookRouter.Put("/:id", api.UpdateBook) - bookRouter.Post("/", api.CreateBook) - bookRouter.Delete("/:id", api.DeleteBook) } - } diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index 60fc23c..57254e8 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -17,6 +17,7 @@ const ( RootGroupNotAllowDelete = 30002 GuestGroupNotAllowDelete = 30003 PermissionNotFound = 30004 + UserPermissionRequired = 40000 ) func init() { @@ -34,5 +35,6 @@ func init() { GuestGroupNotAllowDelete: "guest分组不允许删除", GroupFound: "分组已存在", PermissionNotFound: "权限不存在", + UserPermissionRequired: "用户权限必须存在", } } diff --git a/test/user_test.go b/test/user_test.go index ee3996f..9844ab5 100644 --- a/test/user_test.go +++ b/test/user_test.go @@ -3,33 +3,64 @@ package test import ( "encoding/json" "fmt" - "github.com/xushuhui/goal/utils" "io/ioutil" "net/http" "testing" ) -func TestAddUsers(t *testing.T) { - m := make(map[int64]AlbumResponse) - for i := 1; i <= 501; i = i + 10 { - url := `http://localhost:4455/api/albums?offset=` + utils.IntToString(i) + `&limit=10&app_id=8456804462776431` - fmt.Println(url) - items := do(url) - fmt.Println(items) - for _, v := range items { - - _, ok := m[v.Id] +type Categories struct { + ID int + Pid int + Name string + Children []Categories +} - if ok { - fmt.Println("------------------------------------------------------------------------------------------") - fmt.Println("repeat ", i, m[v.Id]) +func getNode(list []Categories, pid int) (l []Categories) { + for _, val := range list { + if val.Pid == pid { + if pid == 0 { + // 顶层 + l = append(l, val) } else { - m[v.Id] = v + var children []Categories + child := val + children = append(children, child) + } + } + } + return +} + +func Tree(list []Categories, pid int) (newList []Categories) { + for _, v := range list { + if v.Pid == pid { + child := getNode(list, v.ID) + node := Categories{ + ID: v.ID, + Name: v.Name, + Pid: v.Pid, } + node.Children = child + newList = append(newList, node) } + } + return +} +func TestAddUsers(t *testing.T) { + categories := []Categories{ + {ID: 1, Pid: 0, Name: "电脑"}, + {ID: 2, Pid: 0, Name: "手机"}, + {ID: 3, Pid: 1, Name: "笔记本"}, + {ID: 4, Pid: 1, Name: "台式机"}, + {ID: 5, Pid: 2, Name: "智能机"}, + {ID: 6, Pid: 2, Name: "功能机"}, + {ID: 7, Pid: 3, Name: "超级本"}, + {ID: 8, Pid: 3, Name: "游戏本"}, } + m := Tree(categories, 0) + fmt.Println(m) } type AlbumResponse struct { @@ -38,11 +69,13 @@ type AlbumResponse struct { IssueDate string `json:"issue_date"` IssueTime string `json:"issue_time"` } + type Response struct { Code int `json:"code"` Message string `json:"message"` Data PageResponse `json:"data"` } + type PageResponse struct { Items []AlbumResponse `json:"items"` Total int64 `json:"total"` @@ -64,8 +97,7 @@ func do(url string) []AlbumResponse { var resp Response json.Unmarshal(body, &resp) return resp.Data.Items - } -func TestUserAll(t *testing.T) { +func TestUserAll(t *testing.T) { } From 94a0ace3a2533aff7d2b074faa6e1818764331a1 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Mon, 15 Nov 2021 22:04:36 +0800 Subject: [PATCH 37/44] feat: delete user --- api/admin.go | 4 +- internal/biz/admin.go | 46 ++++++----- internal/biz/biz.go | 36 ++++++++- internal/data/ent/schema/lin_user_group.go | 2 - internal/data/permission.go | 3 + internal/data/user.go | 7 ++ internal/server/middleware.go | 89 +++++----------------- internal/server/routes.go | 17 ++--- pkg/errcode/message.go | 2 + 9 files changed, 102 insertions(+), 104 deletions(-) diff --git a/api/admin.go b/api/admin.go index 96fac54..5086f4e 100644 --- a/api/admin.go +++ b/api/admin.go @@ -30,7 +30,7 @@ func ChangeUserPassword(c *fiber.Ctx) error { return err } - err := biz.ChangeUserPassword(req) + err := biz.ChangeUserPassword(c.Context(), req.Id, req.NewPassword) if err != nil { return err } @@ -44,7 +44,7 @@ func DeleteUser(c *fiber.Ctx) error { if err != nil { return err } - err = biz.DeleteUser(id) + err = biz.DeleteUser(c.Context(), id) if err != nil { return err } diff --git a/internal/biz/admin.go b/internal/biz/admin.go index 714d9a4..836a9a6 100644 --- a/internal/biz/admin.go +++ b/internal/biz/admin.go @@ -1,32 +1,42 @@ package biz import ( + "context" + "github.com/xushuhui/goal/core" + "golang.org/x/crypto/bcrypt" + "lin-cms-go/internal/data" + "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" + "lin-cms-go/pkg/errcode" ) -func GetUsers(req request.GetUsers) (data map[string]interface{}, err error) { +func GetUsers(req request.GetUsers) (res interface{}, err error) { return } -func ChangeUserPassword(req request.ChangeUserPassword) (err error) { +func ChangeUserPassword(ctx context.Context, userId int, password string) (err error) { + user, err := data.GetLinUserIdentityByUserId(ctx, userId) + if err != nil { + return + } - //userIdentityModel, err := modelbak.GetLinUserIdentityOne("user_id=?", req.Id) - //if err != nil { - // return - //} - // - //hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) - //if err != nil { - // return - //} - //userIdentityModel.Credential = string(hash) - //err = global.DBEngine.Save(&userIdentityModel).Error - //if err != nil { - // return - //} + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return + } + err = data.UpdateLinUserIdentityPassword(ctx, user.Identifier, string(hash)) + + if err != nil { + return + } return } -func DeleteUser(id int) (err error) { - +func DeleteUser(ctx context.Context, userId int) (err error) { + _, err = data.GetLinUserById(ctx, userId) + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.UserNotFound) + return + } + err = data.SoftDeleteUser(ctx, userId) return } func UpdateUser(req request.UpdateUser) (err error) { diff --git a/internal/biz/biz.go b/internal/biz/biz.go index 0383618..27f41ef 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -1,9 +1,12 @@ package biz import ( + "context" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/pkg/enum" + "lin-cms-go/pkg/errcode" "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v4" @@ -29,7 +32,9 @@ func IsAdmin(c *fiber.Ctx) (is bool, err error) { if err != nil { return } + for _, v := range u.Edges.LinGroup { + if v.Level == enum.ROOT { is = true } @@ -37,5 +42,34 @@ func IsAdmin(c *fiber.Ctx) (is bool, err error) { return } -func UserHasPermission(userId int) { +type Permission struct { + Name string `json:"name"` + Module string `json:"module"` +} + +func UserHasPermission(c *fiber.Ctx) (has bool, err error) { + user := LocalUser(c) + + u, err := data.GetLinUserWithGroupById(context.Background(), user.ID) + if err != nil { + return + } + local := c.Locals("permission") + if local == nil { + return false, core.NewErrorCode(errcode.UserPermissionRequired) + } + userPermission := local.(Permission) + var ps []model.LinPermission + for _, v := range u.Edges.LinGroup { + for _, p := range v.Edges.LinPermission { + ps = append(ps, *p) + } + + } + for _, p := range ps { + if p.Module == userPermission.Module && p.Name == userPermission.Name { + has = true + } + } + return } diff --git a/internal/data/ent/schema/lin_user_group.go b/internal/data/ent/schema/lin_user_group.go index f7ed412..951a1fb 100644 --- a/internal/data/ent/schema/lin_user_group.go +++ b/internal/data/ent/schema/lin_user_group.go @@ -9,8 +9,6 @@ import ( ) type TimeMixin struct { - // We embed the `mixin.Schema` to avoid - // implementing the rest of the methods. mixin.Schema } diff --git a/internal/data/permission.go b/internal/data/permission.go index 2565c91..9e8dd74 100644 --- a/internal/data/permission.go +++ b/internal/data/permission.go @@ -10,3 +10,6 @@ func GetLinPermissionById(ctx context.Context, id int) (permission *model.LinPer permission, err = GetDB().LinPermission.Query().Where(linpermission.ID(id)).First(ctx) return } +func GetUserPermission(ctx context.Context, userId int, name, module string) { + +} diff --git a/internal/data/user.go b/internal/data/user.go index ca2484e..3fc52f0 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -5,6 +5,7 @@ import ( "lin-cms-go/internal/data/model" "lin-cms-go/internal/data/model/linuser" "lin-cms-go/internal/data/model/linuseridentiy" + "time" ) func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (model *model.LinUserIdentiy, err error) { @@ -62,3 +63,9 @@ func UpdateLinUserIdentityPassword(ctx context.Context, username, password strin return } +func SoftDeleteUser(ctx context.Context, userId int) (err error) { + _, err = GetDB().LinUser.Update().Where(linuser.ID(userId)). + SetDeleteTime(time.Now()).Save(ctx) + + return +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go index e313202..7535b89 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -1,15 +1,12 @@ package server import ( - "fmt" + "github.com/gofiber/fiber/v2" + jwtware "github.com/gofiber/jwt/v3" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/biz" "lin-cms-go/internal/data" "lin-cms-go/pkg/errcode" - - jwtware "github.com/gofiber/jwt/v3" - "github.com/xushuhui/goal/core" - - "github.com/gofiber/fiber/v2" ) func UserLog(c *fiber.Ctx) error { @@ -28,21 +25,22 @@ func UserLog(c *fiber.Ctx) error { return err } -type Permission struct { - Name string `json:"name"` - Module string `json:"module"` -} - func SetPermission(name, module string) fiber.Handler { return func(c *fiber.Ctx) error { - c.Locals("permission", Permission{Name: name, Module: module}) + c.Locals("permission", biz.Permission{Name: name, Module: module}) return c.Next() } } func AdminRequired(c *fiber.Ctx) error { - fmt.Println("-------------------admin require middle+") - fmt.Println(c.Locals("permission")) + + isAdmin, err := biz.IsAdmin(c) + if err != nil { + return err + } + if !isAdmin { + return core.NewErrorCode(errcode.UserNoPermission) + } return c.Next() } @@ -65,67 +63,16 @@ func GroupRequired(c *fiber.Ctx) error { return c.Next() } - local := c.Locals("permission") - if local == nil { - return core.NewErrorCode(errcode.UserPermissionRequired) + has, err := biz.UserHasPermission(c) + if err != nil { + return err + } + if !has { + return core.NewErrorCode(errcode.UserNoPermission) } - p := local.(Permission) - fmt.Println(p) return c.Next() } -// -//func (a *Auth) GroupRequired(c *gin.Context) { -// user, _ := c.Get("currentUser") -// userId := user.(model.User).ID -// // admin直接通过 -// admin, _ := a.UserService.IsAdmin(userId) -// if admin { -// c.Next() -// } else { -// meta, ok := c.Get("meta") -// if !ok { -// return -// } -// routeMeta := meta.(router.Meta) -// if !routeMeta.Mount { -// c.Next() -// } else { -// hasPermission := a.GroupService.GetUserHasPermission(userId, routeMeta) -// if !hasPermission { -// _ = c.Error(response.UnifyResponse(10001, c)) -// c.Abort() -// return -// } else { -// c.Next() -// } -// } -// } -//} - -// -//func (a *Auth) AdminRequired(c *gin.Context) { -// if err := a.mountUser(c); err != nil { -// _ = c.Error(err) -// c.Abort() -// return -// } -// user, _ := c.Get("currentUser") -// currentUser := user.(model.User) -// admin, err := a.UserService.IsAdmin(currentUser.ID) -// if err != nil { -// _ = c.Error(response.UnifyResponse(10021, c)) -// c.Abort() -// return -// } -// if admin { -// c.Next() -// } else { -// _ = c.Error(response.UnifyResponse(10001, c)) -// c.Abort() -// return -// } -//} // //func (a *Auth) RefreshRequired(ctx *gin.Context) { // refreshToken, tokenErr := getHeaderToken(ctx) diff --git a/internal/server/routes.go b/internal/server/routes.go index 7aeef5c..739c985 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -11,7 +11,7 @@ func InitRoute(app *fiber.App) { app.Static("/upload", "storage/upload") app.Get("/", api.Hello) cms := app.Group("/cms") - // v1 := app.Group("/v1") + v1 := app.Group("/v1") cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) @@ -19,21 +19,18 @@ func InitRoute(app *fiber.App) { // FIXME 开发阶段先注释jwt cms.Use(LoginRequired) - //v1.Use(jwtware.New(jwtware.Config{ - // SigningKey: []byte("secret"), - //})) - userRouter := cms.Group("/user") - adminRouter := cms.Group("/admin") - logRouter := cms.Group("/log") - - bookRouter := app.Group("/v1/book").Use(GroupRequired) + bookRouter := v1.Group("/book").Use(GroupRequired).Use(SetPermission("book", "图书")) { - bookRouter.Use(SetPermission("book", "图书")).Get("/", api.GetBooks) + bookRouter.Get("/", api.GetBooks) bookRouter.Get("/:id", api.GetBook) bookRouter.Put("/:id", api.UpdateBook) bookRouter.Post("/", api.CreateBook) bookRouter.Delete("/:id", api.DeleteBook) } + + userRouter := cms.Group("/user") + adminRouter := cms.Group("/admin") + logRouter := cms.Group("/log") { userRouter.Use(AdminRequired).Post("/register", api.Register) userRouter.Put("/", api.UpdateMe) diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index 57254e8..5edb55d 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -18,6 +18,7 @@ const ( GuestGroupNotAllowDelete = 30003 PermissionNotFound = 30004 UserPermissionRequired = 40000 + UserNoPermission = 40001 ) func init() { @@ -36,5 +37,6 @@ func init() { GroupFound: "分组已存在", PermissionNotFound: "权限不存在", UserPermissionRequired: "用户权限必须存在", + UserNoPermission: "用户没有权限访问", } } From 66d3383a29d28e3343f0ddba7af8bfd486cdf06b Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Tue, 16 Nov 2021 10:25:44 +0800 Subject: [PATCH 38/44] feat : updateUser,getUsers --- api/admin.go | 16 +++++-------- internal/biz/admin.go | 21 ++++++++++++----- internal/biz/biz.go | 5 ++--- internal/biz/user.go | 16 ++++++------- internal/data/ent/schema/lin_user_group.go | 3 ++- internal/data/permission.go | 2 +- internal/data/user.go | 26 ++++++++++++++++++++++ internal/request/admin.go | 8 +++++-- internal/server/middleware.go | 11 ++++----- 9 files changed, 72 insertions(+), 36 deletions(-) diff --git a/api/admin.go b/api/admin.go index 5086f4e..205d5f5 100644 --- a/api/admin.go +++ b/api/admin.go @@ -1,27 +1,25 @@ package api import ( + "lin-cms-go/internal/biz" + "lin-cms-go/internal/request" + "github.com/gofiber/fiber/v2" "github.com/xushuhui/goal/core" "github.com/xushuhui/goal/utils" - "lin-cms-go/internal/biz" - "lin-cms-go/internal/request" ) func GetUsers(c *fiber.Ctx) error { var req request.GetUsers if err := core.ParseRequest(c, &req); err != nil { - return err } - data, err := biz.GetUsers(req) + data, err := biz.GetUsers(c.Context(), req.GroupId, core.GetPage(c), core.GetSize(c)) if err != nil { - return err } return core.SetData(c, data) - } func ChangeUserPassword(c *fiber.Ctx) error { @@ -35,11 +33,9 @@ func ChangeUserPassword(c *fiber.Ctx) error { return err } return core.SuccessResp(c) - } func DeleteUser(c *fiber.Ctx) error { - id, err := utils.StringToInt(c.Params("id")) if err != nil { return err @@ -49,7 +45,6 @@ func DeleteUser(c *fiber.Ctx) error { return err } return core.SuccessResp(c) - } func UpdateUser(c *fiber.Ctx) error { @@ -58,10 +53,9 @@ func UpdateUser(c *fiber.Ctx) error { return err } - err := biz.UpdateUser(req) + err := biz.UpdateUser(c.Context(), req.Id, req.GroupIds) if err != nil { return err } return core.SuccessResp(c) - } diff --git a/internal/biz/admin.go b/internal/biz/admin.go index 836a9a6..39c4f5f 100644 --- a/internal/biz/admin.go +++ b/internal/biz/admin.go @@ -2,17 +2,20 @@ package biz import ( "context" - "github.com/xushuhui/goal/core" - "golang.org/x/crypto/bcrypt" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" - "lin-cms-go/internal/request" "lin-cms-go/pkg/errcode" + + "github.com/xushuhui/goal/core" + "golang.org/x/crypto/bcrypt" ) -func GetUsers(req request.GetUsers) (res interface{}, err error) { +func GetUsers(ctx context.Context, groupId int, page, size int) (res interface{}, err error) { + list, err := data.NewPaging(page, size).ListUserByGroupId(ctx, groupId) + res = list return } + func ChangeUserPassword(ctx context.Context, userId int, password string) (err error) { user, err := data.GetLinUserIdentityByUserId(ctx, userId) if err != nil { @@ -30,6 +33,7 @@ func ChangeUserPassword(ctx context.Context, userId int, password string) (err e } return } + func DeleteUser(ctx context.Context, userId int) (err error) { _, err = data.GetLinUserById(ctx, userId) if model.IsNotFound(err) { @@ -39,6 +43,13 @@ func DeleteUser(ctx context.Context, userId int) (err error) { err = data.SoftDeleteUser(ctx, userId) return } -func UpdateUser(req request.UpdateUser) (err error) { + +func UpdateUser(ctx context.Context, userId int, groupId []int) (err error) { + _, err = data.GetLinUserById(ctx, userId) + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.UserNotFound) + return + } + err = data.AddLinUserGroupIDs(ctx, userId, groupId) return } diff --git a/internal/biz/biz.go b/internal/biz/biz.go index 27f41ef..b1399a8 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -2,12 +2,13 @@ package biz import ( "context" - "github.com/xushuhui/goal/core" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/pkg/enum" "lin-cms-go/pkg/errcode" + "github.com/xushuhui/goal/core" + "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v4" "github.com/xushuhui/goal/utils" @@ -34,7 +35,6 @@ func IsAdmin(c *fiber.Ctx) (is bool, err error) { } for _, v := range u.Edges.LinGroup { - if v.Level == enum.ROOT { is = true } @@ -64,7 +64,6 @@ func UserHasPermission(c *fiber.Ctx) (has bool, err error) { for _, p := range v.Edges.LinPermission { ps = append(ps, *p) } - } for _, p := range ps { if p.Module == userPermission.Module && p.Name == userPermission.Name { diff --git a/internal/biz/user.go b/internal/biz/user.go index 8e238ec..483c9e9 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -2,23 +2,21 @@ package biz import ( "context" - "errors" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" - - "github.com/xushuhui/goal/core" "lin-cms-go/internal/request" "lin-cms-go/pkg/errcode" "lin-cms-go/pkg/lib" "time" + "github.com/xushuhui/goal/core" + "github.com/golang-jwt/jwt/v4" "golang.org/x/crypto/bcrypt" ) func Login(ctx context.Context, username, password string) (res map[string]interface{}, err error) { - // 正确密码验证 userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, username) if model.IsNotFound(err) { @@ -50,13 +48,14 @@ func Login(ctx context.Context, username, password string) (res map[string]inter res["access_token"] = token return } + func Register(ctx context.Context, req request.Register) (err error) { userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, req.Username) if model.MaskNotFound(err) != nil { return err } if userIdentityModel != nil && userIdentityModel.ID > 0 { - err = errors.New("user is found") + err = core.NewErrorCode(errcode.UserNotFound) return } @@ -66,8 +65,8 @@ func Register(ctx context.Context, req request.Register) (err error) { } err = data.CreateLinUser(ctx, req.Username, string(hash), req.Email, req.GroupId) return - } + func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { _, err = data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { @@ -80,8 +79,8 @@ func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { err = data.UpdateLinUser(ctx, uid, req.Avatar, req.Nickname, req.Email) return } -func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, username string) (err error) { +func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, username string) (err error) { userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, username) if err != nil { return err @@ -102,6 +101,7 @@ func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, usernam return } + func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, err error) { user, err := data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { @@ -122,7 +122,7 @@ func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, res = make(map[string]interface{}) res["is_admin"] = isRoot - //data["permissions"] = permissions + // data["permissions"] = permissions return } diff --git a/internal/data/ent/schema/lin_user_group.go b/internal/data/ent/schema/lin_user_group.go index 951a1fb..c75edd8 100644 --- a/internal/data/ent/schema/lin_user_group.go +++ b/internal/data/ent/schema/lin_user_group.go @@ -1,11 +1,12 @@ package schema import ( + "time" + "entgo.io/ent" "entgo.io/ent/schema/field" "entgo.io/ent/schema/mixin" - "time" ) type TimeMixin struct { diff --git a/internal/data/permission.go b/internal/data/permission.go index 9e8dd74..2b2c2dd 100644 --- a/internal/data/permission.go +++ b/internal/data/permission.go @@ -10,6 +10,6 @@ func GetLinPermissionById(ctx context.Context, id int) (permission *model.LinPer permission, err = GetDB().LinPermission.Query().Where(linpermission.ID(id)).First(ctx) return } -func GetUserPermission(ctx context.Context, userId int, name, module string) { +func GetUserPermission(ctx context.Context, userId int, name, module string) { } diff --git a/internal/data/user.go b/internal/data/user.go index 3fc52f0..32afa7f 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -3,6 +3,7 @@ package data import ( "context" "lin-cms-go/internal/data/model" + "lin-cms-go/internal/data/model/lingroup" "lin-cms-go/internal/data/model/linuser" "lin-cms-go/internal/data/model/linuseridentiy" "time" @@ -63,9 +64,34 @@ func UpdateLinUserIdentityPassword(ctx context.Context, username, password strin return } + func SoftDeleteUser(ctx context.Context, userId int) (err error) { _, err = GetDB().LinUser.Update().Where(linuser.ID(userId)). SetDeleteTime(time.Now()).Save(ctx) return } + +func (p *Paging) ListUser(ctx context.Context) (users []*model.LinUser, err error) { + users, err = GetDB().LinUser.Query().WithLinGroup().Limit(p.Size).Offset(p.Offset).All(ctx) + return +} + +func (p *Paging) ListUserByGroupId(ctx context.Context, groupId int) (users []*model.LinUser, err error) { + groups, err := GetDB().LinGroup.Query().Where(lingroup.ID(groupId)).WithLinUser(func(query *model.LinUserQuery) { + query.Limit(p.Size).Offset(p.Offset).WithLinGroup() + }).All(ctx) + if err != nil { + return + } + for _, g := range groups { + users = append(users, g.Edges.LinUser...) + } + + return +} + +func AddLinUserGroupIDs(ctx context.Context, userId int, groupIds []int) (err error) { + _, err = GetDB().LinUser.Update().Where(linuser.ID(userId)).ClearLinGroup().AddLinGroupIDs(groupIds...).Save(ctx) + return +} diff --git a/internal/request/admin.go b/internal/request/admin.go index 155b06c..c9402de 100644 --- a/internal/request/admin.go +++ b/internal/request/admin.go @@ -1,27 +1,31 @@ package request type GetUsers struct { - GroupId int `json:"group_id" validate:"required"` - Pages + GroupId int `json:"group_id" ` } + type Pages struct { Count int `json:"count" validate:"required" comment:"数量"` Page int `json:"page" validate:"required" comment:"页码"` } + type ChangeUserPassword struct { Id int `json:"uid"` NewPassword string `json:"new_password" validate:"required" comment:"新密码"` ConfirmPassword string `json:"confirm_password" validate:"required,eqcsfield=NewPassword" comment:"确认密码"` } + type UpdateUser struct { Id int `json:"id" validate:"required"` GroupIds []int `json:"group_ids" validate:"required"` } + type CreateGroup struct { Name string `json:"name" validate:"required" comment:"分组名称"` Info string `json:"info" validate:"required" comment:"分组信息"` PermissionIds []int `json:"permission_ids"` } + type UpdateGroup struct { Name string `json:"name" validate:"required" comment:"分组名称" ` Info string `json:"info" validate:"required" comment:"分组信息" ` diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 7535b89..f0a56dc 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -1,12 +1,14 @@ package server import ( - "github.com/gofiber/fiber/v2" - jwtware "github.com/gofiber/jwt/v3" - "github.com/xushuhui/goal/core" "lin-cms-go/internal/biz" "lin-cms-go/internal/data" "lin-cms-go/pkg/errcode" + + jwtware "github.com/gofiber/jwt/v3" + + "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" ) func UserLog(c *fiber.Ctx) error { @@ -33,7 +35,6 @@ func SetPermission(name, module string) fiber.Handler { } func AdminRequired(c *fiber.Ctx) error { - isAdmin, err := biz.IsAdmin(c) if err != nil { return err @@ -51,7 +52,7 @@ func LoginRequired(c *fiber.Ctx) error { }) return c.Next() } - return c.Next() + return core.NewErrorCode(errcode.UserNoPermission) } func GroupRequired(c *fiber.Ctx) error { From 0cd43903c9de29b5eb846cb946c4ba2fe6bb7248 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Tue, 16 Nov 2021 13:35:50 +0800 Subject: [PATCH 39/44] fix: permission --- docs/rest.http | 4 ++++ internal/biz/biz.go | 9 +++++++-- internal/data/init.go | 21 +++++++++++---------- internal/data/user.go | 6 ++++-- internal/server/middleware.go | 13 +++++-------- internal/server/routes.go | 8 ++++---- pkg/lib/jwt.go | 12 +++++++++++- 7 files changed, 46 insertions(+), 27 deletions(-) diff --git a/docs/rest.http b/docs/rest.http index 6069bc3..1f81743 100644 --- a/docs/rest.http +++ b/docs/rest.http @@ -51,3 +51,7 @@ Authorization: Bearer {{token}} DELETE http://localhost:3000/cms/admin/group/1 Content-Type: application/json Authorization: Bearer {{token}} +### +GET http://localhost:3000/v1/book +Content-Type: application/json +Authorization: Bearer {{token}} diff --git a/internal/biz/biz.go b/internal/biz/biz.go index b1399a8..dfff025 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -28,7 +28,10 @@ func LocalUser(c *fiber.Ctx) (user model.LinUser) { func IsAdmin(c *fiber.Ctx) (is bool, err error) { user := LocalUser(c) - + if user.ID == 0 { + err = core.NewErrorCode(errcode.ErrorAuthToken) + return + } u, err := data.GetLinUserWithGroupById(c.Context(), user.ID) if err != nil { return @@ -51,9 +54,11 @@ func UserHasPermission(c *fiber.Ctx) (has bool, err error) { user := LocalUser(c) u, err := data.GetLinUserWithGroupById(context.Background(), user.ID) - if err != nil { + if model.IsNotFound(err) { + err = core.NewErrorCode(errcode.UserNotFound) return } + local := c.Locals("permission") if local == nil { return false, core.NewErrorCode(errcode.UserPermissionRequired) diff --git a/internal/data/init.go b/internal/data/init.go index f1e5a28..05d9252 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -2,18 +2,21 @@ package data import ( "context" - "github.com/pkg/errors" "lin-cms-go/internal/conf" - - "github.com/xushuhui/goal/core" "lin-cms-go/internal/data/model" "sync" + "github.com/pkg/errors" + + "github.com/xushuhui/goal/core" + _ "github.com/go-sql-driver/mysql" ) -var ds *DataSource -var once sync.Once +var ( + ds *DataSource + once sync.Once +) type Paging struct { Page int @@ -38,15 +41,13 @@ func NewDataSource(conf *conf.Data) { ds = &DataSource{ Db: make(map[string]*model.Client), } - db := NewDBClient(conf) - ds.Db["default"] = db + + ds.Db["default"] = NewDBClient(conf) } func NewDBClient(conf *conf.Data) (db *model.Client) { - var err error once.Do(func() { - db, err = model.Open(conf.Database.Driver, conf.Database.Source, model.Debug()) if err != nil { panic(err) @@ -66,6 +67,7 @@ func (d *DataSource) GetDb(name string) *model.Client { func GetDB() *model.Client { return ds.GetDb("default") } + func WithTx(ctx context.Context, client *model.Client, fn func(tx *model.Tx) error) error { tx, err := client.Tx(ctx) if err != nil { @@ -80,7 +82,6 @@ func WithTx(ctx context.Context, client *model.Client, fn func(tx *model.Tx) err if err := fn(tx); err != nil { if rerr := tx.Rollback(); rerr != nil { err = errors.Wrapf(err, "rolling back transaction: %v", rerr) - } return err } diff --git a/internal/data/user.go b/internal/data/user.go index 32afa7f..348cf6d 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -45,8 +45,10 @@ func GetLinUserById(ctx context.Context, uid int) (model *model.LinUser, err err return } -func GetLinUserWithGroupById(ctx context.Context, uid int) (model *model.LinUser, err error) { - model, err = GetDB().LinUser.Query().Where(linuser.ID(uid)).WithLinGroup().First(ctx) +func GetLinUserWithGroupById(ctx context.Context, uid int) (users *model.LinUser, err error) { + users, err = GetDB().LinUser.Query().Where(linuser.ID(uid)).WithLinGroup(func(query *model.LinGroupQuery) { + query.WithLinPermission() + }).First(ctx) return } diff --git a/internal/server/middleware.go b/internal/server/middleware.go index f0a56dc..53fea54 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -5,8 +5,6 @@ import ( "lin-cms-go/internal/data" "lin-cms-go/pkg/errcode" - jwtware "github.com/gofiber/jwt/v3" - "github.com/gofiber/fiber/v2" "github.com/xushuhui/goal/core" ) @@ -46,13 +44,12 @@ func AdminRequired(c *fiber.Ctx) error { } func LoginRequired(c *fiber.Ctx) error { - if c.Method() != fiber.MethodOptions { - jwtware.New(jwtware.Config{ - SigningKey: []byte("secret"), - }) - return c.Next() + user := biz.LocalUser(c) + if user.ID == 0 { + return core.NewErrorCode(errcode.AuthCheckTokenFail) } - return core.NewErrorCode(errcode.UserNoPermission) + + return c.Next() } func GroupRequired(c *fiber.Ctx) error { diff --git a/internal/server/routes.go b/internal/server/routes.go index 739c985..b7281d5 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -2,6 +2,7 @@ package server import ( "lin-cms-go/api" + "lin-cms-go/pkg/lib" "github.com/gofiber/fiber/v2" ) @@ -16,10 +17,9 @@ func InitRoute(app *fiber.App) { cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) - // FIXME 开发阶段先注释jwt - cms.Use(LoginRequired) - - bookRouter := v1.Group("/book").Use(GroupRequired).Use(SetPermission("book", "图书")) + cms.Use(lib.ParseJwt(), LoginRequired) + v1.Use(lib.ParseJwt(), LoginRequired) + bookRouter := v1.Group("/book").Use(SetPermission("book", "图书")).Use(GroupRequired) { bookRouter.Get("/", api.GetBooks) bookRouter.Get("/:id", api.GetBook) diff --git a/pkg/lib/jwt.go b/pkg/lib/jwt.go index 31afdd0..3c08620 100644 --- a/pkg/lib/jwt.go +++ b/pkg/lib/jwt.go @@ -1,14 +1,24 @@ package lib import ( + "github.com/gofiber/fiber/v2" + jwtware "github.com/gofiber/jwt/v3" "github.com/golang-jwt/jwt/v4" ) +var jwtKey = "secret" + func GenerateJwt(claims jwt.MapClaims) (jwtToken string, err error) { // Create token token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) // Generate encoded token and send it as response. - jwtToken, err = token.SignedString([]byte("secret")) + jwtToken, err = token.SignedString([]byte(jwtKey)) return } + +func ParseJwt() fiber.Handler { + return jwtware.New(jwtware.Config{ + SigningKey: []byte(jwtKey), + }) +} From d91925d1a28de46429e333a3ce928a9a3ceb7af6 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Tue, 16 Nov 2021 18:18:48 +0800 Subject: [PATCH 40/44] fix: permission --- README.md | 2 +- Dockerfile => deploy/Dockerfile | 0 internal/biz/permission.go | 11 ++++++++++- internal/data/permission.go | 9 ++++++++- internal/server/middleware.go | 8 +++++++- 5 files changed, 26 insertions(+), 4 deletions(-) rename Dockerfile => deploy/Dockerfile (100%) diff --git a/README.md b/README.md index 8ef3769..17d9e83 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ ## 专栏教程 (todo) -* [《lin cms go&vue 教程》](https://github.com/xushuhui/lin-cms-go) 专栏教程连载更新中,通过实战开源前后端分离 cms——lin cms 全家桶(lin-cms-vue & lin-cms-go)为一个前端应用实现内容管理系统。一套教程入门上手 vue、fiber 两大框架,自用、工作、私单一次打通。 +* lin cms 全家桶(lin-cms-vue & lin-cms-go)为一个前端应用实现内容管理系统。一套教程入门上手 vue、fiber 两大框架。 * 读者反馈:[《lin cms php&vue 教程》读者反馈贴](https://github.com/xushuhui/lin-cms-go/issues/47) diff --git a/Dockerfile b/deploy/Dockerfile similarity index 100% rename from Dockerfile rename to deploy/Dockerfile diff --git a/internal/biz/permission.go b/internal/biz/permission.go index 274feb2..20aed27 100644 --- a/internal/biz/permission.go +++ b/internal/biz/permission.go @@ -14,7 +14,6 @@ func GetAllPermissions(ctx context.Context) (res interface{}, err error) { } m := make(map[string][]model.LinPermission) for _, v := range list { - m[v.Module] = append(m[v.Module], *v) } res = m @@ -30,6 +29,7 @@ func DispatchPermissions(ctx context.Context, groupId int, permissionIds []int) return } + func RemovePermissions(ctx context.Context, groupId int, permissionIds []int) (err error) { _, err = data.GetGroupPermissionByGroupId(ctx, groupId) if err != nil { @@ -38,3 +38,12 @@ func RemovePermissions(ctx context.Context, groupId int, permissionIds []int) (e err = data.DeleteGroupPermission(ctx, groupId, permissionIds) return } + +func CreateIfNoPermissions(ctx context.Context, p Permission) (err error) { + _, err = data.GetPermission(ctx, p.Name, p.Module) + if model.IsNotFound(err) { + err = data.CreatePermission(context.Background(), p.Name, p.Module) + } + + return +} diff --git a/internal/data/permission.go b/internal/data/permission.go index 2b2c2dd..66667d5 100644 --- a/internal/data/permission.go +++ b/internal/data/permission.go @@ -11,5 +11,12 @@ func GetLinPermissionById(ctx context.Context, id int) (permission *model.LinPer return } -func GetUserPermission(ctx context.Context, userId int, name, module string) { +func GetPermission(ctx context.Context, name, module string) (p *model.LinPermission, err error) { + p, err = GetDB().LinPermission.Query().Where(linpermission.Module(module), linpermission.Name(name)).First(ctx) + return +} + +func CreatePermission(ctx context.Context, name, module string) (err error) { + _, err = GetDB().LinPermission.Create().SetModule(module).SetName(name).SetMount(1).Save(ctx) + return } diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 53fea54..866270a 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -27,7 +27,13 @@ func UserLog(c *fiber.Ctx) error { func SetPermission(name, module string) fiber.Handler { return func(c *fiber.Ctx) error { - c.Locals("permission", biz.Permission{Name: name, Module: module}) + p := biz.Permission{Name: name, Module: module} + err := biz.CreateIfNoPermissions(c.Context(), p) + if err != nil { + return err + } + c.Locals("permission", p) + return c.Next() } } From 34024721189d8d327edce4914a75dc00b2b56900 Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Wed, 17 Nov 2021 14:04:12 +0800 Subject: [PATCH 41/44] refactor: error --- go.mod | 2 +- go.sum | 9 +++++++-- internal/biz/admin.go | 4 ++-- internal/biz/biz.go | 6 +++--- internal/biz/book.go | 8 ++++---- internal/biz/group.go | 17 +++++++++-------- internal/biz/user.go | 12 ++++++------ internal/data/ent/schema/lin_user.go | 3 +++ internal/server/middleware.go | 6 +++--- 9 files changed, 38 insertions(+), 29 deletions(-) diff --git a/go.mod b/go.mod index 8547de9..da44d78 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/pkg/errors v0.9.1 github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/stretchr/testify v1.7.0 - github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d + github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect golang.org/x/text v0.3.7 // indirect diff --git a/go.sum b/go.sum index f43b26a..04cf59a 100644 --- a/go.sum +++ b/go.sum @@ -146,6 +146,7 @@ github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= @@ -186,8 +187,10 @@ github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:F github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= @@ -254,8 +257,10 @@ github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d h1:p9VAqF9oQ3PMFeOgYvHf0ooX/PkyCAN6G+O9DEEILCQ= -github.com/xushuhui/goal v0.0.0-20211111072059-9e0980ea752d/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= +github.com/xushuhui/goal v0.0.0-20211116121521-afb3872f881c h1:yKTjapqcNjriF9Gy84glT68nQIwfrb8AL6M2H87FVGU= +github.com/xushuhui/goal v0.0.0-20211116121521-afb3872f881c/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= +github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40 h1:vcKaNC1maKJUsm9aVqg4hSaXFAvzqV9rrXf+N8YdB1A= +github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= diff --git a/internal/biz/admin.go b/internal/biz/admin.go index 39c4f5f..33bb678 100644 --- a/internal/biz/admin.go +++ b/internal/biz/admin.go @@ -37,7 +37,7 @@ func ChangeUserPassword(ctx context.Context, userId int, password string) (err e func DeleteUser(ctx context.Context, userId int) (err error) { _, err = data.GetLinUserById(ctx, userId) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } err = data.SoftDeleteUser(ctx, userId) @@ -47,7 +47,7 @@ func DeleteUser(ctx context.Context, userId int) (err error) { func UpdateUser(ctx context.Context, userId int, groupId []int) (err error) { _, err = data.GetLinUserById(ctx, userId) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } err = data.AddLinUserGroupIDs(ctx, userId, groupId) diff --git a/internal/biz/biz.go b/internal/biz/biz.go index dfff025..feec847 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -29,7 +29,7 @@ func LocalUser(c *fiber.Ctx) (user model.LinUser) { func IsAdmin(c *fiber.Ctx) (is bool, err error) { user := LocalUser(c) if user.ID == 0 { - err = core.NewErrorCode(errcode.ErrorAuthToken) + err = core.UnAuthenticatedError(errcode.ErrorAuthToken) return } u, err := data.GetLinUserWithGroupById(c.Context(), user.ID) @@ -55,13 +55,13 @@ func UserHasPermission(c *fiber.Ctx) (has bool, err error) { u, err := data.GetLinUserWithGroupById(context.Background(), user.ID) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } local := c.Locals("permission") if local == nil { - return false, core.NewErrorCode(errcode.UserPermissionRequired) + return false, core.UnAuthenticatedError(errcode.UserPermissionRequired) } userPermission := local.(Permission) var ps []model.LinPermission diff --git a/internal/biz/book.go b/internal/biz/book.go index 97e774d..44df6de 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -27,7 +27,7 @@ func GetBookTotal(ctx context.Context) (total int, err error) { func UpdateBook(ctx context.Context, id int, req request.UpdateBook) (err error) { _, err = data.GetBookById(ctx, id) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.BookNotFound) + err = core.NotFoundError(errcode.BookNotFound) return } if err != nil { @@ -43,7 +43,7 @@ func CreateBook(ctx context.Context, req request.CreateBook) (err error) { return err } if book != nil { - err = core.NewErrorCode(errcode.BookTitleRepetition) + err = core.ParamsError(errcode.BookTitleRepetition) return } err = data.CreateBook(ctx, req.Title, req.Author, req.Summary, req.Image) @@ -53,7 +53,7 @@ func CreateBook(ctx context.Context, req request.CreateBook) (err error) { func DeleteBook(ctx context.Context, id int) (err error) { _, err = data.GetBookById(ctx, id) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.BookNotFound) + err = core.NotFoundError(errcode.BookNotFound) return } err = data.SoftDeleteBook(ctx, id) @@ -63,7 +63,7 @@ func DeleteBook(ctx context.Context, id int) (err error) { func GetBook(ctx context.Context, id int) (res interface{}, err error) { book, err := data.GetBookById(ctx, id) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.BookNotFound) + err = core.NotFoundError(errcode.BookNotFound) return } res = book diff --git a/internal/biz/group.go b/internal/biz/group.go index db7250c..0f38f09 100644 --- a/internal/biz/group.go +++ b/internal/biz/group.go @@ -2,12 +2,13 @@ package biz import ( "context" - "github.com/xushuhui/goal/core" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" "lin-cms-go/pkg/enum" "lin-cms-go/pkg/errcode" + + "github.com/xushuhui/goal/core" ) type Group struct { @@ -28,7 +29,7 @@ func GetGroup(ctx context.Context, id int) (res interface{}, err error) { var linGroupModel *model.LinGroup linGroupModel, err = data.GetLinGroupById(ctx, id) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.GroupNotFound) + err = core.NotFoundError(errcode.GroupNotFound) return } res = Group{Id: linGroupModel.ID, Name: linGroupModel.Name, Info: linGroupModel.Info, Level: linGroupModel.Level} @@ -46,13 +47,13 @@ func simplifyGroup(groupModel []*model.LinGroup) []Group { func CreateGroup(ctx context.Context, name string, info string, permissionIds []int) (err error) { group, _ := data.GetLinGroupByName(ctx, name) if group != nil { - err = core.NewErrorCode(errcode.GroupFound) + err = core.ParamsError(errcode.GroupFound) return } for _, v := range permissionIds { _, err = data.GetLinPermissionById(ctx, v) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.PermissionNotFound) + err = core.NotFoundError(errcode.PermissionNotFound) return } } @@ -71,7 +72,7 @@ func CreateGroup(ctx context.Context, name string, info string, permissionIds [] func UpdateGroup(ctx context.Context, id int, req request.UpdateGroup) (err error) { _, err = data.GetLinGroupById(ctx, id) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.GroupNotFound) + err = core.NotFoundError(errcode.GroupNotFound) return } err = data.UpdateGroup(ctx, id, req.Name, req.Info) @@ -82,19 +83,19 @@ func DeleteGroup(ctx context.Context, id int) (err error) { var linGroup *model.LinGroup linGroup, err = data.GetLinGroupById(ctx, id) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.GroupNotFound) + err = core.NotFoundError(errcode.GroupNotFound) return } if err != nil { return } if linGroup.Level == enum.ROOT { - err = core.NewErrorCode(errcode.RootGroupNotAllowDelete) + err = core.ParamsError(errcode.RootGroupNotAllowDelete) return } if linGroup.Level == enum.GUEST { - err = core.NewErrorCode(errcode.GuestGroupNotAllowDelete) + err = core.ParamsError(errcode.GuestGroupNotAllowDelete) return } diff --git a/internal/biz/user.go b/internal/biz/user.go index 483c9e9..2505eb8 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -29,7 +29,7 @@ func Login(ctx context.Context, username, password string) (res map[string]inter err = bcrypt.CompareHashAndPassword([]byte(userIdentityModel.Credential), []byte(password)) if err != nil { - err = core.NewErrorCode(errcode.ErrorPassWord) + err = core.ParamsError(errcode.ErrorPassWord) return } user, err := data.GetLinUserById(ctx, userIdentityModel.UserID) @@ -55,7 +55,7 @@ func Register(ctx context.Context, req request.Register) (err error) { return err } if userIdentityModel != nil && userIdentityModel.ID > 0 { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.ParamsError(errcode.UserFound) return } @@ -70,7 +70,7 @@ func Register(ctx context.Context, req request.Register) (err error) { func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { _, err = data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } if err != nil { @@ -87,7 +87,7 @@ func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, usernam } err = bcrypt.CompareHashAndPassword([]byte(userIdentityModel.Credential), []byte(req.OldPassword)) if err != nil { - err = core.NewErrorCode(errcode.ErrorPassWord) + err = core.ParamsError(errcode.ErrorPassWord) return } hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) @@ -105,7 +105,7 @@ func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, usernam func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, err error) { user, err := data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } if err != nil { @@ -133,7 +133,7 @@ type LinUser struct { func GetMyInfomation(ctx context.Context, uid int) (res LinUser, err error) { usermodel, err := data.GetLinUserById(ctx, uid) if model.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + err = core.NotFoundError(errcode.UserNotFound) return } res = LinUser{*usermodel} diff --git a/internal/data/ent/schema/lin_user.go b/internal/data/ent/schema/lin_user.go index 6be21a0..946d5aa 100644 --- a/internal/data/ent/schema/lin_user.go +++ b/internal/data/ent/schema/lin_user.go @@ -17,11 +17,13 @@ func (LinUser) Annotations() []schema.Annotation { entsql.Annotation{Table: "lin_user"}, } } + func (LinUser) Mixin() []ent.Mixin { return []ent.Mixin{ TimeMixin{}, } } + func (LinUser) Fields() []ent.Field { return []ent.Field{ field.String("username").Comment("用户名,唯一").Unique(), @@ -30,6 +32,7 @@ func (LinUser) Fields() []ent.Field { field.String("email").Comment("邮箱").Unique(), } } + func (LinUser) Edges() []ent.Edge { return []ent.Edge{ edge.To("lin_user_identiy", LinUserIdentiy.Type), diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 866270a..51732dc 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -44,7 +44,7 @@ func AdminRequired(c *fiber.Ctx) error { return err } if !isAdmin { - return core.NewErrorCode(errcode.UserNoPermission) + return core.UnAuthenticatedError(errcode.UserNoPermission) } return c.Next() } @@ -52,7 +52,7 @@ func AdminRequired(c *fiber.Ctx) error { func LoginRequired(c *fiber.Ctx) error { user := biz.LocalUser(c) if user.ID == 0 { - return core.NewErrorCode(errcode.AuthCheckTokenFail) + return core.UnAuthenticatedError(errcode.AuthCheckTokenFail) } return c.Next() @@ -72,7 +72,7 @@ func GroupRequired(c *fiber.Ctx) error { return err } if !has { - return core.NewErrorCode(errcode.UserNoPermission) + return core.UnAuthenticatedError(errcode.UserNoPermission) } return c.Next() } From 8d06c53cc8faa7c5cd311fcef093e972069ce72d Mon Sep 17 00:00:00 2001 From: xushuhui <474497097@qq.com> Date: Tue, 23 Nov 2021 22:13:12 +0800 Subject: [PATCH 42/44] refactor: error wrap --- README.md | 2 +- go.sum | 2 -- internal/biz/biz.go | 1 + internal/biz/book.go | 16 +++++++++++++++- internal/biz/group.go | 22 +++++++++++++++++++++- internal/biz/log.go | 16 ++++++++++++++-- internal/biz/user.go | 38 +++++++++++++++++++++++++++++++++++--- 7 files changed, 87 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 17d9e83..5fbc162 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@

php version - fiber version + fiber version lisence

diff --git a/go.sum b/go.sum index 04cf59a..adbc864 100644 --- a/go.sum +++ b/go.sum @@ -257,8 +257,6 @@ github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xushuhui/goal v0.0.0-20211116121521-afb3872f881c h1:yKTjapqcNjriF9Gy84glT68nQIwfrb8AL6M2H87FVGU= -github.com/xushuhui/goal v0.0.0-20211116121521-afb3872f881c/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40 h1:vcKaNC1maKJUsm9aVqg4hSaXFAvzqV9rrXf+N8YdB1A= github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= diff --git a/internal/biz/biz.go b/internal/biz/biz.go index feec847..bb83504 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -22,6 +22,7 @@ func LocalUser(c *fiber.Ctx) (user model.LinUser) { jwtToken := local.(*jwt.Token) claims := jwtToken.Claims.(jwt.MapClaims) bytes, _ := utils.JSONEncode(claims["user"]) + utils.JSONDecode(bytes, &user) return } diff --git a/internal/biz/book.go b/internal/biz/book.go index 44df6de..5f0f0ed 100644 --- a/internal/biz/book.go +++ b/internal/biz/book.go @@ -2,6 +2,8 @@ package biz import ( "context" + "github.com/pkg/errors" + "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" @@ -40,13 +42,17 @@ func UpdateBook(ctx context.Context, id int, req request.UpdateBook) (err error) func CreateBook(ctx context.Context, req request.CreateBook) (err error) { book, err := data.GetBookByTitle(ctx, req.Title) if model.MaskNotFound(err) != nil { - return err + return errors.Wrap(err, "GetBookByTitleError") } if book != nil { err = core.ParamsError(errcode.BookTitleRepetition) return } err = data.CreateBook(ctx, req.Title, req.Author, req.Summary, req.Image) + if err != nil { + err = errors.Wrap(err, "createBookError") + } + return } @@ -56,6 +62,10 @@ func DeleteBook(ctx context.Context, id int) (err error) { err = core.NotFoundError(errcode.BookNotFound) return } + if err != nil { + + return errors.Wrap(err, "GetBookByIdError") + } err = data.SoftDeleteBook(ctx, id) return } @@ -66,6 +76,10 @@ func GetBook(ctx context.Context, id int) (res interface{}, err error) { err = core.NotFoundError(errcode.BookNotFound) return } + if err != nil { + err = errors.Wrap(err, "GetBookError") + return + } res = book return } diff --git a/internal/biz/group.go b/internal/biz/group.go index 0f38f09..ee1c734 100644 --- a/internal/biz/group.go +++ b/internal/biz/group.go @@ -2,6 +2,7 @@ package biz import ( "context" + "github.com/pkg/errors" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" @@ -32,6 +33,7 @@ func GetGroup(ctx context.Context, id int) (res interface{}, err error) { err = core.NotFoundError(errcode.GroupNotFound) return } + res = Group{Id: linGroupModel.ID, Name: linGroupModel.Name, Info: linGroupModel.Info, Level: linGroupModel.Level} return } @@ -56,14 +58,20 @@ func CreateGroup(ctx context.Context, name string, info string, permissionIds [] err = core.NotFoundError(errcode.PermissionNotFound) return } + if err != nil { + err = errors.Wrap(err, "GetLinPermissionById err") + return + } } groupModel, err := data.CreateGroup(ctx, name, info, enum.USER) if err != nil { + err = errors.Wrap(err, "CreateGroup err") return } err = data.BatchCreateGroupPermission(ctx, groupModel.ID, permissionIds) if err != nil { + err = errors.Wrap(err, "BatchCreateGroupPermission err") return } return @@ -75,7 +83,15 @@ func UpdateGroup(ctx context.Context, id int, req request.UpdateGroup) (err erro err = core.NotFoundError(errcode.GroupNotFound) return } + if err != nil { + err = errors.Wrap(err, "GetLinGroupById") + return + } err = data.UpdateGroup(ctx, id, req.Name, req.Info) + if err != nil { + err = errors.Wrap(err, "UpdateGroup") + return + } return } @@ -87,6 +103,7 @@ func DeleteGroup(ctx context.Context, id int) (err error) { return } if err != nil { + err = errors.Wrap(err, "GetLinGroupById ") return } if linGroup.Level == enum.ROOT { @@ -100,6 +117,9 @@ func DeleteGroup(ctx context.Context, id int) (err error) { } err = data.DeleteGroup(ctx, id) - + if err != nil { + err = errors.Wrap(err, "DeleteGroup ") + return + } return } diff --git a/internal/biz/log.go b/internal/biz/log.go index d6a4f34..3dcccad 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -2,6 +2,7 @@ package biz import ( "context" + "github.com/pkg/errors" "github.com/xushuhui/goal/utils" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" @@ -25,10 +26,12 @@ func GetLogs(ctx context.Context, req request.GetLogs, page int, size int) (res query = append(query, q) } logs, err = paging.Search(ctx, query) - total = data.GetSearchTotal(ctx, query) if err != nil { + err = errors.Wrap(err, "Search ") return } + total = data.GetSearchTotal(ctx, query) + res = logs return } @@ -51,6 +54,10 @@ func SearchLogs(ctx context.Context, req request.SearchLogs, page int, size int) query = append(query, data.WithKeyword(req.Name)) } logs, err = paging.Search(ctx, query) + if err != nil { + err = errors.Wrap(err, "Search ") + return + } total = data.GetSearchTotal(ctx, query) res = logs return @@ -59,8 +66,13 @@ func GetLogUsers(ctx context.Context, page, size int) (res interface{}, total in paging := data.NewPaging(page, size) res, err = paging.GetLogUsers(ctx) if err != nil { + err = errors.Wrap(err, "GetLogUsers ") + return + } + total, err = data.GetLogUsersTotal(ctx) + if err != nil { + err = errors.Wrap(err, "GetLogUsersTotal ") return } - total, _ = data.GetLogUsersTotal(ctx) return } diff --git a/internal/biz/user.go b/internal/biz/user.go index 2505eb8..aa8337b 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -2,6 +2,7 @@ package biz import ( "context" + "github.com/pkg/errors" "lin-cms-go/internal/data" "lin-cms-go/internal/data/model" "lin-cms-go/internal/request" @@ -24,16 +25,22 @@ func Login(ctx context.Context, username, password string) (res map[string]inter return } if err != nil { + err = errors.Wrap(err, "GetLinUserIdentityByIdentifier ") return } err = bcrypt.CompareHashAndPassword([]byte(userIdentityModel.Credential), []byte(password)) - if err != nil { + if err == bcrypt.ErrMismatchedHashAndPassword { err = core.ParamsError(errcode.ErrorPassWord) return } + if err != nil { + err = errors.Wrap(err, "CompareHashAndPassword ") + return + } user, err := data.GetLinUserById(ctx, userIdentityModel.UserID) if err != nil { + err = errors.Wrap(err, "GetLinUserById ") return } // jwt @@ -42,6 +49,7 @@ func Login(ctx context.Context, username, password string) (res map[string]inter claims["exp"] = time.Now().Add(time.Hour * 72).Unix() token, err := lib.GenerateJwt(claims) if err != nil { + err = errors.Wrap(err, "GenerateJwt ") return } res = make(map[string]interface{}) @@ -52,7 +60,8 @@ func Login(ctx context.Context, username, password string) (res map[string]inter func Register(ctx context.Context, req request.Register) (err error) { userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, req.Username) if model.MaskNotFound(err) != nil { - return err + err = errors.Wrap(err, "GetLinUserIdentityByIdentifier ") + return } if userIdentityModel != nil && userIdentityModel.ID > 0 { err = core.ParamsError(errcode.UserFound) @@ -61,9 +70,14 @@ func Register(ctx context.Context, req request.Register) (err error) { hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { + err = errors.Wrap(err, "GenerateFromPassword ") return } err = data.CreateLinUser(ctx, req.Username, string(hash), req.Email, req.GroupId) + if err != nil { + err = errors.Wrap(err, "CreateLinUser ") + return + } return } @@ -74,28 +88,40 @@ func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { return } if err != nil { + err = errors.Wrap(err, "GetLinUserById ") return } err = data.UpdateLinUser(ctx, uid, req.Avatar, req.Nickname, req.Email) + if err != nil { + err = errors.Wrap(err, "UpdateLinUser ") + return + } return } func ChangeMyPassword(ctx context.Context, req request.ChangeMyPassword, username string) (err error) { userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, username) if err != nil { + err = errors.Wrap(err, "GetLinUserIdentityByIdentifier ") return err } err = bcrypt.CompareHashAndPassword([]byte(userIdentityModel.Credential), []byte(req.OldPassword)) - if err != nil { + if err == bcrypt.ErrMismatchedHashAndPassword { err = core.ParamsError(errcode.ErrorPassWord) return } + if err != nil { + err = errors.Wrap(err, "CompareHashAndPassword ") + return + } hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) if err != nil { + err = errors.Wrap(err, "GenerateFromPassword ") return } err = data.UpdateLinUserIdentityPassword(ctx, username, string(hash)) if err != nil { + err = errors.Wrap(err, "UpdateLinUserIdentityPassword ") return } @@ -109,10 +135,12 @@ func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, return } if err != nil { + err = errors.Wrap(err, "GetLinUserById ") return } groupModel, err := user.QueryLinGroup().First(ctx) if err != nil { + err = errors.Wrap(err, "user.QueryLinGroup ") return } var isRoot bool @@ -136,6 +164,10 @@ func GetMyInfomation(ctx context.Context, uid int) (res LinUser, err error) { err = core.NotFoundError(errcode.UserNotFound) return } + if err != nil { + err = errors.Wrap(err, "GetLinUserById ") + return + } res = LinUser{*usermodel} return } From 545203c760970ecdfb54a00d536e88729b03bc96 Mon Sep 17 00:00:00 2001 From: Shuhui Xu <474497097@qq.com> Date: Tue, 20 Sep 2022 14:19:03 +0800 Subject: [PATCH 43/44] fix; doc --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5fbc162..e240fe6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

- php version + go version fiber version lisence

@@ -24,7 +24,7 @@ * lin cms 全家桶(lin-cms-vue & lin-cms-go)为一个前端应用实现内容管理系统。一套教程入门上手 vue、fiber 两大框架。 -* 读者反馈:[《lin cms php&vue 教程》读者反馈贴](https://github.com/xushuhui/lin-cms-go/issues/47) +* 读者反馈:[《lin cms go &vue 教程》读者反馈贴](https://github.com/xushuhui/lin-cms-go/issues/47) ## 线上文档地址(完善中) @@ -95,6 +95,7 @@ git clone https://github.com/xushuhui/lin-cms-go.git ## 安装依赖包 ```bash + go mod tidy ``` From 4d71d19ce2fe2cf0fdbc04d0801dc57021985e23 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 7 Mar 2023 00:42:49 +0000 Subject: [PATCH 44/44] chore(deps): bump golang.org/x/crypto Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.0.0-20210921155107-089bfa567519 to 0.1.0. - [Release notes](https://github.com/golang/crypto/releases) - [Commits](https://github.com/golang/crypto/commits/v0.1.0) --- updated-dependencies: - dependency-name: golang.org/x/crypto dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- go.mod | 4 +--- go.sum | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index da44d78..ec1b793 100644 --- a/go.mod +++ b/go.mod @@ -15,9 +15,7 @@ require ( github.com/rogpeppe/go-internal v1.8.1-0.20211023094830-115ce09fd6b4 // indirect github.com/stretchr/testify v1.7.0 github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40 - golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 - golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect - golang.org/x/text v0.3.7 // indirect + golang.org/x/crypto v0.1.0 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index adbc864..a3b63de 100644 --- a/go.sum +++ b/go.sum @@ -260,6 +260,7 @@ github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40 h1:vcKaNC1maKJUsm9aVqg4hSaXFAvzqV9rrXf+N8YdB1A= github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40/go.mod h1:tt/FlyU4tD/Zhg1ncrgGfmgwd0PMykAgShbSR5sDMWc= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= @@ -276,8 +277,9 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU= +golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -297,6 +299,7 @@ golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCc golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -315,6 +318,8 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -324,6 +329,7 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -346,16 +352,21 @@ golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ= -golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -379,6 +390,7 @@ golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=