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 diff --git a/.gitignore b/.gitignore index 5a9c45d..f674dda 100644 --- a/.gitignore +++ b/.gitignore @@ -2,9 +2,8 @@ /.idea /.vscode *.exe -/storage/* +*.log -/configs/*.yaml /tmp .air.conf \ No newline at end of file diff --git a/README.md b/README.md index 7594832..e240fe6 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,149 @@ -# lin-cms-go -## 框架选型 -fiber ent +

+ + +
+ lin-cms-go +

-lin-cms-go 不断更新。let's go +

+ go version + fiber version + lisence +

-## lin-cms 接口文档 -https://doc.cms.talelin.com/api/ +# 简介 + +## 预防针 + +* 本项目非官方团队出品,仅出于学习、研究目的丰富下官方项目的语言支持 +* 本项目采取后跟进官方团队功能的形式,即官方团队出什么功能,这边就跟进开发什么功能,开发者不必担心前端适配问题。 +* 在上一点的基础上,我们会尝试加入一些自己的想法并实现。 +* 局限于本人水平,有些地方还需重构,已经纳入了计划中,当然也会有我没考虑到的,希望有更多人参与进来一起完善。 + +## 专栏教程 (todo) + +* lin cms 全家桶(lin-cms-vue & lin-cms-go)为一个前端应用实现内容管理系统。一套教程入门上手 vue、fiber 两大框架。 + +* 读者反馈:[《lin cms go &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 + +``` + +## 数据库配置 + +lin 需要你自己在 mysql 中新建一个数据库,名字由你自己决定。例如,新建一个名为` lin-cms `的数据库。接着,我们需要在工程中进行一项简单的配置。使用编辑器打开 lin 工程根目录下`/configs/config.yaml`,找到如下配置项: + +```yaml +data: + datasource: + source: 用户名:密码@tcp(服务器地址)/数据库名?charset=utf8mb4&parseTime=True +``` + +**请务必根据自己的实际情况修改此配置项** + +## 导入数据 + +接下来使用你本机上任意一款数据库可视化工具,为已经创建好的`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/api/admin.go b/api/admin.go index e1cdf36..205d5f5 100644 --- a/api/admin.go +++ b/api/admin.go @@ -1,27 +1,25 @@ package api import ( - "github.com/gofiber/fiber/v2" "lin-cms-go/internal/biz" "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" - "lin-cms-go/pkg/utils" + + "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" + "github.com/xushuhui/goal/utils" ) 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 { @@ -30,26 +28,23 @@ 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 } return core.SuccessResp(c) - } func DeleteUser(c *fiber.Ctx) error { - id, err := utils.StringToInt(c.Params("id")) if err != nil { return err } - err = biz.DeleteUser(id) + err = biz.DeleteUser(c.Context(), id) if err != nil { 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/api/book.go b/api/book.go new file mode 100644 index 0000000..26bef78 --- /dev/null +++ b/api/book.go @@ -0,0 +1,81 @@ +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" +) + +func GetBooks(c *fiber.Ctx) error { + // TODO book 接口少了权限判断 + + size := core.GetSize(c) + page := core.GetPage(c) + data, err := biz.GetBookAll(c.Context(), page, size) + if err != nil { + return err + } + total, err := biz.GetBookTotal(c.Context()) + if err != nil { + return err + } + core.SetPage(c, data, total) + return nil +} + +func UpdateBook(c *fiber.Ctx) error { + var req request.UpdateBook + if err := core.ParseRequest(c, &req); err != nil { + return err + } + id, err := utils.StringToInt(c.Params("id")) + if err != nil { + return err + } + + err = biz.UpdateBook(c.Context(), id, 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 { + id, err := utils.StringToInt(c.Params("id")) + if err != nil { + return err + } + 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/api/group.go b/api/group.go index 4e30e1e..ed5b05a 100644 --- a/api/group.go +++ b/api/group.go @@ -2,62 +2,68 @@ 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 { - 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 { + err = biz.DeleteGroup(c.Context(), id) + if err != nil { return err } return core.SuccessResp(c) diff --git a/api/log.go b/api/log.go index 59322e3..34a3e95 100644 --- a/api/log.go +++ b/api/log.go @@ -2,52 +2,50 @@ package api import ( "github.com/gofiber/fiber/v2" - "lin-cms-go/internal/request" + "github.com/xushuhui/goal/core" "lin-cms-go/internal/biz" - "lin-cms-go/pkg/core" + "lin-cms-go/internal/request" ) 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 { - + page := core.GetPage(c) + size := core.GetSize(c) + if err := core.ParseQuery(c, &req); err != nil { return err } - data, err := biz.GetLogs(req) + data, total, err := biz.GetLogs(c.Context(), req, page, size) 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 { + if err := core.ParseQuery(c, &req); err != nil { return err } + page := core.GetPage(c) + size := core.GetSize(c) - data, err := biz.SearchLogs(req) + data, total, err := biz.SearchLogs(c.Context(), req, page, size) if err != nil { return err } - - return core.SetData(c, data) + return core.SetPage(c, data, total) } -func GetLogUsers(c *fiber.Ctx) error { - var req request.GetLogUsers - if err := core.ParseRequest(c, &req); err != nil { - return err - } - data, err := biz.GetLogUsers(req) +func GetLogUsers(c *fiber.Ctx) error { + page := core.GetPage(c) + size := core.GetSize(c) + data, total, err := biz.GetLogUsers(c.Context(), page, size) if err != nil { return err } - - return core.SetData(c, data) + return core.SetPage(c, data, total) } diff --git a/api/permission.go b/api/permission.go index 6767028..7c3897c 100644 --- a/api/permission.go +++ b/api/permission.go @@ -2,13 +2,15 @@ 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 { - data, err := biz.GetAllPermissions() + c.Locals("logMessage", "this is a message") + + data, err := biz.GetAllPermissions(c.Context()) if err != nil { return err @@ -19,6 +21,7 @@ func GetAllPermissions(c *fiber.Ctx) error { //TODO: 没找到必须实现该接口的业务场景,而且功能和分配多个权限重复,开发待定 func DispatchPermission(c *fiber.Ctx) error { + return nil } @@ -27,7 +30,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 } @@ -41,7 +44,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/api/user.go b/api/user.go index a3f8137..9a31748 100644 --- a/api/user.go +++ b/api/user.go @@ -1,9 +1,9 @@ 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" ) @@ -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.Username) if err != nil { return err @@ -80,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/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 diff --git a/deploy/Dockerfile b/deploy/Dockerfile new file mode 100644 index 0000000..9a529ae --- /dev/null +++ b/deploy/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 diff --git a/docs/rest.http b/docs/rest.http index 862d2ad..1f81743 100644 --- a/docs/rest.http +++ b/docs/rest.http @@ -19,7 +19,39 @@ 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 +Authorization: Bearer {{token}} + +{ + "group_id": 1, + "permission_ids": [1,2,3] +} ### 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}} +### +GET http://localhost:3000/v1/book +Content-Type: application/json +Authorization: Bearer {{token}} diff --git a/docs/schema.sql b/docs/schema.sql index 8ea799a..0ab4953 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); @@ -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/go.mod b/go.mod index 6895939..ec1b793 100644 --- a/go.mod +++ b/go.mod @@ -4,16 +4,18 @@ 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.1 - github.com/gofiber/jwt/v3 v3.1.2 + 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/google/wire v0.5.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 - golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a + github.com/xushuhui/goal v0.0.0-20211117054211-7316adac0e40 + golang.org/x/crypto v0.1.0 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index 487df58..a3b63de 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,23 +58,23 @@ 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/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/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= @@ -92,7 +94,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= @@ -102,23 +103,21 @@ 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= 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= 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= @@ -142,34 +141,38 @@ 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 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= 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= @@ -184,17 +187,21 @@ 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= -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/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= @@ -210,6 +217,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= @@ -221,11 +232,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= @@ -233,20 +242,25 @@ 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= 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= +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= @@ -261,8 +275,11 @@ 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/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= @@ -281,8 +298,8 @@ golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU 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/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= @@ -300,8 +317,9 @@ 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/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= @@ -311,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= @@ -330,15 +349,24 @@ 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-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 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +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= @@ -350,7 +378,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= @@ -362,12 +389,11 @@ 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/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= -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= @@ -403,23 +429,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/admin.go b/internal/biz/admin.go index a08576c..33bb678 100644 --- a/internal/biz/admin.go +++ b/internal/biz/admin.go @@ -1,38 +1,55 @@ package biz import ( - "lin-cms-go/internal/request" - "lin-cms-go/pkg/core" + "context" + "lin-cms-go/internal/data" + "lin-cms-go/internal/data/model" + "lin-cms-go/pkg/errcode" + + "github.com/xushuhui/goal/core" + "golang.org/x/crypto/bcrypt" ) -func GetUsers(req request.GetUsers) (data map[string]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(req request.ChangeUserPassword) (err error) { - - //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 - //} + +func ChangeUserPassword(ctx context.Context, userId int, password string) (err error) { + user, err := data.GetLinUserIdentityByUserId(ctx, userId) + 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) { - if id <= 0 { - err = core.NewInvalidParamsError("id cannot be negative") + +func DeleteUser(ctx context.Context, userId int) (err error) { + _, err = data.GetLinUserById(ctx, userId) + if model.IsNotFound(err) { + err = core.NotFoundError(errcode.UserNotFound) return } + 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.NotFoundError(errcode.UserNotFound) + return + } + err = data.AddLinUserGroupIDs(ctx, userId, groupId) return } diff --git a/internal/biz/biz.go b/internal/biz/biz.go index e580a53..bb83504 100644 --- a/internal/biz/biz.go +++ b/internal/biz/biz.go @@ -1,16 +1,80 @@ package biz import ( + "context" + "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" - "lin-cms-go/internal/data/ent" - "lin-cms-go/pkg/utils" + "github.com/xushuhui/goal/utils" ) -func LocalUser(c *fiber.Ctx) (user ent.LinUser) { - jwtToken := c.Locals("user").(*jwt.Token) +func LocalUser(c *fiber.Ctx) (user model.LinUser) { + 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) return } + +func IsAdmin(c *fiber.Ctx) (is bool, err error) { + user := LocalUser(c) + if user.ID == 0 { + err = core.UnAuthenticatedError(errcode.ErrorAuthToken) + return + } + 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 +} + +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 model.IsNotFound(err) { + err = core.NotFoundError(errcode.UserNotFound) + return + } + + local := c.Locals("permission") + if local == nil { + return false, core.UnAuthenticatedError(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/biz/book.go b/internal/biz/book.go new file mode 100644 index 0000000..5f0f0ed --- /dev/null +++ b/internal/biz/book.go @@ -0,0 +1,85 @@ +package biz + +import ( + "context" + "github.com/pkg/errors" + + "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) { + books, err := data.NewPaging(page, size).ListBook(ctx) + if err != nil { + return + } + res = books + return +} + +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 model.IsNotFound(err) { + err = core.NotFoundError(errcode.BookNotFound) + return + } + if err != nil { + return + } + err = data.UpdateBook(ctx, id, req.Title, req.Author, req.Summary, req.Image) + return +} + +func CreateBook(ctx context.Context, req request.CreateBook) (err error) { + book, err := data.GetBookByTitle(ctx, req.Title) + if model.MaskNotFound(err) != nil { + 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 +} + +func DeleteBook(ctx context.Context, id int) (err error) { + _, err = data.GetBookById(ctx, id) + if model.IsNotFound(err) { + err = core.NotFoundError(errcode.BookNotFound) + return + } + if err != nil { + + return errors.Wrap(err, "GetBookByIdError") + } + err = data.SoftDeleteBook(ctx, id) + return +} + +func GetBook(ctx context.Context, id int) (res interface{}, err error) { + book, err := data.GetBookById(ctx, id) + if model.IsNotFound(err) { + 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 1c857bf..ee1c734 100644 --- a/internal/biz/group.go +++ b/internal/biz/group.go @@ -1,30 +1,125 @@ package biz import ( + "context" + "github.com/pkg/errors" + "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" ) -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) + if model.IsNotFound(err) { + err = core.NotFoundError(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.ParamsError(errcode.GroupFound) + return + } + for _, v := range permissionIds { + _, err = data.GetLinPermissionById(ctx, v) + if model.IsNotFound(err) { + 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 } -func UpdateGroup(req request.UpdateGroup) (err error) { + +func UpdateGroup(ctx context.Context, id int, req request.UpdateGroup) (err error) { + _, err = data.GetLinGroupById(ctx, id) + if model.IsNotFound(err) { + 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 } -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) + if model.IsNotFound(err) { + err = core.NotFoundError(errcode.GroupNotFound) + return + } + if err != nil { + err = errors.Wrap(err, "GetLinGroupById ") + return + } + if linGroup.Level == enum.ROOT { + err = core.ParamsError(errcode.RootGroupNotAllowDelete) + return + } + + if linGroup.Level == enum.GUEST { + err = core.ParamsError(errcode.GuestGroupNotAllowDelete) + return + } + + 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 8731b47..3dcccad 100644 --- a/internal/biz/log.go +++ b/internal/biz/log.go @@ -1,17 +1,78 @@ package biz -import "lin-cms-go/internal/request" +import ( + "context" + "github.com/pkg/errors" + "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" +) -func Upload() { +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(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) + q := linlog.And(linlog.CreateTimeGT(start), linlog.CreateTimeLT(end)) + query = append(query, q) + } + logs, err = paging.Search(ctx, query) + if err != nil { + err = errors.Wrap(err, "Search ") + return + } + total = data.GetSearchTotal(ctx, query) + + 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) { + +func SearchLogs(ctx context.Context, req request.SearchLogs, page int, size int) (res interface{}, total int, err error) { + var logs []*model.LinLog + + 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) + q := linlog.And(linlog.CreateTimeGT(start), linlog.CreateTimeLT(end)) + query = append(query, q) + } + if req.Keyword != "" { + 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 } -func GetLogUsers(req request.GetLogUsers) (res map[string]interface{}, err error) { +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 { + err = errors.Wrap(err, "GetLogUsers ") + return + } + total, err = data.GetLogUsersTotal(ctx) + if err != nil { + err = errors.Wrap(err, "GetLogUsersTotal ") + return + } return } diff --git a/internal/biz/permission.go b/internal/biz/permission.go index 75c4c83..20aed27 100644 --- a/internal/biz/permission.go +++ b/internal/biz/permission.go @@ -1,8 +1,22 @@ package biz -import "lin-cms-go/internal/request" +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 } @@ -10,9 +24,26 @@ 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(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 } -func RemovePermissions(req request.RemovePermissions) (err error) { + +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/biz/user.go b/internal/biz/user.go index e659294..aa8337b 100644 --- a/internal/biz/user.go +++ b/internal/biz/user.go @@ -2,38 +2,45 @@ package biz import ( "context" - "errors" - "github.com/golang-jwt/jwt/v4" + "github.com/pkg/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" "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 ent.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + if model.IsNotFound(err) { + err = core.NotFoundError(errcode.UserNotFound) return } if err != nil { + err = errors.Wrap(err, "GetLinUserIdentityByIdentifier ") return } err = bcrypt.CompareHashAndPassword([]byte(userIdentityModel.Credential), []byte(password)) + if err == bcrypt.ErrMismatchedHashAndPassword { + err = core.ParamsError(errcode.ErrorPassWord) + return + } if err != nil { - err = core.NewErrorCode(errcode.ErrorPassWord) + err = errors.Wrap(err, "CompareHashAndPassword ") return } user, err := data.GetLinUserById(ctx, userIdentityModel.UserID) if err != nil { + err = errors.Wrap(err, "GetLinUserById ") return } // jwt @@ -42,76 +49,98 @@ 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{}) res["access_token"] = token return } + func Register(ctx context.Context, req request.Register) (err error) { userIdentityModel, err := data.GetLinUserIdentityByIdentifier(ctx, req.Username) - if ent.MaskNotFound(err) != nil { - return err + if model.MaskNotFound(err) != nil { + err = errors.Wrap(err, "GetLinUserIdentityByIdentifier ") + return } if userIdentityModel != nil && userIdentityModel.ID > 0 { - err = errors.New("user is found") + err = core.ParamsError(errcode.UserFound) return } 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 - } + func UpdateMe(ctx context.Context, req request.UpdateMe, uid int) (err error) { _, err = data.GetLinUserById(ctx, uid) - if ent.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + if model.IsNotFound(err) { + err = core.NotFoundError(errcode.UserNotFound) 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, 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 { + err = errors.Wrap(err, "GetLinUserIdentityByIdentifier ") return err } err = bcrypt.CompareHashAndPassword([]byte(userIdentityModel.Credential), []byte(req.OldPassword)) + if err == bcrypt.ErrMismatchedHashAndPassword { + err = core.ParamsError(errcode.ErrorPassWord) + return + } if err != nil { - err = core.NewErrorCode(errcode.ErrorPassWord) + 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 } return } + func GetMyPermissions(ctx context.Context, uid int) (res map[string]interface{}, err error) { user, err := data.GetLinUserById(ctx, uid) - if ent.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + if model.IsNotFound(err) { + err = core.NotFoundError(errcode.UserNotFound) 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 @@ -121,17 +150,24 @@ 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 } -func GetMyInfomation(ctx context.Context, uid int) (res map[string]interface{}, err error) { - _, err = data.GetLinUserById(ctx, uid) - if ent.IsNotFound(err) { - err = core.NewErrorCode(errcode.UserNotFound) + +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.NotFoundError(errcode.UserNotFound) return } if err != nil { + err = errors.Wrap(err, "GetLinUserById ") return } + res = LinUser{*usermodel} return } diff --git a/internal/data/book.go b/internal/data/book.go new file mode 100644 index 0000000..91736e2 --- /dev/null +++ b/internal/data/book.go @@ -0,0 +1,43 @@ +package data + +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) { + model, err = GetDB().Book.Query().Where(book.ID(id)).First(ctx) + return +} + +func GetBookByTitle(ctx context.Context, title string) (model *model.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 +} + +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 SoftDeleteBook(ctx context.Context, id int) (err error) { + _, err = GetDB().Book.Update().Where(book.ID(id)).SetDeleteTime(time.Now()).Save(ctx) + return +} + +func GetBookCount(ctx context.Context) (count int, err error) { + count, err = GetDB().Book.Query().Count(ctx) + return +} + +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 8d3fdfd..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 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/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/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_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_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/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/ent/schema/lin_user.go b/internal/data/ent/schema/lin_user.go index 41faa30..946d5aa 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 { @@ -18,11 +17,13 @@ func (LinUser) Annotations() []schema.Annotation { entsql.Annotation{Table: "lin_user"}, } } + func (LinUser) Mixin() []ent.Mixin { return []ent.Mixin{ - mixin.Time{}, + TimeMixin{}, } } + func (LinUser) Fields() []ent.Field { return []ent.Field{ field.String("username").Comment("用户名,唯一").Unique(), @@ -31,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/data/ent/schema/lin_user_group.go b/internal/data/ent/schema/lin_user_group.go index 714d18e..c75edd8 100644 --- a/internal/data/ent/schema/lin_user_group.go +++ b/internal/data/ent/schema/lin_user_group.go @@ -1,40 +1,27 @@ package schema import ( + "time" + "entgo.io/ent" "entgo.io/ent/schema/field" + "entgo.io/ent/schema/mixin" - "time" ) type TimeMixin struct { - // We embed the `mixin.Schema` to avoid - // implementing the rest of the methods. mixin.Schema } 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"). + Optional(), } } - -//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/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/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 }} + diff --git a/internal/data/group.go b/internal/data/group.go new file mode 100644 index 0000000..4d5697a --- /dev/null +++ b/internal/data/group.go @@ -0,0 +1,49 @@ +package data + +import ( + "context" + "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) { + 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)).First(ctx) + return +} + +func GetRootLinGroup(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, level int8) (res *model.LinGroup, err error) { + res, err = GetDB().LinGroup.Create().SetName(name).SetInfo(info).SetLevel(level).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 +} + +// 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 err + +} diff --git a/internal/data/groupPermission.go b/internal/data/groupPermission.go new file mode 100644 index 0000000..db724af --- /dev/null +++ b/internal/data/groupPermission.go @@ -0,0 +1,38 @@ +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.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 + //} + + _, 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 +} diff --git a/internal/data/init.go b/internal/data/init.go index 920de8a..05d9252 100644 --- a/internal/data/init.go +++ b/internal/data/init.go @@ -1,35 +1,54 @@ package data import ( + "context" "lin-cms-go/internal/conf" - "lin-cms-go/internal/data/ent" + "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 + 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 + 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) { + ds.Db["default"] = NewDBClient(conf) +} +func NewDBClient(conf *conf.Data) (db *model.Client) { var err error once.Do(func() { - opt := ent.Debug() - db, err = ent.Open(conf.Database.Driver, conf.Database.Source, opt) + db, err = model.Open(conf.Database.Driver, conf.Database.Source, model.Debug()) if err != nil { panic(err) } @@ -38,13 +57,36 @@ 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") } + +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/log.go b/internal/data/log.go index 0ad59c2..6c1705e 100644 --- a/internal/data/log.go +++ b/internal/data/log.go @@ -1 +1,46 @@ 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" +) + +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 GetSearchTotal(ctx context.Context, query []predicate.LinLog) (total int) { + total, _ = GetDB().LinLog.Query().Where(query...).Count(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 +} + +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/book.go b/internal/data/model/book.go new file mode 100644 index 0000000..724ccd0 --- /dev/null +++ b/internal/data/model/book.go @@ -0,0 +1,162 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/book" + "strings" + "time" + + "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"` + // 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. + 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) + 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]) + } + } + 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.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]) + } 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(", 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=") + 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..312a479 --- /dev/null +++ b/internal/data/model/book/book.go @@ -0,0 +1,61 @@ +// Code generated by entc, DO NOT EDIT. + +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. + 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, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + 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 +} + +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 new file mode 100644 index 0000000..5b395c3 --- /dev/null +++ b/internal/data/model/book/where.go @@ -0,0 +1,860 @@ +// Code generated by entc, DO NOT EDIT. + +package book + +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.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)) + }) +} + +// 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) { + 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)) + }) +} + +// 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) { + 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..cfad8b4 --- /dev/null +++ b/internal/data/model/book_create.go @@ -0,0 +1,358 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/book" + "time" + + "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 +} + +// 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) + 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 + ) + bc.defaults() + 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) + } +} + +// 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"`)} + } + 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.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, + 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] + builder.defaults() + 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..bf4f39a --- /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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Book.Query(). +// GroupBy(book.FieldCreateTime). +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.Book.Query(). +// Select(book.FieldCreateTime). +// 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..341baa1 --- /dev/null +++ b/internal/data/model/book_update.go @@ -0,0 +1,453 @@ +// 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" + "time" + + "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 +} + +// 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) + 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 + ) + bu.defaults() + 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) + } +} + +// 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{ + 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.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, + 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 +} + +// 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) + 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 + ) + buo.defaults() + 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) + } +} + +// 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{ + 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.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, + 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..22e166a --- /dev/null +++ b/internal/data/model/lingroup.go @@ -0,0 +1,197 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/lingroup" + "strings" + "time" + + "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"` + // 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"` + // 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) + 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]) + } + } + 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.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]) + } 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(", 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=") + 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..70b549b --- /dev/null +++ b/internal/data/model/lingroup/lingroup.go @@ -0,0 +1,81 @@ +// Code generated by entc, DO NOT EDIT. + +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. + 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, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldName, + FieldInfo, + FieldLevel, +} + +var ( + // LinUserPrimaryKey and LinUserColumn2 are the table columns denoting the + // primary key for the lin_user relation (M2M). + 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"} +) + +// 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 +) diff --git a/internal/data/model/lingroup/where.go b/internal/data/model/lingroup/where.go new file mode 100644 index 0000000..f03739a --- /dev/null +++ b/internal/data/model/lingroup/where.go @@ -0,0 +1,764 @@ +// Code generated by entc, DO NOT EDIT. + +package lingroup + +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.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)) + }) +} + +// 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) { + 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)) + }) +} + +// 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)) + }) +} + +// 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) { + 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..9399b1c --- /dev/null +++ b/internal/data/model/lingroup_create.go @@ -0,0 +1,411 @@ +// 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" + "time" + + "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 +} + +// 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) + 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 + ) + lgc.defaults() + 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) + } +} + +// 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) + } +} + +// 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.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.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, + 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] + builder.defaults() + 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..6460311 --- /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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinGroup.Query(). +// GroupBy(lingroup.FieldCreateTime). +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.LinGroup.Query(). +// Select(lingroup.FieldCreateTime). +// 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..9cbc7c5 --- /dev/null +++ b/internal/data/model/lingroup_update.go @@ -0,0 +1,817 @@ +// 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" + "time" + + "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 +} + +// 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 +} + +// 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) + 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 + ) + lgu.defaults() + 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) + } +} + +// 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{ + 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.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 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, + 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 +} + +// 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 +} + +// 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) + 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 + ) + lguo.defaults() + 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) + } +} + +// 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{ + 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.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 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, + 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..cb53813 --- /dev/null +++ b/internal/data/model/linlog/linlog.go @@ -0,0 +1,70 @@ +// 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 +) diff --git a/internal/data/model/linlog/where.go b/internal/data/model/linlog/where.go new file mode 100644 index 0000000..e263558 --- /dev/null +++ b/internal/data/model/linlog/where.go @@ -0,0 +1,1144 @@ +// 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)) + }) +} + +// 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) { + 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..acd101a --- /dev/null +++ b/internal/data/model/linlog_create.go @@ -0,0 +1,409 @@ +// 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) + } +} + +// 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.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..ce7e23c --- /dev/null +++ b/internal/data/model/linlog_update.go @@ -0,0 +1,587 @@ +// 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 +} + +// 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) + 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 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, + 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 +} + +// 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) + 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 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, + 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..3024df4 --- /dev/null +++ b/internal/data/model/linuser/linuser.go @@ -0,0 +1,85 @@ +// 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{"group_id", "user_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 + // 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..6b1ba39 --- /dev/null +++ b/internal/data/model/linuser/where.go @@ -0,0 +1,917 @@ +// 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)) + }) +} + +// 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) { + 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..58f2c34 --- /dev/null +++ b/internal/data/model/linuser_create.go @@ -0,0 +1,440 @@ +// 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.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.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..59b46bd --- /dev/null +++ b/internal/data/model/linuser_update.go @@ -0,0 +1,831 @@ +// 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 +} + +// 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) + 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 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, + 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 +} + +// 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) + 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 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, + 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..05fefe3 --- /dev/null +++ b/internal/data/model/linuseridentiy.go @@ -0,0 +1,173 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "strings" + "time" + + "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"` + // 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"` + // 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.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: + 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.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]) + } 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(", 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=") + 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..68522b1 --- /dev/null +++ b/internal/data/model/linuseridentiy/linuseridentiy.go @@ -0,0 +1,72 @@ +// Code generated by entc, DO NOT EDIT. + +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. + 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, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + 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 +} + +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/linuseridentiy/where.go b/internal/data/model/linuseridentiy/where.go new file mode 100644 index 0000000..1878b0f --- /dev/null +++ b/internal/data/model/linuseridentiy/where.go @@ -0,0 +1,825 @@ +// Code generated by entc, DO NOT EDIT. + +package linuseridentiy + +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.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)) + }) +} + +// 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) { + 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)) + }) +} + +// 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)) + }) +} + +// 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) { + 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..eaeaac5 --- /dev/null +++ b/internal/data/model/linuseridentiy_create.go @@ -0,0 +1,358 @@ +// Code generated by entc, DO NOT EDIT. + +package model + +import ( + "context" + "errors" + "fmt" + "lin-cms-go/internal/data/model/linuseridentiy" + "time" + + "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 +} + +// 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) + 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 + ) + luic.defaults() + 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) + } +} + +// 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) + } +} + +// 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.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.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, + 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] + builder.defaults() + 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..21e989e --- /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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LinUserIdentiy.Query(). +// GroupBy(linuseridentiy.FieldCreateTime). +// 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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.LinUserIdentiy.Query(). +// Select(linuseridentiy.FieldCreateTime). +// 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..cbe9d84 --- /dev/null +++ b/internal/data/model/linuseridentiy_update.go @@ -0,0 +1,481 @@ +// 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" + "time" + + "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 +} + +// 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 +} + +// 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() + 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 + ) + luiu.defaults() + 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) + } +} + +// 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{ + 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.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 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, + 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 +} + +// 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 +} + +// 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() + 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 + ) + luiuo.defaults() + 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) + } +} + +// 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{ + 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.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 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, + 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..e302af7 --- /dev/null +++ b/internal/data/model/migrate/schema.go @@ -0,0 +1,228 @@ +// 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: "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}, + {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: "create_time", Type: field.TypeTime}, + {Name: "update_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}, + } + // 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, Nullable: true}, + {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, Nullable: true}, + {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: "create_time", Type: field.TypeTime}, + {Name: "update_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}, + {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[8]}, + RefColumns: []*schema.Column{LinUserColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // LinUserGroupColumns holds the columns for the "lin_user_group" table. + LinUserGroupColumns = []*schema.Column{ + {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{ + Name: "lin_user_group", + Columns: LinUserGroupColumns, + PrimaryKey: []*schema.Column{LinUserGroupColumns[0], LinUserGroupColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "lin_user_group_group_id", + Columns: []*schema.Column{LinUserGroupColumns[0]}, + RefColumns: []*schema.Column{LinGroupColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "lin_user_group_user_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..9a8cbcb --- /dev/null +++ b/internal/data/model/mutation.go @@ -0,0 +1,4989 @@ +// 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 + create_time *time.Time + update_time *time.Time + delete_time *time.Time + 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 +} + +// 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 +} + +// 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, 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) + } + 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.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: + 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.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: + 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.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 { + 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 { + 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 +// 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 { + switch name { + case book.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + 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.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 + 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 + create_time *time.Time + update_time *time.Time + delete_time *time.Time + 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 +} + +// 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 +} + +// 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. +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, 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) + } + 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.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: + 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.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: + 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.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 { + 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 { + 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 +// 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 { + switch name { + case lingroup.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + 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.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 + 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 +} + +// 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. +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 { + 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 +// 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 { + switch name { + case linlog.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + 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 +} + +// 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. +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 { + 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 +// 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 { + switch name { + case linuser.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + 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 + create_time *time.Time + update_time *time.Time + delete_time *time.Time + 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 +} + +// 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 +} + +// 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. +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, 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) + } + 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.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: + 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.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: + 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.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 { + 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 { + 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 +// 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 { + switch name { + case linuseridentiy.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + 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.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 + 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..15df6fb --- /dev/null +++ b/internal/data/model/runtime.go @@ -0,0 +1,98 @@ +// Code generated by entc, DO NOT EDIT. + +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" + "lin-cms-go/internal/data/model/linuseridentiy" + "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() { + 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 + 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) + 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) + 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) + // 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) + 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) +} 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) diff --git a/internal/data/permission.go b/internal/data/permission.go new file mode 100644 index 0000000..66667d5 --- /dev/null +++ b/internal/data/permission.go @@ -0,0 +1,22 @@ +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 +} + +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/data/user.go b/internal/data/user.go index 40935ee..348cf6d 100644 --- a/internal/data/user.go +++ b/internal/data/user.go @@ -2,19 +2,24 @@ 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/lingroup" + "lin-cms-go/internal/data/model/linuser" + "lin-cms-go/internal/data/model/linuseridentiy" + "time" ) -func GetLinUserIdentityByIdentifier(ctx context.Context, identifier string) (po *ent.LinUserIdentiy, err error) { - - po, err = GetDB().LinUserIdentiy.Query().Where(linuseridentiy.Identifier(identifier)).First(ctx) +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). @@ -33,21 +38,62 @@ 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 } +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 +} + 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) 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 8c6bcbc..c9402de 100644 --- a/internal/request/admin.go +++ b/internal/request/admin.go @@ -1,28 +1,32 @@ package request type GetUsers struct { - GroupId int `json:"group_id" binding:"required"` - Pages + GroupId int `json:"group_id" ` } + 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"` - 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/internal/request/book.go b/internal/request/book.go new file mode 100644 index 0000000..4b4a3c8 --- /dev/null +++ b/internal/request/book.go @@ -0,0 +1,19 @@ +package request + +type UpdateBook 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 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 GetBooks struct { + Size int `json:"size" validate:"required" comment:"数量"` + Page int `json:"page" validate:"required" comment:"页码"` +} 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 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/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..51732dc --- /dev/null +++ b/internal/server/middleware.go @@ -0,0 +1,116 @@ +package server + +import ( + "lin-cms-go/internal/biz" + "lin-cms-go/internal/data" + "lin-cms-go/pkg/errcode" + + "github.com/gofiber/fiber/v2" + "github.com/xushuhui/goal/core" +) + +func UserLog(c *fiber.Ctx) error { + 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(), "") + + return err +} + +func SetPermission(name, module string) fiber.Handler { + return func(c *fiber.Ctx) error { + 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() + } +} + +func AdminRequired(c *fiber.Ctx) error { + isAdmin, err := biz.IsAdmin(c) + if err != nil { + return err + } + if !isAdmin { + return core.UnAuthenticatedError(errcode.UserNoPermission) + } + return c.Next() +} + +func LoginRequired(c *fiber.Ctx) error { + user := biz.LocalUser(c) + if user.ID == 0 { + return core.UnAuthenticatedError(errcode.AuthCheckTokenFail) + } + + return c.Next() +} + +func GroupRequired(c *fiber.Ctx) error { + isAdmin, err := biz.IsAdmin(c) + if err != nil { + return err + } + if isAdmin { + return c.Next() + } + + has, err := biz.UserHasPermission(c) + if err != nil { + return err + } + if !has { + return core.UnAuthenticatedError(errcode.UserNoPermission) + } + return c.Next() +} + +// +//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 7f90308..b7281d5 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -1,26 +1,38 @@ package server import ( - "github.com/gofiber/fiber/v2" - jwtware "github.com/gofiber/jwt/v3" "lin-cms-go/api" + "lin-cms-go/pkg/lib" + + "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") + cms.Post("/file", api.Upload) cms.Post("/user/login", api.Login) - cms.Use(jwtware.New(jwtware.Config{ - SigningKey: []byte("secret"), - })) + + cms.Use(lib.ParseJwt(), LoginRequired) + v1.Use(lib.ParseJwt(), LoginRequired) + bookRouter := v1.Group("/book").Use(SetPermission("book", "图书")).Use(GroupRequired) { - userRouter := cms.Group("/user") - adminRouter := cms.Group("/admin") - logRouter := cms.Group("/log") - userRouter.Post("/register", api.Register) + 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) userRouter.Put("/change_password", api.ChangeMyPassword) userRouter.Get("/permissions", api.GetMyPermissions) @@ -42,9 +54,9 @@ 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 deleted file mode 100644 index 29677a4..0000000 --- a/internal/server/server.go +++ /dev/null @@ -1,8 +0,0 @@ -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..23fcbc6 100644 --- a/main.go +++ b/main.go @@ -1,38 +1,47 @@ package main import ( + "github.com/gofiber/fiber/v2" + "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" - "log" - - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/logger" - "github.com/gofiber/fiber/v2/middleware/recover" - "gopkg.in/yaml.v2" ) +func errorHandler(c *fiber.Ctx, err error) error { + // response err handle + if e, ok := err.(core.HttpError); ok { + if e.Err == nil { + return e.HandleHttpError(c) + } + } + + return core.HandleServerError(c, err) +} +func initLog(c *conf.Config) { + log.SetFile(log.FileConfig{ + + 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{ - // 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(logger.New()) + app.Use(cors.New(), server.UserLog) + initLog(c) data.NewDataSource(&c.Data) //TODO clean source @@ -48,11 +57,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) - log.Fatal(app.Listen(c.Server.Http.Addr)) + app.Listen(c.Server.Http.Addr) + } 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 940c23c..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("size")) - if pageSize <= 0 { - return 20 - } - - 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 34eb696..0000000 --- a/pkg/core/response.go +++ /dev/null @@ -1,122 +0,0 @@ -package core - -import ( - "errors" - "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:"-"` -} - -func (err IError) Error() (re string) { - return fmt.Sprintf("code=%v, Message=%v", err.Code, err.Message) -} - -func NewErrorCode(code int) (err error) { - err = IError{ - Code: code, - Message: errcode.GetMsg(code), - } - return -} -func NewErrorMessage(code int, message string) (err error) { - err = IError{ - Code: code, - Message: message, - } - 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 errors.New(s) - } - return nil -} -func ParseRequest(c *fiber.Ctx, request interface{}) (err error) { - err = c.BodyParser(request) - - if err != nil { - return err - } - 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{ - Code: code, - Message: msg, - }) - -} -func InvalidParamsError(c *fiber.Ctx, msg string) error { - - return c.JSON(IError{ - Code: errcode.InvalidParams, - Message: msg, - }) - -} - -func SuccessResp(c *fiber.Ctx) error { - return c.JSON(IError{ - Code: 0, - Message: errcode.GetMsg(0), - }) -} -func SetData(c *fiber.Ctx, data map[string]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 ServerError(c *fiber.Ctx, err error) error { - - return c.JSON(IError{ - Code: errcode.ServerError, - Message: errcode.GetMsg(errcode.ServerError), - Err: err, - }) -} -func (err *IError) HttpError(c *fiber.Ctx) error { - return c.JSON(IError{ - Code: err.Code, - Message: errcode.GetMsg(err.Code), - }) -} 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/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 diff --git a/pkg/errcode/message.go b/pkg/errcode/message.go index bdfc77e..5edb55d 100644 --- a/pkg/errcode/message.go +++ b/pkg/errcode/message.go @@ -1,37 +1,42 @@ package errcode +import "github.com/xushuhui/goal/core" + const ( - SUCCESS = iota - InvalidParams - DBError - ServerError - AuthCheckTokenFail - AuthCheckTokenTimeout - ErrorAuthToken - TimeoutAuthToken - ErrorPassWord - UserFound - UserNotFound + 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 + UserPermissionRequired = 40000 + UserNoPermission = 40001 ) -var MsgFlags = map[int]string{ - SUCCESS: "ok", - InvalidParams: "请求参数错误", - DBError: "数据库错误", - ServerError: "系统异常,请联系管理员!", - AuthCheckTokenFail: "Token鉴权失败", - AuthCheckTokenTimeout: "Token已超时", - ErrorAuthToken: "Token错误", - ErrorPassWord: "密码错误", - UserFound: "用户已存在", - UserNotFound: "用户不存在", -} - -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: "权限不存在", + UserPermissionRequired: "用户权限必须存在", + UserNoPermission: "用户没有权限访问", } - - return MsgFlags[InvalidParams] } 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), + }) +} 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/log/logger.go b/pkg/log/logger.go new file mode 100644 index 0000000..94bc7b0 --- /dev/null +++ b/pkg/log/logger.go @@ -0,0 +1,18 @@ +package log + +import log "github.com/grestful/logs" + +var SqlLogger log.Logger + +func SetSqlLogger(path string) { + log.SetFile(log.FileConfig{ + + Category: "file", + Level: "DEBUG", + Filename: path + "/sql.log", + Rotate: true, + Daily: true, + }) + writer := log.GetLogger("file") + log.SetDefaultLog(writer) +} 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...)) -} 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 f1c9db9..0000000 --- a/pkg/utils/time.go +++ /dev/null @@ -1,27 +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() -} 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/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) + // } + // }) + // } +} diff --git a/test/user_test.go b/test/user_test.go index c6fd2a1..9844ab5 100644 --- a/test/user_test.go +++ b/test/user_test.go @@ -1,38 +1,103 @@ package test import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" "testing" ) -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, - }, +type Categories struct { + ID int + Pid int + Name string + Children []Categories +} + +func getNode(list []Categories, pid int) (l []Categories) { + for _, val := range list { + if val.Pid == pid { + if pid == 0 { + // 顶层 + l = append(l, val) + } else { + 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 { + 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 do(url string) []AlbumResponse { + rsps, err := http.Get(url) + if err != nil { + fmt.Println("Request failed:", err) + return nil } - call(t, testcase) + 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("TestAddUsers", testAddUsers) - //t.Run("TestEditUsers", testEditUsers) - //t.Run("TestDeleteUsers", testDeleteUsers) }