From 5b8eca5d87ef752e353c0da1924daabb2d10fdb2 Mon Sep 17 00:00:00 2001 From: yanghao05 Date: Thu, 20 Apr 2023 12:11:34 +0800 Subject: [PATCH] restructure --- bin/.gitignore | 2 - cmd/migrate.go | 27 +- cmd/model.go | 27 +- cmd/root.go | 39 -- cmd/seed.go | 20 +- common/structure/sex.go | 1 - container/container.go | 7 +- contracts/routes.go | 5 - ...0130_193508_create_sys_operation_record.go | 56 --- .../migrations/20230131_160904_create_user.go | 56 --- .../20230131_162400_create_sys_api.go | 50 -- .../20230131_165134_create_sys_dictionary.go | 50 -- ...131_165218_create_sys_dictionary_detail.go | 51 -- .../20230131_165352_create_user_role.go | 46 -- .../20230131_165509_create_sys_role.go | 50 -- .../20230131_170433_create_casbin_rule.go | 43 -- database/migrations/placeholder.go | 36 -- database/models/casbin_rule.gen.go | 24 - database/models/migrations.gen.go | 17 - database/models/sys_apis.gen.go | 30 -- database/models/sys_dictionaries.gen.go | 30 -- database/models/sys_dictionary_details.gen.go | 31 -- database/models/sys_operation_records.gen.go | 36 -- database/models/sys_roles.gen.go | 30 -- database/models/user_roles.gen.go | 18 - database/models/users.gen.go | 35 -- database/query/casbin_rule.gen.go | 420 ----------------- database/query/migrations.gen.go | 392 ---------------- database/query/query.gen.go | 163 ------- database/query/sys_apis.gen.go | 418 ----------------- database/query/sys_dictionaries.gen.go | 420 ----------------- database/query/sys_dictionary_details.gen.go | 424 ----------------- database/query/sys_operation_records.gen.go | 444 ------------------ database/query/sys_roles.gen.go | 418 ----------------- database/query/user_roles.gen.go | 394 ---------------- database/query/users.gen.go | 438 ----------------- database/seeders/migration.go | 44 -- database/seeders/placeholder.go | 40 -- database/seeders/sys_role.go | 64 --- {common => ds}/request/page.go | 0 {common => ds}/response/page.go | 0 go.mod | 2 +- main.go | 2 +- middleware/cors.go | 71 --- middleware/jwt.go | 41 -- middleware/middleware.go | 1 - middleware/operation.go | 138 ------ middleware/rbac.go | 45 -- modules/auth/container/container.go | 54 --- modules/auth/controller/permission.go | 39 -- modules/auth/controller/role.go | 46 -- modules/auth/controller/user.go | 44 -- modules/auth/dao/role.go | 85 ---- modules/auth/dao/role_test.go | 151 ------ modules/auth/dao/user.go | 28 -- modules/auth/dao/user_role.go | 44 -- modules/auth/dao/user_role_test.go | 79 ---- modules/auth/dao/user_test.go | 93 ---- modules/auth/dto/role.go | 22 - modules/auth/dto/user.go | 10 - modules/auth/routes/routes.go | 72 --- modules/auth/service/role.go | 94 ---- modules/auth/service/user.go | 59 --- modules/modules.go | 7 - modules/resources/.keep | 0 modules/resources/container/container.go | 15 - modules/resources/routes/routes.go | 18 - modules/system/container/container.go | 30 -- modules/system/controller/captcha.go | 27 -- modules/system/dao/dao.go | 25 - modules/system/dao/dao_test.go | 60 --- modules/system/dto/captcha.go | 1 - modules/system/routes/routes.go | 22 - modules/system/service/service.go | 13 - proto/.gitignore | 2 - proto/web_api.proto | 44 -- providers/captcha/captcha.go | 46 +- providers/captcha/config.go | 25 + providers/captcha/driver/digit.go | 26 - providers/config/loader.go | 56 --- providers/config/section_app.go | 18 - providers/config/section_captcha.go | 22 - providers/config/section_database.go | 109 ----- providers/config/section_log.go | 5 - providers/config/section_storage.go | 29 -- providers/database/database.go | 35 -- providers/database/mysql.go | 73 --- providers/database/mysql/config.go | 50 ++ providers/database/mysql/mysql.go | 77 +++ providers/database/postgres.go | 36 -- providers/database/postgres/config.go | 31 ++ providers/database/postgres/postgres.go | 40 ++ providers/database/redis/todo.go | 1 + providers/database/sqlite.go | 18 - providers/database/sqlite/config.go | 13 + providers/database/sqlite/sqlite.go | 21 + providers/dictionary/dict.go | 116 ----- providers/dictionary/info.go | 14 - providers/faker/faker.go | 21 +- .../section_http.go => http/config.go} | 25 +- providers/http/contracts.go | 9 + providers/http/engine.go | 61 --- providers/http/gin/engine.go | 54 +++ providers/jwt/config.go | 21 + providers/jwt/jwt.go | 30 +- providers/log/config.go | 28 ++ providers/log/gin_level_writer.go | 8 +- providers/log/logger.go | 66 +-- providers/log/zap.go | 7 +- providers/provider.go | 17 - providers/query/query.go | 19 - providers/rbac/casbin.go | 134 ------ providers/rbac/rbac.go | 7 - providers/single_flight/flight.go | 17 +- providers/uuid/uuid.go | 20 +- services/http.go | 24 + services/http/http.go | 30 -- utils/{ => db}/db.go | 2 +- {common => utils}/err/common.go | 0 utils/share.go | 8 - 120 files changed, 546 insertions(+), 7303 deletions(-) delete mode 100644 bin/.gitignore delete mode 100644 cmd/root.go delete mode 100644 common/structure/sex.go delete mode 100644 contracts/routes.go delete mode 100755 database/migrations/20230130_193508_create_sys_operation_record.go delete mode 100755 database/migrations/20230131_160904_create_user.go delete mode 100755 database/migrations/20230131_162400_create_sys_api.go delete mode 100755 database/migrations/20230131_165134_create_sys_dictionary.go delete mode 100755 database/migrations/20230131_165218_create_sys_dictionary_detail.go delete mode 100755 database/migrations/20230131_165352_create_user_role.go delete mode 100755 database/migrations/20230131_165509_create_sys_role.go delete mode 100755 database/migrations/20230131_170433_create_casbin_rule.go delete mode 100644 database/migrations/placeholder.go delete mode 100644 database/models/casbin_rule.gen.go delete mode 100644 database/models/migrations.gen.go delete mode 100644 database/models/sys_apis.gen.go delete mode 100644 database/models/sys_dictionaries.gen.go delete mode 100644 database/models/sys_dictionary_details.gen.go delete mode 100644 database/models/sys_operation_records.gen.go delete mode 100644 database/models/sys_roles.gen.go delete mode 100644 database/models/user_roles.gen.go delete mode 100644 database/models/users.gen.go delete mode 100644 database/query/casbin_rule.gen.go delete mode 100644 database/query/migrations.gen.go delete mode 100644 database/query/query.gen.go delete mode 100644 database/query/sys_apis.gen.go delete mode 100644 database/query/sys_dictionaries.gen.go delete mode 100644 database/query/sys_dictionary_details.gen.go delete mode 100644 database/query/sys_operation_records.gen.go delete mode 100644 database/query/sys_roles.gen.go delete mode 100644 database/query/user_roles.gen.go delete mode 100644 database/query/users.gen.go delete mode 100755 database/seeders/migration.go delete mode 100644 database/seeders/placeholder.go delete mode 100755 database/seeders/sys_role.go rename {common => ds}/request/page.go (100%) rename {common => ds}/response/page.go (100%) delete mode 100644 middleware/cors.go delete mode 100644 middleware/jwt.go delete mode 100644 middleware/middleware.go delete mode 100644 middleware/operation.go delete mode 100644 middleware/rbac.go delete mode 100755 modules/auth/container/container.go delete mode 100755 modules/auth/controller/permission.go delete mode 100755 modules/auth/controller/role.go delete mode 100755 modules/auth/controller/user.go delete mode 100755 modules/auth/dao/role.go delete mode 100755 modules/auth/dao/role_test.go delete mode 100755 modules/auth/dao/user.go delete mode 100755 modules/auth/dao/user_role.go delete mode 100755 modules/auth/dao/user_role_test.go delete mode 100755 modules/auth/dao/user_test.go delete mode 100644 modules/auth/dto/role.go delete mode 100644 modules/auth/dto/user.go delete mode 100755 modules/auth/routes/routes.go delete mode 100755 modules/auth/service/role.go delete mode 100755 modules/auth/service/user.go delete mode 100644 modules/modules.go delete mode 100644 modules/resources/.keep delete mode 100644 modules/resources/container/container.go delete mode 100644 modules/resources/routes/routes.go delete mode 100644 modules/system/container/container.go delete mode 100755 modules/system/controller/captcha.go delete mode 100644 modules/system/dao/dao.go delete mode 100644 modules/system/dao/dao_test.go delete mode 100644 modules/system/dto/captcha.go delete mode 100644 modules/system/routes/routes.go delete mode 100644 modules/system/service/service.go delete mode 100644 proto/.gitignore delete mode 100644 proto/web_api.proto create mode 100644 providers/captcha/config.go delete mode 100644 providers/captcha/driver/digit.go delete mode 100644 providers/config/loader.go delete mode 100644 providers/config/section_app.go delete mode 100644 providers/config/section_captcha.go delete mode 100755 providers/config/section_database.go delete mode 100644 providers/config/section_log.go delete mode 100644 providers/config/section_storage.go delete mode 100644 providers/database/database.go delete mode 100644 providers/database/mysql.go create mode 100755 providers/database/mysql/config.go create mode 100644 providers/database/mysql/mysql.go delete mode 100644 providers/database/postgres.go create mode 100755 providers/database/postgres/config.go create mode 100644 providers/database/postgres/postgres.go create mode 100644 providers/database/redis/todo.go delete mode 100644 providers/database/sqlite.go create mode 100755 providers/database/sqlite/config.go create mode 100644 providers/database/sqlite/sqlite.go delete mode 100644 providers/dictionary/dict.go delete mode 100644 providers/dictionary/info.go rename providers/{config/section_http.go => http/config.go} (51%) create mode 100644 providers/http/contracts.go delete mode 100644 providers/http/engine.go create mode 100644 providers/http/gin/engine.go create mode 100644 providers/jwt/config.go create mode 100644 providers/log/config.go delete mode 100644 providers/provider.go delete mode 100644 providers/query/query.go delete mode 100644 providers/rbac/casbin.go delete mode 100644 providers/rbac/rbac.go create mode 100644 services/http.go delete mode 100644 services/http/http.go rename utils/{ => db}/db.go (90%) rename {common => utils}/err/common.go (100%) delete mode 100644 utils/share.go diff --git a/bin/.gitignore b/bin/.gitignore deleted file mode 100644 index c96a04f..0000000 --- a/bin/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/cmd/migrate.go b/cmd/migrate.go index 663796a..b57647a 100644 --- a/cmd/migrate.go +++ b/cmd/migrate.go @@ -4,12 +4,8 @@ import ( "log" "sort" - // init dependencies - _ "atom/database/migrations" - _ "atom/providers" - - "atom/container" - "atom/contracts" + "github.com/rogeecn/atom/container" + "github.com/rogeecn/atom/contracts" "github.com/go-gormigrate/gormigrate/v2" "github.com/spf13/cobra" @@ -17,19 +13,21 @@ import ( "gorm.io/gorm" ) -// migrateCmd represents the migrate command -var migrateCmd = &cobra.Command{ - Use: "migrate", - Short: "migrate database tables", - Long: `migrate database tables`, -} - -func init() { +func WithMigration(rootCmd *cobra.Command) *cobra.Command { rootCmd.AddCommand(migrateCmd) migrateCmd.AddCommand(migrateUpCmd) migrateCmd.AddCommand(migrateDownCmd) migrateCmd.PersistentFlags().StringVar(&migrateToId, "to", "", "migration to id") + + return rootCmd +} + +// migrateCmd represents the migrate command +var migrateCmd = &cobra.Command{ + Use: "migrate", + Short: "migrate database tables", + Long: `migrate database tables`, } var migrateToId string @@ -50,7 +48,6 @@ var migrateUpCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { return container.Container.Invoke(func(mi MigrationInfo) error { m := gormigrate.New(mi.DB, gormigrate.DefaultOptions, sortedMigrations(mi.Migrations)) - if len(migrateToId) > 0 { log.Printf("migrate up to [%s]\n", migrateToId) return m.MigrateTo(migrateToId) diff --git a/cmd/model.go b/cmd/model.go index 8ca0452..6c7d86a 100644 --- a/cmd/model.go +++ b/cmd/model.go @@ -4,24 +4,29 @@ Copyright © 2023 NAME HERE package cmd import ( - "atom/container" - "atom/providers/config" - "atom/providers/database" "errors" "log" + "github.com/glebarez/sqlite" + "github.com/rogeecn/atom/container" "github.com/spf13/cobra" "go.uber.org/dig" + "gorm.io/driver/mysql" + "gorm.io/driver/postgres" "gorm.io/gen" "gorm.io/gorm" ) +func WithModel(rootCmd *cobra.Command) *cobra.Command { + rootCmd.AddCommand(modelCmd) + return rootCmd +} + // MigrationInfo http service container type GenQueryGenerator struct { dig.In - Config *config.Config - DB *gorm.DB + DB *gorm.DB } // // Dynamic SQL @@ -39,18 +44,18 @@ var modelCmd = &cobra.Command{ return container.Container.Invoke(func(gq GenQueryGenerator) error { var tables []string - switch gq.Config.Database.Driver { - case database.DriverMySQL: + switch gq.DB.Dialector.Name() { + case mysql.Dialector{}.Name(): err := gq.DB.Raw("show tables").Scan(&tables).Error if err != nil { log.Fatal(err) } - case database.DriverPostgres: + case postgres.Dialector{}.Name(): err := gq.DB.Raw("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'").Scan(&tables).Error if err != nil { log.Fatal(err) } - case database.DriverSQLite: + case sqlite.DriverName: err := gq.DB.Raw("SELECT name FROM sqlite_master WHERE type='table'").Scan(&tables).Error if err != nil { log.Fatal(err) @@ -89,7 +94,3 @@ var modelCmd = &cobra.Command{ }) }, } - -func init() { - rootCmd.AddCommand(modelCmd) -} diff --git a/cmd/root.go b/cmd/root.go deleted file mode 100644 index e705dcc..0000000 --- a/cmd/root.go +++ /dev/null @@ -1,39 +0,0 @@ -package cmd - -import ( - _ "atom/providers" - "log" - - "atom/container" - "atom/services/http" - "atom/utils" - "fmt" - "os" - - "github.com/spf13/cobra" -) - -var rootCmd = &cobra.Command{ - Use: "atom", - Short: "atom", - Long: `the app long description`, - Version: fmt.Sprintf("\nVersion: %s\nGitHash: %s\nBuildAt: %s\n", utils.Version, utils.GitHash, utils.BuildAt), - PersistentPreRun: func(cmd *cobra.Command, args []string) { - log.Println("using config file: ", utils.ShareConfigFile) - }, - RunE: func(cmd *cobra.Command, args []string) error { - return container.Container.Invoke(http.Serve) - }, -} - -func Execute() { - err := rootCmd.Execute() - if err != nil { - os.Exit(1) - } -} - -func init() { - rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") - rootCmd.PersistentFlags().StringVarP(&utils.ShareConfigFile, "config", "c", "config.toml", "config file") -} diff --git a/cmd/seed.go b/cmd/seed.go index abe780f..90dee87 100644 --- a/cmd/seed.go +++ b/cmd/seed.go @@ -1,22 +1,22 @@ -/* -Copyright © 2023 NAME HERE -*/ package cmd import ( - _ "atom/database/seeders" - _ "atom/providers" - - "atom/container" - "atom/contracts" "log" + "github.com/rogeecn/atom/container" + "github.com/rogeecn/atom/contracts" + "github.com/brianvoe/gofakeit/v6" "github.com/spf13/cobra" "go.uber.org/dig" "gorm.io/gorm" ) +func WithSeeder(rootCmd *cobra.Command) *cobra.Command { + rootCmd.AddCommand(seedCmd) + return rootCmd +} + // seedCmd represents the seed command var seedCmd = &cobra.Command{ Use: "seed", @@ -40,10 +40,6 @@ var seedCmd = &cobra.Command{ }, } -func init() { - rootCmd.AddCommand(seedCmd) -} - type SeedersContainer struct { dig.In diff --git a/common/structure/sex.go b/common/structure/sex.go deleted file mode 100644 index 6fe4564..0000000 --- a/common/structure/sex.go +++ /dev/null @@ -1 +0,0 @@ -package structure diff --git a/container/container.go b/container/container.go index 26749ba..79c3a55 100644 --- a/container/container.go +++ b/container/container.go @@ -8,9 +8,14 @@ import ( ) var Container *dig.Container = dig.New() +var Cancel context.CancelFunc func init() { - if err := Container.Provide(context.Background); err != nil { + if err := Container.Provide(func() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + Cancel = cancel + return ctx + }); err != nil { log.Fatal(err) } } diff --git a/contracts/routes.go b/contracts/routes.go deleted file mode 100644 index 4c567c9..0000000 --- a/contracts/routes.go +++ /dev/null @@ -1,5 +0,0 @@ -package contracts - -type Route interface { - Register() -} diff --git a/database/migrations/20230130_193508_create_sys_operation_record.go b/database/migrations/20230130_193508_create_sys_operation_record.go deleted file mode 100755 index 58e2203..0000000 --- a/database/migrations/20230130_193508_create_sys_operation_record.go +++ /dev/null @@ -1,56 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - "time" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230130_193508CreateSysOperationRecordMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230130_193508CreateSysOperationRecord struct { - id string -} - -func New20230130_193508CreateSysOperationRecordMigration() contracts.Migration { - return &Migration20230130_193508CreateSysOperationRecord{id: "20230130_193508_create_sys_operation_record"} -} - -func (m *Migration20230130_193508CreateSysOperationRecord) ID() string { - return m.id -} - -func (m *Migration20230130_193508CreateSysOperationRecord) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230130_193508CreateSysOperationRecord) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230130_193508CreateSysOperationRecord) table() interface{} { - type SysOperationRecord struct { - gorm.Model - Ip string `gorm:"comment:请求ip"` - Method string `gorm:"comment:请求方法"` - Path string `gorm:"comment:请求路径"` - Status int `gorm:"comment:请求状态"` - Latency time.Duration `gorm:"comment:延迟"` - Agent string `gorm:"comment:代理"` - ErrorMessage string `gorm:"comment:错误信息"` - Body string `gorm:"comment:请求Body"` - Resp string `gorm:"comment:响应Body"` - UserID int `gorm:"comment:用户id"` - } - - return SysOperationRecord{} -} diff --git a/database/migrations/20230131_160904_create_user.go b/database/migrations/20230131_160904_create_user.go deleted file mode 100755 index b076e54..0000000 --- a/database/migrations/20230131_160904_create_user.go +++ /dev/null @@ -1,56 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - "github.com/gofrs/uuid" - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_160904CreateUserMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_160904CreateUser struct { - id string -} - -func New20230131_160904CreateUserMigration() contracts.Migration { - return &Migration20230131_160904CreateUser{id: "20230131_160904_create_user"} -} - -func (m *Migration20230131_160904CreateUser) ID() string { - return m.id -} - -func (m *Migration20230131_160904CreateUser) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_160904CreateUser) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_160904CreateUser) table() interface{} { - type User struct { - gorm.Model - - UUID uuid.UUID `gorm:"index;comment:UUID"` - Username string `gorm:"index;comment:登录名"` - Password string `gorm:"comment:登录密码"` - Nickname string `gorm:"default:'';comment:昵称"` - Avatar string `gorm:"default:'';comment:头像"` - RoleID uint `gorm:"default:1;comment:角色ID"` - Phone string `gorm:"comment:手机号"` - Email string `gorm:"comment:邮箱"` - Status string `gorm:"default:ok;comment:用户状态"` // OK,BLOCKED,DISABLED, - } - - return User{} -} diff --git a/database/migrations/20230131_162400_create_sys_api.go b/database/migrations/20230131_162400_create_sys_api.go deleted file mode 100755 index 2bd5ee6..0000000 --- a/database/migrations/20230131_162400_create_sys_api.go +++ /dev/null @@ -1,50 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_162400CreateSysApiMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_162400CreateSysApi struct { - id string -} - -func New20230131_162400CreateSysApiMigration() contracts.Migration { - return &Migration20230131_162400CreateSysApi{id: "20230131_162400_create_sys_api"} -} - -func (m *Migration20230131_162400CreateSysApi) ID() string { - return m.id -} - -func (m *Migration20230131_162400CreateSysApi) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_162400CreateSysApi) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_162400CreateSysApi) table() interface{} { - type SysApi struct { - gorm.Model - - Path string `gorm:"comment:路径"` - Description string `gorm:"comment:中文描述"` - ApiGroup string `gorm:"comment:组"` - Method string `gorm:"default:GET;comment:方法"` - } - - return SysApi{} -} diff --git a/database/migrations/20230131_165134_create_sys_dictionary.go b/database/migrations/20230131_165134_create_sys_dictionary.go deleted file mode 100755 index 7397a8d..0000000 --- a/database/migrations/20230131_165134_create_sys_dictionary.go +++ /dev/null @@ -1,50 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_165134CreateSysDictionaryMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_165134CreateSysDictionary struct { - id string -} - -func New20230131_165134CreateSysDictionaryMigration() contracts.Migration { - return &Migration20230131_165134CreateSysDictionary{id: "20230131_165134_create_sys_dictionary"} -} - -func (m *Migration20230131_165134CreateSysDictionary) ID() string { - return m.id -} - -func (m *Migration20230131_165134CreateSysDictionary) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_165134CreateSysDictionary) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_165134CreateSysDictionary) table() interface{} { - type SysDictionary struct { - gorm.Model - - Name string `gorm:"comment:字典名(中)"` // 字典名(中) - Alias string `gorm:"comment:字典名(英)"` // 字典名(英) - Status bool `gorm:"comment:状态"` // 状态 - Description string `gorm:"comment:描述"` // 描述 - } - - return SysDictionary{} -} diff --git a/database/migrations/20230131_165218_create_sys_dictionary_detail.go b/database/migrations/20230131_165218_create_sys_dictionary_detail.go deleted file mode 100755 index 4c57096..0000000 --- a/database/migrations/20230131_165218_create_sys_dictionary_detail.go +++ /dev/null @@ -1,51 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_165218CreateSysDictionaryDetailMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_165218CreateSysDictionaryDetail struct { - id string -} - -func New20230131_165218CreateSysDictionaryDetailMigration() contracts.Migration { - return &Migration20230131_165218CreateSysDictionaryDetail{id: "20230131_165218_create_sys_dictionary_detail"} -} - -func (m *Migration20230131_165218CreateSysDictionaryDetail) ID() string { - return m.id -} - -func (m *Migration20230131_165218CreateSysDictionaryDetail) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_165218CreateSysDictionaryDetail) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_165218CreateSysDictionaryDetail) table() interface{} { - type SysDictionaryDetail struct { - gorm.Model - - SysDictionaryID int `gorm:"comment:关联标记"` - Label string `gorm:"comment:展示值"` - Value string `gorm:"comment:字典值"` - Status bool `gorm:"comment:启用状态"` - Weight int `gorm:"comment:排序权重"` - } - - return SysDictionaryDetail{} -} diff --git a/database/migrations/20230131_165352_create_user_role.go b/database/migrations/20230131_165352_create_user_role.go deleted file mode 100755 index 7c3d3b3..0000000 --- a/database/migrations/20230131_165352_create_user_role.go +++ /dev/null @@ -1,46 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_165352CreateUserRoleMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_165352CreateUserRole struct { - id string -} - -func New20230131_165352CreateUserRoleMigration() contracts.Migration { - return &Migration20230131_165352CreateUserRole{id: "20230131_165352_create_user_role"} -} - -func (m *Migration20230131_165352CreateUserRole) ID() string { - return m.id -} - -func (m *Migration20230131_165352CreateUserRole) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_165352CreateUserRole) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_165352CreateUserRole) table() interface{} { - type UserRole struct { - UserID uint `gorm:"column:user_id"` - RoleID uint `gorm:"column:role_id"` - } - - return UserRole{} -} diff --git a/database/migrations/20230131_165509_create_sys_role.go b/database/migrations/20230131_165509_create_sys_role.go deleted file mode 100755 index 82ba148..0000000 --- a/database/migrations/20230131_165509_create_sys_role.go +++ /dev/null @@ -1,50 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_165509CreateSysRoleMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_165509CreateSysRole struct { - id string -} - -func New20230131_165509CreateSysRoleMigration() contracts.Migration { - return &Migration20230131_165509CreateSysRole{id: "20230131_165509_create_sys_role"} -} - -func (m *Migration20230131_165509CreateSysRole) ID() string { - return m.id -} - -func (m *Migration20230131_165509CreateSysRole) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_165509CreateSysRole) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_165509CreateSysRole) table() interface{} { - type SysRole struct { - gorm.Model - - UUID string `gorm:"not null;unique;primary_key;comment:角色Alias;size:90"` // 角色UUID - Name string `gorm:"comment:角色名"` // 角色名 - ParentId *uint `gorm:"comment:父角色ID"` // 父角色ID - DefaultRouter string `gorm:"comment:默认菜单;default:dashboard"` // 默认菜单(默认dashboard) - } - - return SysRole{} -} diff --git a/database/migrations/20230131_170433_create_casbin_rule.go b/database/migrations/20230131_170433_create_casbin_rule.go deleted file mode 100755 index ac9abc0..0000000 --- a/database/migrations/20230131_170433_create_casbin_rule.go +++ /dev/null @@ -1,43 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "atom/providers/log" - - adapter "github.com/casbin/gorm-adapter/v3" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20230131_170433CreateCasbinRuleMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20230131_170433CreateCasbinRule struct { - id string -} - -func New20230131_170433CreateCasbinRuleMigration() contracts.Migration { - return &Migration20230131_170433CreateCasbinRule{id: "20230131_170433_create_casbin_rule"} -} - -func (m *Migration20230131_170433CreateCasbinRule) ID() string { - return m.id -} - -func (m *Migration20230131_170433CreateCasbinRule) Up(tx *gorm.DB) error { - table := m.table() - return tx.AutoMigrate(&table) -} - -func (m *Migration20230131_170433CreateCasbinRule) Down(tx *gorm.DB) error { - return tx.Migrator().DropTable(m.table()) -} - -func (m *Migration20230131_170433CreateCasbinRule) table() interface{} { - return adapter.CasbinRule{} -} diff --git a/database/migrations/placeholder.go b/database/migrations/placeholder.go deleted file mode 100644 index ea51298..0000000 --- a/database/migrations/placeholder.go +++ /dev/null @@ -1,36 +0,0 @@ -package migrations - -import ( - "atom/container" - "atom/contracts" - "log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(New20140202InitMigration, dig.Group("migrations")); err != nil { - log.Fatal(err) - } -} - -type Migration20140202Init struct { - id string -} - -func New20140202InitMigration() contracts.Migration { - return &Migration20140202Init{id: "20140202_package_placeholder"} -} - -func (m *Migration20140202Init) ID() string { - return m.id -} - -func (m *Migration20140202Init) Up(tx *gorm.DB) error { - return nil -} - -func (m *Migration20140202Init) Down(tx *gorm.DB) error { - return nil -} diff --git a/database/models/casbin_rule.gen.go b/database/models/casbin_rule.gen.go deleted file mode 100644 index 2fc2b63..0000000 --- a/database/models/casbin_rule.gen.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -const TableNameCasbinRule = "casbin_rule" - -// CasbinRule mapped from table -type CasbinRule struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - Ptype string `gorm:"column:ptype;type:varchar(100)" json:"ptype"` - V0 string `gorm:"column:v0;type:varchar(100)" json:"v0"` - V1 string `gorm:"column:v1;type:varchar(100)" json:"v1"` - V2 string `gorm:"column:v2;type:varchar(100)" json:"v2"` - V3 string `gorm:"column:v3;type:varchar(100)" json:"v3"` - V4 string `gorm:"column:v4;type:varchar(100)" json:"v4"` - V5 string `gorm:"column:v5;type:varchar(100)" json:"v5"` -} - -// TableName CasbinRule's table name -func (*CasbinRule) TableName() string { - return TableNameCasbinRule -} diff --git a/database/models/migrations.gen.go b/database/models/migrations.gen.go deleted file mode 100644 index e327ab0..0000000 --- a/database/models/migrations.gen.go +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -const TableNameMigration = "migrations" - -// Migration mapped from table -type Migration struct { - ID string `gorm:"column:id;type:varchar(255);primaryKey" json:"id"` -} - -// TableName Migration's table name -func (*Migration) TableName() string { - return TableNameMigration -} diff --git a/database/models/sys_apis.gen.go b/database/models/sys_apis.gen.go deleted file mode 100644 index db92bf5..0000000 --- a/database/models/sys_apis.gen.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -import ( - "time" - - "gorm.io/gorm" -) - -const TableNameSysAPI = "sys_apis" - -// SysAPI mapped from table -type SysAPI struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"` - Path string `gorm:"column:path;type:varchar(191)" json:"path"` // 路径 - Description string `gorm:"column:description;type:varchar(191)" json:"description"` // 中文描述 - APIGroup string `gorm:"column:api_group;type:varchar(191)" json:"api_group"` // 组 - Method string `gorm:"column:method;type:varchar(191);default:GET" json:"method"` // 方法 -} - -// TableName SysAPI's table name -func (*SysAPI) TableName() string { - return TableNameSysAPI -} diff --git a/database/models/sys_dictionaries.gen.go b/database/models/sys_dictionaries.gen.go deleted file mode 100644 index cc32c08..0000000 --- a/database/models/sys_dictionaries.gen.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -import ( - "time" - - "gorm.io/gorm" -) - -const TableNameSysDictionary = "sys_dictionaries" - -// SysDictionary mapped from table -type SysDictionary struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"` - Name string `gorm:"column:name;type:varchar(191)" json:"name"` // 字典名(中) - Alias_ string `gorm:"column:alias;type:varchar(191)" json:"alias"` // 字典名(英) - Status bool `gorm:"column:status;type:tinyint(1)" json:"status"` // 状态 - Description string `gorm:"column:description;type:varchar(191)" json:"description"` // 描述 -} - -// TableName SysDictionary's table name -func (*SysDictionary) TableName() string { - return TableNameSysDictionary -} diff --git a/database/models/sys_dictionary_details.gen.go b/database/models/sys_dictionary_details.gen.go deleted file mode 100644 index 81d5d37..0000000 --- a/database/models/sys_dictionary_details.gen.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -import ( - "time" - - "gorm.io/gorm" -) - -const TableNameSysDictionaryDetail = "sys_dictionary_details" - -// SysDictionaryDetail mapped from table -type SysDictionaryDetail struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"` - SysDictionaryID int64 `gorm:"column:sys_dictionary_id;type:bigint(20)" json:"sys_dictionary_id"` // 关联标记 - Label string `gorm:"column:label;type:varchar(191)" json:"label"` // 展示值 - Value string `gorm:"column:value;type:varchar(191)" json:"value"` // 字典值 - Status bool `gorm:"column:status;type:tinyint(1)" json:"status"` // 启用状态 - Weight int64 `gorm:"column:weight;type:bigint(20)" json:"weight"` // 排序权重 -} - -// TableName SysDictionaryDetail's table name -func (*SysDictionaryDetail) TableName() string { - return TableNameSysDictionaryDetail -} diff --git a/database/models/sys_operation_records.gen.go b/database/models/sys_operation_records.gen.go deleted file mode 100644 index cb9e2c2..0000000 --- a/database/models/sys_operation_records.gen.go +++ /dev/null @@ -1,36 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -import ( - "time" - - "gorm.io/gorm" -) - -const TableNameSysOperationRecord = "sys_operation_records" - -// SysOperationRecord mapped from table -type SysOperationRecord struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"` - IP string `gorm:"column:ip;type:varchar(191)" json:"ip"` // 请求ip - Method string `gorm:"column:method;type:varchar(191)" json:"method"` // 请求方法 - Path string `gorm:"column:path;type:varchar(191)" json:"path"` // 请求路径 - Status int64 `gorm:"column:status;type:bigint(20)" json:"status"` // 请求状态 - Latency int64 `gorm:"column:latency;type:bigint(20)" json:"latency"` // 延迟 - Agent string `gorm:"column:agent;type:varchar(191)" json:"agent"` // 代理 - ErrorMessage string `gorm:"column:error_message;type:varchar(191)" json:"error_message"` // 错误信息 - Body string `gorm:"column:body;type:varchar(191)" json:"body"` // 请求Body - Resp string `gorm:"column:resp;type:varchar(191)" json:"resp"` // 响应Body - UserID int64 `gorm:"column:user_id;type:bigint(20)" json:"user_id"` // 用户id -} - -// TableName SysOperationRecord's table name -func (*SysOperationRecord) TableName() string { - return TableNameSysOperationRecord -} diff --git a/database/models/sys_roles.gen.go b/database/models/sys_roles.gen.go deleted file mode 100644 index b25393a..0000000 --- a/database/models/sys_roles.gen.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -import ( - "time" - - "gorm.io/gorm" -) - -const TableNameSysRole = "sys_roles" - -// SysRole mapped from table -type SysRole struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"` - UUID string `gorm:"column:uuid;type:varchar(90);primaryKey" json:"uuid"` // 角色Alias - Name string `gorm:"column:name;type:varchar(191)" json:"name"` // 角色名 - ParentID uint64 `gorm:"column:parent_id;type:bigint(20) unsigned" json:"parent_id"` // 父角色ID - DefaultRouter string `gorm:"column:default_router;type:varchar(191);default:dashboard" json:"default_router"` // 默认菜单 -} - -// TableName SysRole's table name -func (*SysRole) TableName() string { - return TableNameSysRole -} diff --git a/database/models/user_roles.gen.go b/database/models/user_roles.gen.go deleted file mode 100644 index 9e150a1..0000000 --- a/database/models/user_roles.gen.go +++ /dev/null @@ -1,18 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -const TableNameUserRole = "user_roles" - -// UserRole mapped from table -type UserRole struct { - UserID uint64 `gorm:"column:user_id;type:bigint(20) unsigned" json:"user_id"` - RoleID uint64 `gorm:"column:role_id;type:bigint(20) unsigned" json:"role_id"` -} - -// TableName UserRole's table name -func (*UserRole) TableName() string { - return TableNameUserRole -} diff --git a/database/models/users.gen.go b/database/models/users.gen.go deleted file mode 100644 index 38ddbd7..0000000 --- a/database/models/users.gen.go +++ /dev/null @@ -1,35 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package models - -import ( - "time" - - "gorm.io/gorm" -) - -const TableNameUser = "users" - -// User mapped from table -type User struct { - ID uint64 `gorm:"column:id;type:bigint(20) unsigned;primaryKey;autoIncrement:true" json:"id"` - CreatedAt time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"` - UpdatedAt time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"` - DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3)" json:"deleted_at"` - UUID string `gorm:"column:uuid;type:varchar(191)" json:"uuid"` // UUID - Username string `gorm:"column:username;type:varchar(191)" json:"username"` // 登录名 - Password string `gorm:"column:password;type:varchar(191)" json:"password"` // 登录密码 - Nickname string `gorm:"column:nickname;type:varchar(191)" json:"nickname"` // 昵称 - Avatar string `gorm:"column:avatar;type:varchar(191)" json:"avatar"` // 头像 - RoleID uint64 `gorm:"column:role_id;type:bigint(20) unsigned;default:1" json:"role_id"` // 角色ID - Phone string `gorm:"column:phone;type:varchar(191)" json:"phone"` // 手机号 - Email string `gorm:"column:email;type:varchar(191)" json:"email"` // 邮箱 - Status string `gorm:"column:status;type:varchar(191);default:ok" json:"status"` // 用户状态 -} - -// TableName User's table name -func (*User) TableName() string { - return TableNameUser -} diff --git a/database/query/casbin_rule.gen.go b/database/query/casbin_rule.gen.go deleted file mode 100644 index 99dc914..0000000 --- a/database/query/casbin_rule.gen.go +++ /dev/null @@ -1,420 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newCasbinRule(db *gorm.DB, opts ...gen.DOOption) casbinRule { - _casbinRule := casbinRule{} - - _casbinRule.casbinRuleDo.UseDB(db, opts...) - _casbinRule.casbinRuleDo.UseModel(&models.CasbinRule{}) - - tableName := _casbinRule.casbinRuleDo.TableName() - _casbinRule.ALL = field.NewAsterisk(tableName) - _casbinRule.ID = field.NewUint64(tableName, "id") - _casbinRule.Ptype = field.NewString(tableName, "ptype") - _casbinRule.V0 = field.NewString(tableName, "v0") - _casbinRule.V1 = field.NewString(tableName, "v1") - _casbinRule.V2 = field.NewString(tableName, "v2") - _casbinRule.V3 = field.NewString(tableName, "v3") - _casbinRule.V4 = field.NewString(tableName, "v4") - _casbinRule.V5 = field.NewString(tableName, "v5") - - _casbinRule.fillFieldMap() - - return _casbinRule -} - -type casbinRule struct { - casbinRuleDo casbinRuleDo - - ALL field.Asterisk - ID field.Uint64 - Ptype field.String - V0 field.String - V1 field.String - V2 field.String - V3 field.String - V4 field.String - V5 field.String - - fieldMap map[string]field.Expr -} - -func (c casbinRule) Table(newTableName string) *casbinRule { - c.casbinRuleDo.UseTable(newTableName) - return c.updateTableName(newTableName) -} - -func (c casbinRule) As(alias string) *casbinRule { - c.casbinRuleDo.DO = *(c.casbinRuleDo.As(alias).(*gen.DO)) - return c.updateTableName(alias) -} - -func (c *casbinRule) updateTableName(table string) *casbinRule { - c.ALL = field.NewAsterisk(table) - c.ID = field.NewUint64(table, "id") - c.Ptype = field.NewString(table, "ptype") - c.V0 = field.NewString(table, "v0") - c.V1 = field.NewString(table, "v1") - c.V2 = field.NewString(table, "v2") - c.V3 = field.NewString(table, "v3") - c.V4 = field.NewString(table, "v4") - c.V5 = field.NewString(table, "v5") - - c.fillFieldMap() - - return c -} - -func (c *casbinRule) WithContext(ctx context.Context) ICasbinRuleDo { - return c.casbinRuleDo.WithContext(ctx) -} - -func (c casbinRule) TableName() string { return c.casbinRuleDo.TableName() } - -func (c casbinRule) Alias() string { return c.casbinRuleDo.Alias() } - -func (c *casbinRule) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := c.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (c *casbinRule) fillFieldMap() { - c.fieldMap = make(map[string]field.Expr, 8) - c.fieldMap["id"] = c.ID - c.fieldMap["ptype"] = c.Ptype - c.fieldMap["v0"] = c.V0 - c.fieldMap["v1"] = c.V1 - c.fieldMap["v2"] = c.V2 - c.fieldMap["v3"] = c.V3 - c.fieldMap["v4"] = c.V4 - c.fieldMap["v5"] = c.V5 -} - -func (c casbinRule) clone(db *gorm.DB) casbinRule { - c.casbinRuleDo.ReplaceConnPool(db.Statement.ConnPool) - return c -} - -func (c casbinRule) replaceDB(db *gorm.DB) casbinRule { - c.casbinRuleDo.ReplaceDB(db) - return c -} - -type casbinRuleDo struct{ gen.DO } - -type ICasbinRuleDo interface { - gen.SubQuery - Debug() ICasbinRuleDo - WithContext(ctx context.Context) ICasbinRuleDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ICasbinRuleDo - WriteDB() ICasbinRuleDo - As(alias string) gen.Dao - Session(config *gorm.Session) ICasbinRuleDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ICasbinRuleDo - Not(conds ...gen.Condition) ICasbinRuleDo - Or(conds ...gen.Condition) ICasbinRuleDo - Select(conds ...field.Expr) ICasbinRuleDo - Where(conds ...gen.Condition) ICasbinRuleDo - Order(conds ...field.Expr) ICasbinRuleDo - Distinct(cols ...field.Expr) ICasbinRuleDo - Omit(cols ...field.Expr) ICasbinRuleDo - Join(table schema.Tabler, on ...field.Expr) ICasbinRuleDo - LeftJoin(table schema.Tabler, on ...field.Expr) ICasbinRuleDo - RightJoin(table schema.Tabler, on ...field.Expr) ICasbinRuleDo - Group(cols ...field.Expr) ICasbinRuleDo - Having(conds ...gen.Condition) ICasbinRuleDo - Limit(limit int) ICasbinRuleDo - Offset(offset int) ICasbinRuleDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ICasbinRuleDo - Unscoped() ICasbinRuleDo - Create(values ...*models.CasbinRule) error - CreateInBatches(values []*models.CasbinRule, batchSize int) error - Save(values ...*models.CasbinRule) error - First() (*models.CasbinRule, error) - Take() (*models.CasbinRule, error) - Last() (*models.CasbinRule, error) - Find() ([]*models.CasbinRule, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.CasbinRule, err error) - FindInBatches(result *[]*models.CasbinRule, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.CasbinRule) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) ICasbinRuleDo - Assign(attrs ...field.AssignExpr) ICasbinRuleDo - Joins(fields ...field.RelationField) ICasbinRuleDo - Preload(fields ...field.RelationField) ICasbinRuleDo - FirstOrInit() (*models.CasbinRule, error) - FirstOrCreate() (*models.CasbinRule, error) - FindByPage(offset int, limit int) (result []*models.CasbinRule, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) ICasbinRuleDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (c casbinRuleDo) Debug() ICasbinRuleDo { - return c.withDO(c.DO.Debug()) -} - -func (c casbinRuleDo) WithContext(ctx context.Context) ICasbinRuleDo { - return c.withDO(c.DO.WithContext(ctx)) -} - -func (c casbinRuleDo) ReadDB() ICasbinRuleDo { - return c.Clauses(dbresolver.Read) -} - -func (c casbinRuleDo) WriteDB() ICasbinRuleDo { - return c.Clauses(dbresolver.Write) -} - -func (c casbinRuleDo) Session(config *gorm.Session) ICasbinRuleDo { - return c.withDO(c.DO.Session(config)) -} - -func (c casbinRuleDo) Clauses(conds ...clause.Expression) ICasbinRuleDo { - return c.withDO(c.DO.Clauses(conds...)) -} - -func (c casbinRuleDo) Returning(value interface{}, columns ...string) ICasbinRuleDo { - return c.withDO(c.DO.Returning(value, columns...)) -} - -func (c casbinRuleDo) Not(conds ...gen.Condition) ICasbinRuleDo { - return c.withDO(c.DO.Not(conds...)) -} - -func (c casbinRuleDo) Or(conds ...gen.Condition) ICasbinRuleDo { - return c.withDO(c.DO.Or(conds...)) -} - -func (c casbinRuleDo) Select(conds ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.Select(conds...)) -} - -func (c casbinRuleDo) Where(conds ...gen.Condition) ICasbinRuleDo { - return c.withDO(c.DO.Where(conds...)) -} - -func (c casbinRuleDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ICasbinRuleDo { - return c.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (c casbinRuleDo) Order(conds ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.Order(conds...)) -} - -func (c casbinRuleDo) Distinct(cols ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.Distinct(cols...)) -} - -func (c casbinRuleDo) Omit(cols ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.Omit(cols...)) -} - -func (c casbinRuleDo) Join(table schema.Tabler, on ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.Join(table, on...)) -} - -func (c casbinRuleDo) LeftJoin(table schema.Tabler, on ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.LeftJoin(table, on...)) -} - -func (c casbinRuleDo) RightJoin(table schema.Tabler, on ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.RightJoin(table, on...)) -} - -func (c casbinRuleDo) Group(cols ...field.Expr) ICasbinRuleDo { - return c.withDO(c.DO.Group(cols...)) -} - -func (c casbinRuleDo) Having(conds ...gen.Condition) ICasbinRuleDo { - return c.withDO(c.DO.Having(conds...)) -} - -func (c casbinRuleDo) Limit(limit int) ICasbinRuleDo { - return c.withDO(c.DO.Limit(limit)) -} - -func (c casbinRuleDo) Offset(offset int) ICasbinRuleDo { - return c.withDO(c.DO.Offset(offset)) -} - -func (c casbinRuleDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ICasbinRuleDo { - return c.withDO(c.DO.Scopes(funcs...)) -} - -func (c casbinRuleDo) Unscoped() ICasbinRuleDo { - return c.withDO(c.DO.Unscoped()) -} - -func (c casbinRuleDo) Create(values ...*models.CasbinRule) error { - if len(values) == 0 { - return nil - } - return c.DO.Create(values) -} - -func (c casbinRuleDo) CreateInBatches(values []*models.CasbinRule, batchSize int) error { - return c.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (c casbinRuleDo) Save(values ...*models.CasbinRule) error { - if len(values) == 0 { - return nil - } - return c.DO.Save(values) -} - -func (c casbinRuleDo) First() (*models.CasbinRule, error) { - if result, err := c.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.CasbinRule), nil - } -} - -func (c casbinRuleDo) Take() (*models.CasbinRule, error) { - if result, err := c.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.CasbinRule), nil - } -} - -func (c casbinRuleDo) Last() (*models.CasbinRule, error) { - if result, err := c.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.CasbinRule), nil - } -} - -func (c casbinRuleDo) Find() ([]*models.CasbinRule, error) { - result, err := c.DO.Find() - return result.([]*models.CasbinRule), err -} - -func (c casbinRuleDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.CasbinRule, err error) { - buf := make([]*models.CasbinRule, 0, batchSize) - err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (c casbinRuleDo) FindInBatches(result *[]*models.CasbinRule, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return c.DO.FindInBatches(result, batchSize, fc) -} - -func (c casbinRuleDo) Attrs(attrs ...field.AssignExpr) ICasbinRuleDo { - return c.withDO(c.DO.Attrs(attrs...)) -} - -func (c casbinRuleDo) Assign(attrs ...field.AssignExpr) ICasbinRuleDo { - return c.withDO(c.DO.Assign(attrs...)) -} - -func (c casbinRuleDo) Joins(fields ...field.RelationField) ICasbinRuleDo { - for _, _f := range fields { - c = *c.withDO(c.DO.Joins(_f)) - } - return &c -} - -func (c casbinRuleDo) Preload(fields ...field.RelationField) ICasbinRuleDo { - for _, _f := range fields { - c = *c.withDO(c.DO.Preload(_f)) - } - return &c -} - -func (c casbinRuleDo) FirstOrInit() (*models.CasbinRule, error) { - if result, err := c.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.CasbinRule), nil - } -} - -func (c casbinRuleDo) FirstOrCreate() (*models.CasbinRule, error) { - if result, err := c.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.CasbinRule), nil - } -} - -func (c casbinRuleDo) FindByPage(offset int, limit int) (result []*models.CasbinRule, count int64, err error) { - result, err = c.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = c.Offset(-1).Limit(-1).Count() - return -} - -func (c casbinRuleDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = c.Count() - if err != nil { - return - } - - err = c.Offset(offset).Limit(limit).Scan(result) - return -} - -func (c casbinRuleDo) Scan(result interface{}) (err error) { - return c.DO.Scan(result) -} - -func (c casbinRuleDo) Delete(models ...*models.CasbinRule) (result gen.ResultInfo, err error) { - return c.DO.Delete(models) -} - -func (c *casbinRuleDo) withDO(do gen.Dao) *casbinRuleDo { - c.DO = *do.(*gen.DO) - return c -} diff --git a/database/query/migrations.gen.go b/database/query/migrations.gen.go deleted file mode 100644 index 2174a6b..0000000 --- a/database/query/migrations.gen.go +++ /dev/null @@ -1,392 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newMigration(db *gorm.DB, opts ...gen.DOOption) migration { - _migration := migration{} - - _migration.migrationDo.UseDB(db, opts...) - _migration.migrationDo.UseModel(&models.Migration{}) - - tableName := _migration.migrationDo.TableName() - _migration.ALL = field.NewAsterisk(tableName) - _migration.ID = field.NewString(tableName, "id") - - _migration.fillFieldMap() - - return _migration -} - -type migration struct { - migrationDo migrationDo - - ALL field.Asterisk - ID field.String - - fieldMap map[string]field.Expr -} - -func (m migration) Table(newTableName string) *migration { - m.migrationDo.UseTable(newTableName) - return m.updateTableName(newTableName) -} - -func (m migration) As(alias string) *migration { - m.migrationDo.DO = *(m.migrationDo.As(alias).(*gen.DO)) - return m.updateTableName(alias) -} - -func (m *migration) updateTableName(table string) *migration { - m.ALL = field.NewAsterisk(table) - m.ID = field.NewString(table, "id") - - m.fillFieldMap() - - return m -} - -func (m *migration) WithContext(ctx context.Context) IMigrationDo { - return m.migrationDo.WithContext(ctx) -} - -func (m migration) TableName() string { return m.migrationDo.TableName() } - -func (m migration) Alias() string { return m.migrationDo.Alias() } - -func (m *migration) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := m.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (m *migration) fillFieldMap() { - m.fieldMap = make(map[string]field.Expr, 1) - m.fieldMap["id"] = m.ID -} - -func (m migration) clone(db *gorm.DB) migration { - m.migrationDo.ReplaceConnPool(db.Statement.ConnPool) - return m -} - -func (m migration) replaceDB(db *gorm.DB) migration { - m.migrationDo.ReplaceDB(db) - return m -} - -type migrationDo struct{ gen.DO } - -type IMigrationDo interface { - gen.SubQuery - Debug() IMigrationDo - WithContext(ctx context.Context) IMigrationDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IMigrationDo - WriteDB() IMigrationDo - As(alias string) gen.Dao - Session(config *gorm.Session) IMigrationDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IMigrationDo - Not(conds ...gen.Condition) IMigrationDo - Or(conds ...gen.Condition) IMigrationDo - Select(conds ...field.Expr) IMigrationDo - Where(conds ...gen.Condition) IMigrationDo - Order(conds ...field.Expr) IMigrationDo - Distinct(cols ...field.Expr) IMigrationDo - Omit(cols ...field.Expr) IMigrationDo - Join(table schema.Tabler, on ...field.Expr) IMigrationDo - LeftJoin(table schema.Tabler, on ...field.Expr) IMigrationDo - RightJoin(table schema.Tabler, on ...field.Expr) IMigrationDo - Group(cols ...field.Expr) IMigrationDo - Having(conds ...gen.Condition) IMigrationDo - Limit(limit int) IMigrationDo - Offset(offset int) IMigrationDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IMigrationDo - Unscoped() IMigrationDo - Create(values ...*models.Migration) error - CreateInBatches(values []*models.Migration, batchSize int) error - Save(values ...*models.Migration) error - First() (*models.Migration, error) - Take() (*models.Migration, error) - Last() (*models.Migration, error) - Find() ([]*models.Migration, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Migration, err error) - FindInBatches(result *[]*models.Migration, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.Migration) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) IMigrationDo - Assign(attrs ...field.AssignExpr) IMigrationDo - Joins(fields ...field.RelationField) IMigrationDo - Preload(fields ...field.RelationField) IMigrationDo - FirstOrInit() (*models.Migration, error) - FirstOrCreate() (*models.Migration, error) - FindByPage(offset int, limit int) (result []*models.Migration, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) IMigrationDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (m migrationDo) Debug() IMigrationDo { - return m.withDO(m.DO.Debug()) -} - -func (m migrationDo) WithContext(ctx context.Context) IMigrationDo { - return m.withDO(m.DO.WithContext(ctx)) -} - -func (m migrationDo) ReadDB() IMigrationDo { - return m.Clauses(dbresolver.Read) -} - -func (m migrationDo) WriteDB() IMigrationDo { - return m.Clauses(dbresolver.Write) -} - -func (m migrationDo) Session(config *gorm.Session) IMigrationDo { - return m.withDO(m.DO.Session(config)) -} - -func (m migrationDo) Clauses(conds ...clause.Expression) IMigrationDo { - return m.withDO(m.DO.Clauses(conds...)) -} - -func (m migrationDo) Returning(value interface{}, columns ...string) IMigrationDo { - return m.withDO(m.DO.Returning(value, columns...)) -} - -func (m migrationDo) Not(conds ...gen.Condition) IMigrationDo { - return m.withDO(m.DO.Not(conds...)) -} - -func (m migrationDo) Or(conds ...gen.Condition) IMigrationDo { - return m.withDO(m.DO.Or(conds...)) -} - -func (m migrationDo) Select(conds ...field.Expr) IMigrationDo { - return m.withDO(m.DO.Select(conds...)) -} - -func (m migrationDo) Where(conds ...gen.Condition) IMigrationDo { - return m.withDO(m.DO.Where(conds...)) -} - -func (m migrationDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) IMigrationDo { - return m.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (m migrationDo) Order(conds ...field.Expr) IMigrationDo { - return m.withDO(m.DO.Order(conds...)) -} - -func (m migrationDo) Distinct(cols ...field.Expr) IMigrationDo { - return m.withDO(m.DO.Distinct(cols...)) -} - -func (m migrationDo) Omit(cols ...field.Expr) IMigrationDo { - return m.withDO(m.DO.Omit(cols...)) -} - -func (m migrationDo) Join(table schema.Tabler, on ...field.Expr) IMigrationDo { - return m.withDO(m.DO.Join(table, on...)) -} - -func (m migrationDo) LeftJoin(table schema.Tabler, on ...field.Expr) IMigrationDo { - return m.withDO(m.DO.LeftJoin(table, on...)) -} - -func (m migrationDo) RightJoin(table schema.Tabler, on ...field.Expr) IMigrationDo { - return m.withDO(m.DO.RightJoin(table, on...)) -} - -func (m migrationDo) Group(cols ...field.Expr) IMigrationDo { - return m.withDO(m.DO.Group(cols...)) -} - -func (m migrationDo) Having(conds ...gen.Condition) IMigrationDo { - return m.withDO(m.DO.Having(conds...)) -} - -func (m migrationDo) Limit(limit int) IMigrationDo { - return m.withDO(m.DO.Limit(limit)) -} - -func (m migrationDo) Offset(offset int) IMigrationDo { - return m.withDO(m.DO.Offset(offset)) -} - -func (m migrationDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IMigrationDo { - return m.withDO(m.DO.Scopes(funcs...)) -} - -func (m migrationDo) Unscoped() IMigrationDo { - return m.withDO(m.DO.Unscoped()) -} - -func (m migrationDo) Create(values ...*models.Migration) error { - if len(values) == 0 { - return nil - } - return m.DO.Create(values) -} - -func (m migrationDo) CreateInBatches(values []*models.Migration, batchSize int) error { - return m.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (m migrationDo) Save(values ...*models.Migration) error { - if len(values) == 0 { - return nil - } - return m.DO.Save(values) -} - -func (m migrationDo) First() (*models.Migration, error) { - if result, err := m.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.Migration), nil - } -} - -func (m migrationDo) Take() (*models.Migration, error) { - if result, err := m.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.Migration), nil - } -} - -func (m migrationDo) Last() (*models.Migration, error) { - if result, err := m.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.Migration), nil - } -} - -func (m migrationDo) Find() ([]*models.Migration, error) { - result, err := m.DO.Find() - return result.([]*models.Migration), err -} - -func (m migrationDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Migration, err error) { - buf := make([]*models.Migration, 0, batchSize) - err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (m migrationDo) FindInBatches(result *[]*models.Migration, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return m.DO.FindInBatches(result, batchSize, fc) -} - -func (m migrationDo) Attrs(attrs ...field.AssignExpr) IMigrationDo { - return m.withDO(m.DO.Attrs(attrs...)) -} - -func (m migrationDo) Assign(attrs ...field.AssignExpr) IMigrationDo { - return m.withDO(m.DO.Assign(attrs...)) -} - -func (m migrationDo) Joins(fields ...field.RelationField) IMigrationDo { - for _, _f := range fields { - m = *m.withDO(m.DO.Joins(_f)) - } - return &m -} - -func (m migrationDo) Preload(fields ...field.RelationField) IMigrationDo { - for _, _f := range fields { - m = *m.withDO(m.DO.Preload(_f)) - } - return &m -} - -func (m migrationDo) FirstOrInit() (*models.Migration, error) { - if result, err := m.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.Migration), nil - } -} - -func (m migrationDo) FirstOrCreate() (*models.Migration, error) { - if result, err := m.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.Migration), nil - } -} - -func (m migrationDo) FindByPage(offset int, limit int) (result []*models.Migration, count int64, err error) { - result, err = m.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = m.Offset(-1).Limit(-1).Count() - return -} - -func (m migrationDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = m.Count() - if err != nil { - return - } - - err = m.Offset(offset).Limit(limit).Scan(result) - return -} - -func (m migrationDo) Scan(result interface{}) (err error) { - return m.DO.Scan(result) -} - -func (m migrationDo) Delete(models ...*models.Migration) (result gen.ResultInfo, err error) { - return m.DO.Delete(models) -} - -func (m *migrationDo) withDO(do gen.Dao) *migrationDo { - m.DO = *do.(*gen.DO) - return m -} diff --git a/database/query/query.gen.go b/database/query/query.gen.go deleted file mode 100644 index 3d64d42..0000000 --- a/database/query/query.gen.go +++ /dev/null @@ -1,163 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - "database/sql" - - "gorm.io/gorm" - - "gorm.io/gen" - - "gorm.io/plugin/dbresolver" -) - -var ( - Q = new(Query) - CasbinRule *casbinRule - Migration *migration - SysAPI *sysAPI - SysDictionary *sysDictionary - SysDictionaryDetail *sysDictionaryDetail - SysOperationRecord *sysOperationRecord - SysRole *sysRole - User *user - UserRole *userRole -) - -func SetDefault(db *gorm.DB, opts ...gen.DOOption) { - *Q = *Use(db, opts...) - CasbinRule = &Q.CasbinRule - Migration = &Q.Migration - SysAPI = &Q.SysAPI - SysDictionary = &Q.SysDictionary - SysDictionaryDetail = &Q.SysDictionaryDetail - SysOperationRecord = &Q.SysOperationRecord - SysRole = &Q.SysRole - User = &Q.User - UserRole = &Q.UserRole -} - -func Use(db *gorm.DB, opts ...gen.DOOption) *Query { - return &Query{ - db: db, - CasbinRule: newCasbinRule(db, opts...), - Migration: newMigration(db, opts...), - SysAPI: newSysAPI(db, opts...), - SysDictionary: newSysDictionary(db, opts...), - SysDictionaryDetail: newSysDictionaryDetail(db, opts...), - SysOperationRecord: newSysOperationRecord(db, opts...), - SysRole: newSysRole(db, opts...), - User: newUser(db, opts...), - UserRole: newUserRole(db, opts...), - } -} - -type Query struct { - db *gorm.DB - - CasbinRule casbinRule - Migration migration - SysAPI sysAPI - SysDictionary sysDictionary - SysDictionaryDetail sysDictionaryDetail - SysOperationRecord sysOperationRecord - SysRole sysRole - User user - UserRole userRole -} - -func (q *Query) Available() bool { return q.db != nil } - -func (q *Query) clone(db *gorm.DB) *Query { - return &Query{ - db: db, - CasbinRule: q.CasbinRule.clone(db), - Migration: q.Migration.clone(db), - SysAPI: q.SysAPI.clone(db), - SysDictionary: q.SysDictionary.clone(db), - SysDictionaryDetail: q.SysDictionaryDetail.clone(db), - SysOperationRecord: q.SysOperationRecord.clone(db), - SysRole: q.SysRole.clone(db), - User: q.User.clone(db), - UserRole: q.UserRole.clone(db), - } -} - -func (q *Query) ReadDB() *Query { - return q.clone(q.db.Clauses(dbresolver.Read)) -} - -func (q *Query) WriteDB() *Query { - return q.clone(q.db.Clauses(dbresolver.Write)) -} - -func (q *Query) ReplaceDB(db *gorm.DB) *Query { - return &Query{ - db: db, - CasbinRule: q.CasbinRule.replaceDB(db), - Migration: q.Migration.replaceDB(db), - SysAPI: q.SysAPI.replaceDB(db), - SysDictionary: q.SysDictionary.replaceDB(db), - SysDictionaryDetail: q.SysDictionaryDetail.replaceDB(db), - SysOperationRecord: q.SysOperationRecord.replaceDB(db), - SysRole: q.SysRole.replaceDB(db), - User: q.User.replaceDB(db), - UserRole: q.UserRole.replaceDB(db), - } -} - -type queryCtx struct { - CasbinRule ICasbinRuleDo - Migration IMigrationDo - SysAPI ISysAPIDo - SysDictionary ISysDictionaryDo - SysDictionaryDetail ISysDictionaryDetailDo - SysOperationRecord ISysOperationRecordDo - SysRole ISysRoleDo - User IUserDo - UserRole IUserRoleDo -} - -func (q *Query) WithContext(ctx context.Context) *queryCtx { - return &queryCtx{ - CasbinRule: q.CasbinRule.WithContext(ctx), - Migration: q.Migration.WithContext(ctx), - SysAPI: q.SysAPI.WithContext(ctx), - SysDictionary: q.SysDictionary.WithContext(ctx), - SysDictionaryDetail: q.SysDictionaryDetail.WithContext(ctx), - SysOperationRecord: q.SysOperationRecord.WithContext(ctx), - SysRole: q.SysRole.WithContext(ctx), - User: q.User.WithContext(ctx), - UserRole: q.UserRole.WithContext(ctx), - } -} - -func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error { - return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...) -} - -func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx { - return &QueryTx{q.clone(q.db.Begin(opts...))} -} - -type QueryTx struct{ *Query } - -func (q *QueryTx) Commit() error { - return q.db.Commit().Error -} - -func (q *QueryTx) Rollback() error { - return q.db.Rollback().Error -} - -func (q *QueryTx) SavePoint(name string) error { - return q.db.SavePoint(name).Error -} - -func (q *QueryTx) RollbackTo(name string) error { - return q.db.RollbackTo(name).Error -} diff --git a/database/query/sys_apis.gen.go b/database/query/sys_apis.gen.go deleted file mode 100644 index f151799..0000000 --- a/database/query/sys_apis.gen.go +++ /dev/null @@ -1,418 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newSysAPI(db *gorm.DB, opts ...gen.DOOption) sysAPI { - _sysAPI := sysAPI{} - - _sysAPI.sysAPIDo.UseDB(db, opts...) - _sysAPI.sysAPIDo.UseModel(&models.SysAPI{}) - - tableName := _sysAPI.sysAPIDo.TableName() - _sysAPI.ALL = field.NewAsterisk(tableName) - _sysAPI.ID = field.NewUint64(tableName, "id") - _sysAPI.CreatedAt = field.NewTime(tableName, "created_at") - _sysAPI.UpdatedAt = field.NewTime(tableName, "updated_at") - _sysAPI.DeletedAt = field.NewField(tableName, "deleted_at") - _sysAPI.Path = field.NewString(tableName, "path") - _sysAPI.Description = field.NewString(tableName, "description") - _sysAPI.APIGroup = field.NewString(tableName, "api_group") - _sysAPI.Method = field.NewString(tableName, "method") - - _sysAPI.fillFieldMap() - - return _sysAPI -} - -type sysAPI struct { - sysAPIDo sysAPIDo - - ALL field.Asterisk - ID field.Uint64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Path field.String // 路径 - Description field.String // 中文描述 - APIGroup field.String // 组 - Method field.String // 方法 - - fieldMap map[string]field.Expr -} - -func (s sysAPI) Table(newTableName string) *sysAPI { - s.sysAPIDo.UseTable(newTableName) - return s.updateTableName(newTableName) -} - -func (s sysAPI) As(alias string) *sysAPI { - s.sysAPIDo.DO = *(s.sysAPIDo.As(alias).(*gen.DO)) - return s.updateTableName(alias) -} - -func (s *sysAPI) updateTableName(table string) *sysAPI { - s.ALL = field.NewAsterisk(table) - s.ID = field.NewUint64(table, "id") - s.CreatedAt = field.NewTime(table, "created_at") - s.UpdatedAt = field.NewTime(table, "updated_at") - s.DeletedAt = field.NewField(table, "deleted_at") - s.Path = field.NewString(table, "path") - s.Description = field.NewString(table, "description") - s.APIGroup = field.NewString(table, "api_group") - s.Method = field.NewString(table, "method") - - s.fillFieldMap() - - return s -} - -func (s *sysAPI) WithContext(ctx context.Context) ISysAPIDo { return s.sysAPIDo.WithContext(ctx) } - -func (s sysAPI) TableName() string { return s.sysAPIDo.TableName() } - -func (s sysAPI) Alias() string { return s.sysAPIDo.Alias() } - -func (s *sysAPI) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := s.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (s *sysAPI) fillFieldMap() { - s.fieldMap = make(map[string]field.Expr, 8) - s.fieldMap["id"] = s.ID - s.fieldMap["created_at"] = s.CreatedAt - s.fieldMap["updated_at"] = s.UpdatedAt - s.fieldMap["deleted_at"] = s.DeletedAt - s.fieldMap["path"] = s.Path - s.fieldMap["description"] = s.Description - s.fieldMap["api_group"] = s.APIGroup - s.fieldMap["method"] = s.Method -} - -func (s sysAPI) clone(db *gorm.DB) sysAPI { - s.sysAPIDo.ReplaceConnPool(db.Statement.ConnPool) - return s -} - -func (s sysAPI) replaceDB(db *gorm.DB) sysAPI { - s.sysAPIDo.ReplaceDB(db) - return s -} - -type sysAPIDo struct{ gen.DO } - -type ISysAPIDo interface { - gen.SubQuery - Debug() ISysAPIDo - WithContext(ctx context.Context) ISysAPIDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ISysAPIDo - WriteDB() ISysAPIDo - As(alias string) gen.Dao - Session(config *gorm.Session) ISysAPIDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ISysAPIDo - Not(conds ...gen.Condition) ISysAPIDo - Or(conds ...gen.Condition) ISysAPIDo - Select(conds ...field.Expr) ISysAPIDo - Where(conds ...gen.Condition) ISysAPIDo - Order(conds ...field.Expr) ISysAPIDo - Distinct(cols ...field.Expr) ISysAPIDo - Omit(cols ...field.Expr) ISysAPIDo - Join(table schema.Tabler, on ...field.Expr) ISysAPIDo - LeftJoin(table schema.Tabler, on ...field.Expr) ISysAPIDo - RightJoin(table schema.Tabler, on ...field.Expr) ISysAPIDo - Group(cols ...field.Expr) ISysAPIDo - Having(conds ...gen.Condition) ISysAPIDo - Limit(limit int) ISysAPIDo - Offset(offset int) ISysAPIDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ISysAPIDo - Unscoped() ISysAPIDo - Create(values ...*models.SysAPI) error - CreateInBatches(values []*models.SysAPI, batchSize int) error - Save(values ...*models.SysAPI) error - First() (*models.SysAPI, error) - Take() (*models.SysAPI, error) - Last() (*models.SysAPI, error) - Find() ([]*models.SysAPI, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysAPI, err error) - FindInBatches(result *[]*models.SysAPI, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.SysAPI) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) ISysAPIDo - Assign(attrs ...field.AssignExpr) ISysAPIDo - Joins(fields ...field.RelationField) ISysAPIDo - Preload(fields ...field.RelationField) ISysAPIDo - FirstOrInit() (*models.SysAPI, error) - FirstOrCreate() (*models.SysAPI, error) - FindByPage(offset int, limit int) (result []*models.SysAPI, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) ISysAPIDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (s sysAPIDo) Debug() ISysAPIDo { - return s.withDO(s.DO.Debug()) -} - -func (s sysAPIDo) WithContext(ctx context.Context) ISysAPIDo { - return s.withDO(s.DO.WithContext(ctx)) -} - -func (s sysAPIDo) ReadDB() ISysAPIDo { - return s.Clauses(dbresolver.Read) -} - -func (s sysAPIDo) WriteDB() ISysAPIDo { - return s.Clauses(dbresolver.Write) -} - -func (s sysAPIDo) Session(config *gorm.Session) ISysAPIDo { - return s.withDO(s.DO.Session(config)) -} - -func (s sysAPIDo) Clauses(conds ...clause.Expression) ISysAPIDo { - return s.withDO(s.DO.Clauses(conds...)) -} - -func (s sysAPIDo) Returning(value interface{}, columns ...string) ISysAPIDo { - return s.withDO(s.DO.Returning(value, columns...)) -} - -func (s sysAPIDo) Not(conds ...gen.Condition) ISysAPIDo { - return s.withDO(s.DO.Not(conds...)) -} - -func (s sysAPIDo) Or(conds ...gen.Condition) ISysAPIDo { - return s.withDO(s.DO.Or(conds...)) -} - -func (s sysAPIDo) Select(conds ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.Select(conds...)) -} - -func (s sysAPIDo) Where(conds ...gen.Condition) ISysAPIDo { - return s.withDO(s.DO.Where(conds...)) -} - -func (s sysAPIDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ISysAPIDo { - return s.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (s sysAPIDo) Order(conds ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.Order(conds...)) -} - -func (s sysAPIDo) Distinct(cols ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.Distinct(cols...)) -} - -func (s sysAPIDo) Omit(cols ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.Omit(cols...)) -} - -func (s sysAPIDo) Join(table schema.Tabler, on ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.Join(table, on...)) -} - -func (s sysAPIDo) LeftJoin(table schema.Tabler, on ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.LeftJoin(table, on...)) -} - -func (s sysAPIDo) RightJoin(table schema.Tabler, on ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.RightJoin(table, on...)) -} - -func (s sysAPIDo) Group(cols ...field.Expr) ISysAPIDo { - return s.withDO(s.DO.Group(cols...)) -} - -func (s sysAPIDo) Having(conds ...gen.Condition) ISysAPIDo { - return s.withDO(s.DO.Having(conds...)) -} - -func (s sysAPIDo) Limit(limit int) ISysAPIDo { - return s.withDO(s.DO.Limit(limit)) -} - -func (s sysAPIDo) Offset(offset int) ISysAPIDo { - return s.withDO(s.DO.Offset(offset)) -} - -func (s sysAPIDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ISysAPIDo { - return s.withDO(s.DO.Scopes(funcs...)) -} - -func (s sysAPIDo) Unscoped() ISysAPIDo { - return s.withDO(s.DO.Unscoped()) -} - -func (s sysAPIDo) Create(values ...*models.SysAPI) error { - if len(values) == 0 { - return nil - } - return s.DO.Create(values) -} - -func (s sysAPIDo) CreateInBatches(values []*models.SysAPI, batchSize int) error { - return s.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (s sysAPIDo) Save(values ...*models.SysAPI) error { - if len(values) == 0 { - return nil - } - return s.DO.Save(values) -} - -func (s sysAPIDo) First() (*models.SysAPI, error) { - if result, err := s.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.SysAPI), nil - } -} - -func (s sysAPIDo) Take() (*models.SysAPI, error) { - if result, err := s.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.SysAPI), nil - } -} - -func (s sysAPIDo) Last() (*models.SysAPI, error) { - if result, err := s.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.SysAPI), nil - } -} - -func (s sysAPIDo) Find() ([]*models.SysAPI, error) { - result, err := s.DO.Find() - return result.([]*models.SysAPI), err -} - -func (s sysAPIDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysAPI, err error) { - buf := make([]*models.SysAPI, 0, batchSize) - err = s.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (s sysAPIDo) FindInBatches(result *[]*models.SysAPI, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return s.DO.FindInBatches(result, batchSize, fc) -} - -func (s sysAPIDo) Attrs(attrs ...field.AssignExpr) ISysAPIDo { - return s.withDO(s.DO.Attrs(attrs...)) -} - -func (s sysAPIDo) Assign(attrs ...field.AssignExpr) ISysAPIDo { - return s.withDO(s.DO.Assign(attrs...)) -} - -func (s sysAPIDo) Joins(fields ...field.RelationField) ISysAPIDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Joins(_f)) - } - return &s -} - -func (s sysAPIDo) Preload(fields ...field.RelationField) ISysAPIDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Preload(_f)) - } - return &s -} - -func (s sysAPIDo) FirstOrInit() (*models.SysAPI, error) { - if result, err := s.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.SysAPI), nil - } -} - -func (s sysAPIDo) FirstOrCreate() (*models.SysAPI, error) { - if result, err := s.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.SysAPI), nil - } -} - -func (s sysAPIDo) FindByPage(offset int, limit int) (result []*models.SysAPI, count int64, err error) { - result, err = s.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = s.Offset(-1).Limit(-1).Count() - return -} - -func (s sysAPIDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = s.Count() - if err != nil { - return - } - - err = s.Offset(offset).Limit(limit).Scan(result) - return -} - -func (s sysAPIDo) Scan(result interface{}) (err error) { - return s.DO.Scan(result) -} - -func (s sysAPIDo) Delete(models ...*models.SysAPI) (result gen.ResultInfo, err error) { - return s.DO.Delete(models) -} - -func (s *sysAPIDo) withDO(do gen.Dao) *sysAPIDo { - s.DO = *do.(*gen.DO) - return s -} diff --git a/database/query/sys_dictionaries.gen.go b/database/query/sys_dictionaries.gen.go deleted file mode 100644 index 59578f5..0000000 --- a/database/query/sys_dictionaries.gen.go +++ /dev/null @@ -1,420 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newSysDictionary(db *gorm.DB, opts ...gen.DOOption) sysDictionary { - _sysDictionary := sysDictionary{} - - _sysDictionary.sysDictionaryDo.UseDB(db, opts...) - _sysDictionary.sysDictionaryDo.UseModel(&models.SysDictionary{}) - - tableName := _sysDictionary.sysDictionaryDo.TableName() - _sysDictionary.ALL = field.NewAsterisk(tableName) - _sysDictionary.ID = field.NewUint64(tableName, "id") - _sysDictionary.CreatedAt = field.NewTime(tableName, "created_at") - _sysDictionary.UpdatedAt = field.NewTime(tableName, "updated_at") - _sysDictionary.DeletedAt = field.NewField(tableName, "deleted_at") - _sysDictionary.Name = field.NewString(tableName, "name") - _sysDictionary.Alias_ = field.NewString(tableName, "alias") - _sysDictionary.Status = field.NewBool(tableName, "status") - _sysDictionary.Description = field.NewString(tableName, "description") - - _sysDictionary.fillFieldMap() - - return _sysDictionary -} - -type sysDictionary struct { - sysDictionaryDo sysDictionaryDo - - ALL field.Asterisk - ID field.Uint64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Name field.String // 字典名(中) - Alias_ field.String // 字典名(英) - Status field.Bool // 状态 - Description field.String // 描述 - - fieldMap map[string]field.Expr -} - -func (s sysDictionary) Table(newTableName string) *sysDictionary { - s.sysDictionaryDo.UseTable(newTableName) - return s.updateTableName(newTableName) -} - -func (s sysDictionary) As(alias string) *sysDictionary { - s.sysDictionaryDo.DO = *(s.sysDictionaryDo.As(alias).(*gen.DO)) - return s.updateTableName(alias) -} - -func (s *sysDictionary) updateTableName(table string) *sysDictionary { - s.ALL = field.NewAsterisk(table) - s.ID = field.NewUint64(table, "id") - s.CreatedAt = field.NewTime(table, "created_at") - s.UpdatedAt = field.NewTime(table, "updated_at") - s.DeletedAt = field.NewField(table, "deleted_at") - s.Name = field.NewString(table, "name") - s.Alias_ = field.NewString(table, "alias") - s.Status = field.NewBool(table, "status") - s.Description = field.NewString(table, "description") - - s.fillFieldMap() - - return s -} - -func (s *sysDictionary) WithContext(ctx context.Context) ISysDictionaryDo { - return s.sysDictionaryDo.WithContext(ctx) -} - -func (s sysDictionary) TableName() string { return s.sysDictionaryDo.TableName() } - -func (s sysDictionary) Alias() string { return s.sysDictionaryDo.Alias() } - -func (s *sysDictionary) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := s.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (s *sysDictionary) fillFieldMap() { - s.fieldMap = make(map[string]field.Expr, 8) - s.fieldMap["id"] = s.ID - s.fieldMap["created_at"] = s.CreatedAt - s.fieldMap["updated_at"] = s.UpdatedAt - s.fieldMap["deleted_at"] = s.DeletedAt - s.fieldMap["name"] = s.Name - s.fieldMap["alias"] = s.Alias_ - s.fieldMap["status"] = s.Status - s.fieldMap["description"] = s.Description -} - -func (s sysDictionary) clone(db *gorm.DB) sysDictionary { - s.sysDictionaryDo.ReplaceConnPool(db.Statement.ConnPool) - return s -} - -func (s sysDictionary) replaceDB(db *gorm.DB) sysDictionary { - s.sysDictionaryDo.ReplaceDB(db) - return s -} - -type sysDictionaryDo struct{ gen.DO } - -type ISysDictionaryDo interface { - gen.SubQuery - Debug() ISysDictionaryDo - WithContext(ctx context.Context) ISysDictionaryDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ISysDictionaryDo - WriteDB() ISysDictionaryDo - As(alias string) gen.Dao - Session(config *gorm.Session) ISysDictionaryDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ISysDictionaryDo - Not(conds ...gen.Condition) ISysDictionaryDo - Or(conds ...gen.Condition) ISysDictionaryDo - Select(conds ...field.Expr) ISysDictionaryDo - Where(conds ...gen.Condition) ISysDictionaryDo - Order(conds ...field.Expr) ISysDictionaryDo - Distinct(cols ...field.Expr) ISysDictionaryDo - Omit(cols ...field.Expr) ISysDictionaryDo - Join(table schema.Tabler, on ...field.Expr) ISysDictionaryDo - LeftJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDo - RightJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDo - Group(cols ...field.Expr) ISysDictionaryDo - Having(conds ...gen.Condition) ISysDictionaryDo - Limit(limit int) ISysDictionaryDo - Offset(offset int) ISysDictionaryDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ISysDictionaryDo - Unscoped() ISysDictionaryDo - Create(values ...*models.SysDictionary) error - CreateInBatches(values []*models.SysDictionary, batchSize int) error - Save(values ...*models.SysDictionary) error - First() (*models.SysDictionary, error) - Take() (*models.SysDictionary, error) - Last() (*models.SysDictionary, error) - Find() ([]*models.SysDictionary, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysDictionary, err error) - FindInBatches(result *[]*models.SysDictionary, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.SysDictionary) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) ISysDictionaryDo - Assign(attrs ...field.AssignExpr) ISysDictionaryDo - Joins(fields ...field.RelationField) ISysDictionaryDo - Preload(fields ...field.RelationField) ISysDictionaryDo - FirstOrInit() (*models.SysDictionary, error) - FirstOrCreate() (*models.SysDictionary, error) - FindByPage(offset int, limit int) (result []*models.SysDictionary, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) ISysDictionaryDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (s sysDictionaryDo) Debug() ISysDictionaryDo { - return s.withDO(s.DO.Debug()) -} - -func (s sysDictionaryDo) WithContext(ctx context.Context) ISysDictionaryDo { - return s.withDO(s.DO.WithContext(ctx)) -} - -func (s sysDictionaryDo) ReadDB() ISysDictionaryDo { - return s.Clauses(dbresolver.Read) -} - -func (s sysDictionaryDo) WriteDB() ISysDictionaryDo { - return s.Clauses(dbresolver.Write) -} - -func (s sysDictionaryDo) Session(config *gorm.Session) ISysDictionaryDo { - return s.withDO(s.DO.Session(config)) -} - -func (s sysDictionaryDo) Clauses(conds ...clause.Expression) ISysDictionaryDo { - return s.withDO(s.DO.Clauses(conds...)) -} - -func (s sysDictionaryDo) Returning(value interface{}, columns ...string) ISysDictionaryDo { - return s.withDO(s.DO.Returning(value, columns...)) -} - -func (s sysDictionaryDo) Not(conds ...gen.Condition) ISysDictionaryDo { - return s.withDO(s.DO.Not(conds...)) -} - -func (s sysDictionaryDo) Or(conds ...gen.Condition) ISysDictionaryDo { - return s.withDO(s.DO.Or(conds...)) -} - -func (s sysDictionaryDo) Select(conds ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.Select(conds...)) -} - -func (s sysDictionaryDo) Where(conds ...gen.Condition) ISysDictionaryDo { - return s.withDO(s.DO.Where(conds...)) -} - -func (s sysDictionaryDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ISysDictionaryDo { - return s.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (s sysDictionaryDo) Order(conds ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.Order(conds...)) -} - -func (s sysDictionaryDo) Distinct(cols ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.Distinct(cols...)) -} - -func (s sysDictionaryDo) Omit(cols ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.Omit(cols...)) -} - -func (s sysDictionaryDo) Join(table schema.Tabler, on ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.Join(table, on...)) -} - -func (s sysDictionaryDo) LeftJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.LeftJoin(table, on...)) -} - -func (s sysDictionaryDo) RightJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.RightJoin(table, on...)) -} - -func (s sysDictionaryDo) Group(cols ...field.Expr) ISysDictionaryDo { - return s.withDO(s.DO.Group(cols...)) -} - -func (s sysDictionaryDo) Having(conds ...gen.Condition) ISysDictionaryDo { - return s.withDO(s.DO.Having(conds...)) -} - -func (s sysDictionaryDo) Limit(limit int) ISysDictionaryDo { - return s.withDO(s.DO.Limit(limit)) -} - -func (s sysDictionaryDo) Offset(offset int) ISysDictionaryDo { - return s.withDO(s.DO.Offset(offset)) -} - -func (s sysDictionaryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ISysDictionaryDo { - return s.withDO(s.DO.Scopes(funcs...)) -} - -func (s sysDictionaryDo) Unscoped() ISysDictionaryDo { - return s.withDO(s.DO.Unscoped()) -} - -func (s sysDictionaryDo) Create(values ...*models.SysDictionary) error { - if len(values) == 0 { - return nil - } - return s.DO.Create(values) -} - -func (s sysDictionaryDo) CreateInBatches(values []*models.SysDictionary, batchSize int) error { - return s.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (s sysDictionaryDo) Save(values ...*models.SysDictionary) error { - if len(values) == 0 { - return nil - } - return s.DO.Save(values) -} - -func (s sysDictionaryDo) First() (*models.SysDictionary, error) { - if result, err := s.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionary), nil - } -} - -func (s sysDictionaryDo) Take() (*models.SysDictionary, error) { - if result, err := s.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionary), nil - } -} - -func (s sysDictionaryDo) Last() (*models.SysDictionary, error) { - if result, err := s.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionary), nil - } -} - -func (s sysDictionaryDo) Find() ([]*models.SysDictionary, error) { - result, err := s.DO.Find() - return result.([]*models.SysDictionary), err -} - -func (s sysDictionaryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysDictionary, err error) { - buf := make([]*models.SysDictionary, 0, batchSize) - err = s.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (s sysDictionaryDo) FindInBatches(result *[]*models.SysDictionary, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return s.DO.FindInBatches(result, batchSize, fc) -} - -func (s sysDictionaryDo) Attrs(attrs ...field.AssignExpr) ISysDictionaryDo { - return s.withDO(s.DO.Attrs(attrs...)) -} - -func (s sysDictionaryDo) Assign(attrs ...field.AssignExpr) ISysDictionaryDo { - return s.withDO(s.DO.Assign(attrs...)) -} - -func (s sysDictionaryDo) Joins(fields ...field.RelationField) ISysDictionaryDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Joins(_f)) - } - return &s -} - -func (s sysDictionaryDo) Preload(fields ...field.RelationField) ISysDictionaryDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Preload(_f)) - } - return &s -} - -func (s sysDictionaryDo) FirstOrInit() (*models.SysDictionary, error) { - if result, err := s.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionary), nil - } -} - -func (s sysDictionaryDo) FirstOrCreate() (*models.SysDictionary, error) { - if result, err := s.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionary), nil - } -} - -func (s sysDictionaryDo) FindByPage(offset int, limit int) (result []*models.SysDictionary, count int64, err error) { - result, err = s.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = s.Offset(-1).Limit(-1).Count() - return -} - -func (s sysDictionaryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = s.Count() - if err != nil { - return - } - - err = s.Offset(offset).Limit(limit).Scan(result) - return -} - -func (s sysDictionaryDo) Scan(result interface{}) (err error) { - return s.DO.Scan(result) -} - -func (s sysDictionaryDo) Delete(models ...*models.SysDictionary) (result gen.ResultInfo, err error) { - return s.DO.Delete(models) -} - -func (s *sysDictionaryDo) withDO(do gen.Dao) *sysDictionaryDo { - s.DO = *do.(*gen.DO) - return s -} diff --git a/database/query/sys_dictionary_details.gen.go b/database/query/sys_dictionary_details.gen.go deleted file mode 100644 index c3ebda8..0000000 --- a/database/query/sys_dictionary_details.gen.go +++ /dev/null @@ -1,424 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newSysDictionaryDetail(db *gorm.DB, opts ...gen.DOOption) sysDictionaryDetail { - _sysDictionaryDetail := sysDictionaryDetail{} - - _sysDictionaryDetail.sysDictionaryDetailDo.UseDB(db, opts...) - _sysDictionaryDetail.sysDictionaryDetailDo.UseModel(&models.SysDictionaryDetail{}) - - tableName := _sysDictionaryDetail.sysDictionaryDetailDo.TableName() - _sysDictionaryDetail.ALL = field.NewAsterisk(tableName) - _sysDictionaryDetail.ID = field.NewUint64(tableName, "id") - _sysDictionaryDetail.CreatedAt = field.NewTime(tableName, "created_at") - _sysDictionaryDetail.UpdatedAt = field.NewTime(tableName, "updated_at") - _sysDictionaryDetail.DeletedAt = field.NewField(tableName, "deleted_at") - _sysDictionaryDetail.SysDictionaryID = field.NewInt64(tableName, "sys_dictionary_id") - _sysDictionaryDetail.Label = field.NewString(tableName, "label") - _sysDictionaryDetail.Value = field.NewString(tableName, "value") - _sysDictionaryDetail.Status = field.NewBool(tableName, "status") - _sysDictionaryDetail.Weight = field.NewInt64(tableName, "weight") - - _sysDictionaryDetail.fillFieldMap() - - return _sysDictionaryDetail -} - -type sysDictionaryDetail struct { - sysDictionaryDetailDo sysDictionaryDetailDo - - ALL field.Asterisk - ID field.Uint64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - SysDictionaryID field.Int64 // 关联标记 - Label field.String // 展示值 - Value field.String // 字典值 - Status field.Bool // 启用状态 - Weight field.Int64 // 排序权重 - - fieldMap map[string]field.Expr -} - -func (s sysDictionaryDetail) Table(newTableName string) *sysDictionaryDetail { - s.sysDictionaryDetailDo.UseTable(newTableName) - return s.updateTableName(newTableName) -} - -func (s sysDictionaryDetail) As(alias string) *sysDictionaryDetail { - s.sysDictionaryDetailDo.DO = *(s.sysDictionaryDetailDo.As(alias).(*gen.DO)) - return s.updateTableName(alias) -} - -func (s *sysDictionaryDetail) updateTableName(table string) *sysDictionaryDetail { - s.ALL = field.NewAsterisk(table) - s.ID = field.NewUint64(table, "id") - s.CreatedAt = field.NewTime(table, "created_at") - s.UpdatedAt = field.NewTime(table, "updated_at") - s.DeletedAt = field.NewField(table, "deleted_at") - s.SysDictionaryID = field.NewInt64(table, "sys_dictionary_id") - s.Label = field.NewString(table, "label") - s.Value = field.NewString(table, "value") - s.Status = field.NewBool(table, "status") - s.Weight = field.NewInt64(table, "weight") - - s.fillFieldMap() - - return s -} - -func (s *sysDictionaryDetail) WithContext(ctx context.Context) ISysDictionaryDetailDo { - return s.sysDictionaryDetailDo.WithContext(ctx) -} - -func (s sysDictionaryDetail) TableName() string { return s.sysDictionaryDetailDo.TableName() } - -func (s sysDictionaryDetail) Alias() string { return s.sysDictionaryDetailDo.Alias() } - -func (s *sysDictionaryDetail) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := s.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (s *sysDictionaryDetail) fillFieldMap() { - s.fieldMap = make(map[string]field.Expr, 9) - s.fieldMap["id"] = s.ID - s.fieldMap["created_at"] = s.CreatedAt - s.fieldMap["updated_at"] = s.UpdatedAt - s.fieldMap["deleted_at"] = s.DeletedAt - s.fieldMap["sys_dictionary_id"] = s.SysDictionaryID - s.fieldMap["label"] = s.Label - s.fieldMap["value"] = s.Value - s.fieldMap["status"] = s.Status - s.fieldMap["weight"] = s.Weight -} - -func (s sysDictionaryDetail) clone(db *gorm.DB) sysDictionaryDetail { - s.sysDictionaryDetailDo.ReplaceConnPool(db.Statement.ConnPool) - return s -} - -func (s sysDictionaryDetail) replaceDB(db *gorm.DB) sysDictionaryDetail { - s.sysDictionaryDetailDo.ReplaceDB(db) - return s -} - -type sysDictionaryDetailDo struct{ gen.DO } - -type ISysDictionaryDetailDo interface { - gen.SubQuery - Debug() ISysDictionaryDetailDo - WithContext(ctx context.Context) ISysDictionaryDetailDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ISysDictionaryDetailDo - WriteDB() ISysDictionaryDetailDo - As(alias string) gen.Dao - Session(config *gorm.Session) ISysDictionaryDetailDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ISysDictionaryDetailDo - Not(conds ...gen.Condition) ISysDictionaryDetailDo - Or(conds ...gen.Condition) ISysDictionaryDetailDo - Select(conds ...field.Expr) ISysDictionaryDetailDo - Where(conds ...gen.Condition) ISysDictionaryDetailDo - Order(conds ...field.Expr) ISysDictionaryDetailDo - Distinct(cols ...field.Expr) ISysDictionaryDetailDo - Omit(cols ...field.Expr) ISysDictionaryDetailDo - Join(table schema.Tabler, on ...field.Expr) ISysDictionaryDetailDo - LeftJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDetailDo - RightJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDetailDo - Group(cols ...field.Expr) ISysDictionaryDetailDo - Having(conds ...gen.Condition) ISysDictionaryDetailDo - Limit(limit int) ISysDictionaryDetailDo - Offset(offset int) ISysDictionaryDetailDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ISysDictionaryDetailDo - Unscoped() ISysDictionaryDetailDo - Create(values ...*models.SysDictionaryDetail) error - CreateInBatches(values []*models.SysDictionaryDetail, batchSize int) error - Save(values ...*models.SysDictionaryDetail) error - First() (*models.SysDictionaryDetail, error) - Take() (*models.SysDictionaryDetail, error) - Last() (*models.SysDictionaryDetail, error) - Find() ([]*models.SysDictionaryDetail, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysDictionaryDetail, err error) - FindInBatches(result *[]*models.SysDictionaryDetail, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.SysDictionaryDetail) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) ISysDictionaryDetailDo - Assign(attrs ...field.AssignExpr) ISysDictionaryDetailDo - Joins(fields ...field.RelationField) ISysDictionaryDetailDo - Preload(fields ...field.RelationField) ISysDictionaryDetailDo - FirstOrInit() (*models.SysDictionaryDetail, error) - FirstOrCreate() (*models.SysDictionaryDetail, error) - FindByPage(offset int, limit int) (result []*models.SysDictionaryDetail, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) ISysDictionaryDetailDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (s sysDictionaryDetailDo) Debug() ISysDictionaryDetailDo { - return s.withDO(s.DO.Debug()) -} - -func (s sysDictionaryDetailDo) WithContext(ctx context.Context) ISysDictionaryDetailDo { - return s.withDO(s.DO.WithContext(ctx)) -} - -func (s sysDictionaryDetailDo) ReadDB() ISysDictionaryDetailDo { - return s.Clauses(dbresolver.Read) -} - -func (s sysDictionaryDetailDo) WriteDB() ISysDictionaryDetailDo { - return s.Clauses(dbresolver.Write) -} - -func (s sysDictionaryDetailDo) Session(config *gorm.Session) ISysDictionaryDetailDo { - return s.withDO(s.DO.Session(config)) -} - -func (s sysDictionaryDetailDo) Clauses(conds ...clause.Expression) ISysDictionaryDetailDo { - return s.withDO(s.DO.Clauses(conds...)) -} - -func (s sysDictionaryDetailDo) Returning(value interface{}, columns ...string) ISysDictionaryDetailDo { - return s.withDO(s.DO.Returning(value, columns...)) -} - -func (s sysDictionaryDetailDo) Not(conds ...gen.Condition) ISysDictionaryDetailDo { - return s.withDO(s.DO.Not(conds...)) -} - -func (s sysDictionaryDetailDo) Or(conds ...gen.Condition) ISysDictionaryDetailDo { - return s.withDO(s.DO.Or(conds...)) -} - -func (s sysDictionaryDetailDo) Select(conds ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Select(conds...)) -} - -func (s sysDictionaryDetailDo) Where(conds ...gen.Condition) ISysDictionaryDetailDo { - return s.withDO(s.DO.Where(conds...)) -} - -func (s sysDictionaryDetailDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ISysDictionaryDetailDo { - return s.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (s sysDictionaryDetailDo) Order(conds ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Order(conds...)) -} - -func (s sysDictionaryDetailDo) Distinct(cols ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Distinct(cols...)) -} - -func (s sysDictionaryDetailDo) Omit(cols ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Omit(cols...)) -} - -func (s sysDictionaryDetailDo) Join(table schema.Tabler, on ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Join(table, on...)) -} - -func (s sysDictionaryDetailDo) LeftJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.LeftJoin(table, on...)) -} - -func (s sysDictionaryDetailDo) RightJoin(table schema.Tabler, on ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.RightJoin(table, on...)) -} - -func (s sysDictionaryDetailDo) Group(cols ...field.Expr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Group(cols...)) -} - -func (s sysDictionaryDetailDo) Having(conds ...gen.Condition) ISysDictionaryDetailDo { - return s.withDO(s.DO.Having(conds...)) -} - -func (s sysDictionaryDetailDo) Limit(limit int) ISysDictionaryDetailDo { - return s.withDO(s.DO.Limit(limit)) -} - -func (s sysDictionaryDetailDo) Offset(offset int) ISysDictionaryDetailDo { - return s.withDO(s.DO.Offset(offset)) -} - -func (s sysDictionaryDetailDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ISysDictionaryDetailDo { - return s.withDO(s.DO.Scopes(funcs...)) -} - -func (s sysDictionaryDetailDo) Unscoped() ISysDictionaryDetailDo { - return s.withDO(s.DO.Unscoped()) -} - -func (s sysDictionaryDetailDo) Create(values ...*models.SysDictionaryDetail) error { - if len(values) == 0 { - return nil - } - return s.DO.Create(values) -} - -func (s sysDictionaryDetailDo) CreateInBatches(values []*models.SysDictionaryDetail, batchSize int) error { - return s.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (s sysDictionaryDetailDo) Save(values ...*models.SysDictionaryDetail) error { - if len(values) == 0 { - return nil - } - return s.DO.Save(values) -} - -func (s sysDictionaryDetailDo) First() (*models.SysDictionaryDetail, error) { - if result, err := s.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionaryDetail), nil - } -} - -func (s sysDictionaryDetailDo) Take() (*models.SysDictionaryDetail, error) { - if result, err := s.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionaryDetail), nil - } -} - -func (s sysDictionaryDetailDo) Last() (*models.SysDictionaryDetail, error) { - if result, err := s.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionaryDetail), nil - } -} - -func (s sysDictionaryDetailDo) Find() ([]*models.SysDictionaryDetail, error) { - result, err := s.DO.Find() - return result.([]*models.SysDictionaryDetail), err -} - -func (s sysDictionaryDetailDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysDictionaryDetail, err error) { - buf := make([]*models.SysDictionaryDetail, 0, batchSize) - err = s.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (s sysDictionaryDetailDo) FindInBatches(result *[]*models.SysDictionaryDetail, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return s.DO.FindInBatches(result, batchSize, fc) -} - -func (s sysDictionaryDetailDo) Attrs(attrs ...field.AssignExpr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Attrs(attrs...)) -} - -func (s sysDictionaryDetailDo) Assign(attrs ...field.AssignExpr) ISysDictionaryDetailDo { - return s.withDO(s.DO.Assign(attrs...)) -} - -func (s sysDictionaryDetailDo) Joins(fields ...field.RelationField) ISysDictionaryDetailDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Joins(_f)) - } - return &s -} - -func (s sysDictionaryDetailDo) Preload(fields ...field.RelationField) ISysDictionaryDetailDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Preload(_f)) - } - return &s -} - -func (s sysDictionaryDetailDo) FirstOrInit() (*models.SysDictionaryDetail, error) { - if result, err := s.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionaryDetail), nil - } -} - -func (s sysDictionaryDetailDo) FirstOrCreate() (*models.SysDictionaryDetail, error) { - if result, err := s.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.SysDictionaryDetail), nil - } -} - -func (s sysDictionaryDetailDo) FindByPage(offset int, limit int) (result []*models.SysDictionaryDetail, count int64, err error) { - result, err = s.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = s.Offset(-1).Limit(-1).Count() - return -} - -func (s sysDictionaryDetailDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = s.Count() - if err != nil { - return - } - - err = s.Offset(offset).Limit(limit).Scan(result) - return -} - -func (s sysDictionaryDetailDo) Scan(result interface{}) (err error) { - return s.DO.Scan(result) -} - -func (s sysDictionaryDetailDo) Delete(models ...*models.SysDictionaryDetail) (result gen.ResultInfo, err error) { - return s.DO.Delete(models) -} - -func (s *sysDictionaryDetailDo) withDO(do gen.Dao) *sysDictionaryDetailDo { - s.DO = *do.(*gen.DO) - return s -} diff --git a/database/query/sys_operation_records.gen.go b/database/query/sys_operation_records.gen.go deleted file mode 100644 index fd5eaff..0000000 --- a/database/query/sys_operation_records.gen.go +++ /dev/null @@ -1,444 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newSysOperationRecord(db *gorm.DB, opts ...gen.DOOption) sysOperationRecord { - _sysOperationRecord := sysOperationRecord{} - - _sysOperationRecord.sysOperationRecordDo.UseDB(db, opts...) - _sysOperationRecord.sysOperationRecordDo.UseModel(&models.SysOperationRecord{}) - - tableName := _sysOperationRecord.sysOperationRecordDo.TableName() - _sysOperationRecord.ALL = field.NewAsterisk(tableName) - _sysOperationRecord.ID = field.NewUint64(tableName, "id") - _sysOperationRecord.CreatedAt = field.NewTime(tableName, "created_at") - _sysOperationRecord.UpdatedAt = field.NewTime(tableName, "updated_at") - _sysOperationRecord.DeletedAt = field.NewField(tableName, "deleted_at") - _sysOperationRecord.IP = field.NewString(tableName, "ip") - _sysOperationRecord.Method = field.NewString(tableName, "method") - _sysOperationRecord.Path = field.NewString(tableName, "path") - _sysOperationRecord.Status = field.NewInt64(tableName, "status") - _sysOperationRecord.Latency = field.NewInt64(tableName, "latency") - _sysOperationRecord.Agent = field.NewString(tableName, "agent") - _sysOperationRecord.ErrorMessage = field.NewString(tableName, "error_message") - _sysOperationRecord.Body = field.NewString(tableName, "body") - _sysOperationRecord.Resp = field.NewString(tableName, "resp") - _sysOperationRecord.UserID = field.NewInt64(tableName, "user_id") - - _sysOperationRecord.fillFieldMap() - - return _sysOperationRecord -} - -type sysOperationRecord struct { - sysOperationRecordDo sysOperationRecordDo - - ALL field.Asterisk - ID field.Uint64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - IP field.String // 请求ip - Method field.String // 请求方法 - Path field.String // 请求路径 - Status field.Int64 // 请求状态 - Latency field.Int64 // 延迟 - Agent field.String // 代理 - ErrorMessage field.String // 错误信息 - Body field.String // 请求Body - Resp field.String // 响应Body - UserID field.Int64 // 用户id - - fieldMap map[string]field.Expr -} - -func (s sysOperationRecord) Table(newTableName string) *sysOperationRecord { - s.sysOperationRecordDo.UseTable(newTableName) - return s.updateTableName(newTableName) -} - -func (s sysOperationRecord) As(alias string) *sysOperationRecord { - s.sysOperationRecordDo.DO = *(s.sysOperationRecordDo.As(alias).(*gen.DO)) - return s.updateTableName(alias) -} - -func (s *sysOperationRecord) updateTableName(table string) *sysOperationRecord { - s.ALL = field.NewAsterisk(table) - s.ID = field.NewUint64(table, "id") - s.CreatedAt = field.NewTime(table, "created_at") - s.UpdatedAt = field.NewTime(table, "updated_at") - s.DeletedAt = field.NewField(table, "deleted_at") - s.IP = field.NewString(table, "ip") - s.Method = field.NewString(table, "method") - s.Path = field.NewString(table, "path") - s.Status = field.NewInt64(table, "status") - s.Latency = field.NewInt64(table, "latency") - s.Agent = field.NewString(table, "agent") - s.ErrorMessage = field.NewString(table, "error_message") - s.Body = field.NewString(table, "body") - s.Resp = field.NewString(table, "resp") - s.UserID = field.NewInt64(table, "user_id") - - s.fillFieldMap() - - return s -} - -func (s *sysOperationRecord) WithContext(ctx context.Context) ISysOperationRecordDo { - return s.sysOperationRecordDo.WithContext(ctx) -} - -func (s sysOperationRecord) TableName() string { return s.sysOperationRecordDo.TableName() } - -func (s sysOperationRecord) Alias() string { return s.sysOperationRecordDo.Alias() } - -func (s *sysOperationRecord) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := s.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (s *sysOperationRecord) fillFieldMap() { - s.fieldMap = make(map[string]field.Expr, 14) - s.fieldMap["id"] = s.ID - s.fieldMap["created_at"] = s.CreatedAt - s.fieldMap["updated_at"] = s.UpdatedAt - s.fieldMap["deleted_at"] = s.DeletedAt - s.fieldMap["ip"] = s.IP - s.fieldMap["method"] = s.Method - s.fieldMap["path"] = s.Path - s.fieldMap["status"] = s.Status - s.fieldMap["latency"] = s.Latency - s.fieldMap["agent"] = s.Agent - s.fieldMap["error_message"] = s.ErrorMessage - s.fieldMap["body"] = s.Body - s.fieldMap["resp"] = s.Resp - s.fieldMap["user_id"] = s.UserID -} - -func (s sysOperationRecord) clone(db *gorm.DB) sysOperationRecord { - s.sysOperationRecordDo.ReplaceConnPool(db.Statement.ConnPool) - return s -} - -func (s sysOperationRecord) replaceDB(db *gorm.DB) sysOperationRecord { - s.sysOperationRecordDo.ReplaceDB(db) - return s -} - -type sysOperationRecordDo struct{ gen.DO } - -type ISysOperationRecordDo interface { - gen.SubQuery - Debug() ISysOperationRecordDo - WithContext(ctx context.Context) ISysOperationRecordDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ISysOperationRecordDo - WriteDB() ISysOperationRecordDo - As(alias string) gen.Dao - Session(config *gorm.Session) ISysOperationRecordDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ISysOperationRecordDo - Not(conds ...gen.Condition) ISysOperationRecordDo - Or(conds ...gen.Condition) ISysOperationRecordDo - Select(conds ...field.Expr) ISysOperationRecordDo - Where(conds ...gen.Condition) ISysOperationRecordDo - Order(conds ...field.Expr) ISysOperationRecordDo - Distinct(cols ...field.Expr) ISysOperationRecordDo - Omit(cols ...field.Expr) ISysOperationRecordDo - Join(table schema.Tabler, on ...field.Expr) ISysOperationRecordDo - LeftJoin(table schema.Tabler, on ...field.Expr) ISysOperationRecordDo - RightJoin(table schema.Tabler, on ...field.Expr) ISysOperationRecordDo - Group(cols ...field.Expr) ISysOperationRecordDo - Having(conds ...gen.Condition) ISysOperationRecordDo - Limit(limit int) ISysOperationRecordDo - Offset(offset int) ISysOperationRecordDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ISysOperationRecordDo - Unscoped() ISysOperationRecordDo - Create(values ...*models.SysOperationRecord) error - CreateInBatches(values []*models.SysOperationRecord, batchSize int) error - Save(values ...*models.SysOperationRecord) error - First() (*models.SysOperationRecord, error) - Take() (*models.SysOperationRecord, error) - Last() (*models.SysOperationRecord, error) - Find() ([]*models.SysOperationRecord, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysOperationRecord, err error) - FindInBatches(result *[]*models.SysOperationRecord, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.SysOperationRecord) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) ISysOperationRecordDo - Assign(attrs ...field.AssignExpr) ISysOperationRecordDo - Joins(fields ...field.RelationField) ISysOperationRecordDo - Preload(fields ...field.RelationField) ISysOperationRecordDo - FirstOrInit() (*models.SysOperationRecord, error) - FirstOrCreate() (*models.SysOperationRecord, error) - FindByPage(offset int, limit int) (result []*models.SysOperationRecord, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) ISysOperationRecordDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (s sysOperationRecordDo) Debug() ISysOperationRecordDo { - return s.withDO(s.DO.Debug()) -} - -func (s sysOperationRecordDo) WithContext(ctx context.Context) ISysOperationRecordDo { - return s.withDO(s.DO.WithContext(ctx)) -} - -func (s sysOperationRecordDo) ReadDB() ISysOperationRecordDo { - return s.Clauses(dbresolver.Read) -} - -func (s sysOperationRecordDo) WriteDB() ISysOperationRecordDo { - return s.Clauses(dbresolver.Write) -} - -func (s sysOperationRecordDo) Session(config *gorm.Session) ISysOperationRecordDo { - return s.withDO(s.DO.Session(config)) -} - -func (s sysOperationRecordDo) Clauses(conds ...clause.Expression) ISysOperationRecordDo { - return s.withDO(s.DO.Clauses(conds...)) -} - -func (s sysOperationRecordDo) Returning(value interface{}, columns ...string) ISysOperationRecordDo { - return s.withDO(s.DO.Returning(value, columns...)) -} - -func (s sysOperationRecordDo) Not(conds ...gen.Condition) ISysOperationRecordDo { - return s.withDO(s.DO.Not(conds...)) -} - -func (s sysOperationRecordDo) Or(conds ...gen.Condition) ISysOperationRecordDo { - return s.withDO(s.DO.Or(conds...)) -} - -func (s sysOperationRecordDo) Select(conds ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.Select(conds...)) -} - -func (s sysOperationRecordDo) Where(conds ...gen.Condition) ISysOperationRecordDo { - return s.withDO(s.DO.Where(conds...)) -} - -func (s sysOperationRecordDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ISysOperationRecordDo { - return s.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (s sysOperationRecordDo) Order(conds ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.Order(conds...)) -} - -func (s sysOperationRecordDo) Distinct(cols ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.Distinct(cols...)) -} - -func (s sysOperationRecordDo) Omit(cols ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.Omit(cols...)) -} - -func (s sysOperationRecordDo) Join(table schema.Tabler, on ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.Join(table, on...)) -} - -func (s sysOperationRecordDo) LeftJoin(table schema.Tabler, on ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.LeftJoin(table, on...)) -} - -func (s sysOperationRecordDo) RightJoin(table schema.Tabler, on ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.RightJoin(table, on...)) -} - -func (s sysOperationRecordDo) Group(cols ...field.Expr) ISysOperationRecordDo { - return s.withDO(s.DO.Group(cols...)) -} - -func (s sysOperationRecordDo) Having(conds ...gen.Condition) ISysOperationRecordDo { - return s.withDO(s.DO.Having(conds...)) -} - -func (s sysOperationRecordDo) Limit(limit int) ISysOperationRecordDo { - return s.withDO(s.DO.Limit(limit)) -} - -func (s sysOperationRecordDo) Offset(offset int) ISysOperationRecordDo { - return s.withDO(s.DO.Offset(offset)) -} - -func (s sysOperationRecordDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ISysOperationRecordDo { - return s.withDO(s.DO.Scopes(funcs...)) -} - -func (s sysOperationRecordDo) Unscoped() ISysOperationRecordDo { - return s.withDO(s.DO.Unscoped()) -} - -func (s sysOperationRecordDo) Create(values ...*models.SysOperationRecord) error { - if len(values) == 0 { - return nil - } - return s.DO.Create(values) -} - -func (s sysOperationRecordDo) CreateInBatches(values []*models.SysOperationRecord, batchSize int) error { - return s.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (s sysOperationRecordDo) Save(values ...*models.SysOperationRecord) error { - if len(values) == 0 { - return nil - } - return s.DO.Save(values) -} - -func (s sysOperationRecordDo) First() (*models.SysOperationRecord, error) { - if result, err := s.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.SysOperationRecord), nil - } -} - -func (s sysOperationRecordDo) Take() (*models.SysOperationRecord, error) { - if result, err := s.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.SysOperationRecord), nil - } -} - -func (s sysOperationRecordDo) Last() (*models.SysOperationRecord, error) { - if result, err := s.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.SysOperationRecord), nil - } -} - -func (s sysOperationRecordDo) Find() ([]*models.SysOperationRecord, error) { - result, err := s.DO.Find() - return result.([]*models.SysOperationRecord), err -} - -func (s sysOperationRecordDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysOperationRecord, err error) { - buf := make([]*models.SysOperationRecord, 0, batchSize) - err = s.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (s sysOperationRecordDo) FindInBatches(result *[]*models.SysOperationRecord, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return s.DO.FindInBatches(result, batchSize, fc) -} - -func (s sysOperationRecordDo) Attrs(attrs ...field.AssignExpr) ISysOperationRecordDo { - return s.withDO(s.DO.Attrs(attrs...)) -} - -func (s sysOperationRecordDo) Assign(attrs ...field.AssignExpr) ISysOperationRecordDo { - return s.withDO(s.DO.Assign(attrs...)) -} - -func (s sysOperationRecordDo) Joins(fields ...field.RelationField) ISysOperationRecordDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Joins(_f)) - } - return &s -} - -func (s sysOperationRecordDo) Preload(fields ...field.RelationField) ISysOperationRecordDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Preload(_f)) - } - return &s -} - -func (s sysOperationRecordDo) FirstOrInit() (*models.SysOperationRecord, error) { - if result, err := s.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.SysOperationRecord), nil - } -} - -func (s sysOperationRecordDo) FirstOrCreate() (*models.SysOperationRecord, error) { - if result, err := s.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.SysOperationRecord), nil - } -} - -func (s sysOperationRecordDo) FindByPage(offset int, limit int) (result []*models.SysOperationRecord, count int64, err error) { - result, err = s.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = s.Offset(-1).Limit(-1).Count() - return -} - -func (s sysOperationRecordDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = s.Count() - if err != nil { - return - } - - err = s.Offset(offset).Limit(limit).Scan(result) - return -} - -func (s sysOperationRecordDo) Scan(result interface{}) (err error) { - return s.DO.Scan(result) -} - -func (s sysOperationRecordDo) Delete(models ...*models.SysOperationRecord) (result gen.ResultInfo, err error) { - return s.DO.Delete(models) -} - -func (s *sysOperationRecordDo) withDO(do gen.Dao) *sysOperationRecordDo { - s.DO = *do.(*gen.DO) - return s -} diff --git a/database/query/sys_roles.gen.go b/database/query/sys_roles.gen.go deleted file mode 100644 index 525c92c..0000000 --- a/database/query/sys_roles.gen.go +++ /dev/null @@ -1,418 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newSysRole(db *gorm.DB, opts ...gen.DOOption) sysRole { - _sysRole := sysRole{} - - _sysRole.sysRoleDo.UseDB(db, opts...) - _sysRole.sysRoleDo.UseModel(&models.SysRole{}) - - tableName := _sysRole.sysRoleDo.TableName() - _sysRole.ALL = field.NewAsterisk(tableName) - _sysRole.ID = field.NewUint64(tableName, "id") - _sysRole.CreatedAt = field.NewTime(tableName, "created_at") - _sysRole.UpdatedAt = field.NewTime(tableName, "updated_at") - _sysRole.DeletedAt = field.NewField(tableName, "deleted_at") - _sysRole.UUID = field.NewString(tableName, "uuid") - _sysRole.Name = field.NewString(tableName, "name") - _sysRole.ParentID = field.NewUint64(tableName, "parent_id") - _sysRole.DefaultRouter = field.NewString(tableName, "default_router") - - _sysRole.fillFieldMap() - - return _sysRole -} - -type sysRole struct { - sysRoleDo sysRoleDo - - ALL field.Asterisk - ID field.Uint64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - UUID field.String // 角色Alias - Name field.String // 角色名 - ParentID field.Uint64 // 父角色ID - DefaultRouter field.String // 默认菜单 - - fieldMap map[string]field.Expr -} - -func (s sysRole) Table(newTableName string) *sysRole { - s.sysRoleDo.UseTable(newTableName) - return s.updateTableName(newTableName) -} - -func (s sysRole) As(alias string) *sysRole { - s.sysRoleDo.DO = *(s.sysRoleDo.As(alias).(*gen.DO)) - return s.updateTableName(alias) -} - -func (s *sysRole) updateTableName(table string) *sysRole { - s.ALL = field.NewAsterisk(table) - s.ID = field.NewUint64(table, "id") - s.CreatedAt = field.NewTime(table, "created_at") - s.UpdatedAt = field.NewTime(table, "updated_at") - s.DeletedAt = field.NewField(table, "deleted_at") - s.UUID = field.NewString(table, "uuid") - s.Name = field.NewString(table, "name") - s.ParentID = field.NewUint64(table, "parent_id") - s.DefaultRouter = field.NewString(table, "default_router") - - s.fillFieldMap() - - return s -} - -func (s *sysRole) WithContext(ctx context.Context) ISysRoleDo { return s.sysRoleDo.WithContext(ctx) } - -func (s sysRole) TableName() string { return s.sysRoleDo.TableName() } - -func (s sysRole) Alias() string { return s.sysRoleDo.Alias() } - -func (s *sysRole) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := s.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (s *sysRole) fillFieldMap() { - s.fieldMap = make(map[string]field.Expr, 8) - s.fieldMap["id"] = s.ID - s.fieldMap["created_at"] = s.CreatedAt - s.fieldMap["updated_at"] = s.UpdatedAt - s.fieldMap["deleted_at"] = s.DeletedAt - s.fieldMap["uuid"] = s.UUID - s.fieldMap["name"] = s.Name - s.fieldMap["parent_id"] = s.ParentID - s.fieldMap["default_router"] = s.DefaultRouter -} - -func (s sysRole) clone(db *gorm.DB) sysRole { - s.sysRoleDo.ReplaceConnPool(db.Statement.ConnPool) - return s -} - -func (s sysRole) replaceDB(db *gorm.DB) sysRole { - s.sysRoleDo.ReplaceDB(db) - return s -} - -type sysRoleDo struct{ gen.DO } - -type ISysRoleDo interface { - gen.SubQuery - Debug() ISysRoleDo - WithContext(ctx context.Context) ISysRoleDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ISysRoleDo - WriteDB() ISysRoleDo - As(alias string) gen.Dao - Session(config *gorm.Session) ISysRoleDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ISysRoleDo - Not(conds ...gen.Condition) ISysRoleDo - Or(conds ...gen.Condition) ISysRoleDo - Select(conds ...field.Expr) ISysRoleDo - Where(conds ...gen.Condition) ISysRoleDo - Order(conds ...field.Expr) ISysRoleDo - Distinct(cols ...field.Expr) ISysRoleDo - Omit(cols ...field.Expr) ISysRoleDo - Join(table schema.Tabler, on ...field.Expr) ISysRoleDo - LeftJoin(table schema.Tabler, on ...field.Expr) ISysRoleDo - RightJoin(table schema.Tabler, on ...field.Expr) ISysRoleDo - Group(cols ...field.Expr) ISysRoleDo - Having(conds ...gen.Condition) ISysRoleDo - Limit(limit int) ISysRoleDo - Offset(offset int) ISysRoleDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ISysRoleDo - Unscoped() ISysRoleDo - Create(values ...*models.SysRole) error - CreateInBatches(values []*models.SysRole, batchSize int) error - Save(values ...*models.SysRole) error - First() (*models.SysRole, error) - Take() (*models.SysRole, error) - Last() (*models.SysRole, error) - Find() ([]*models.SysRole, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysRole, err error) - FindInBatches(result *[]*models.SysRole, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.SysRole) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) ISysRoleDo - Assign(attrs ...field.AssignExpr) ISysRoleDo - Joins(fields ...field.RelationField) ISysRoleDo - Preload(fields ...field.RelationField) ISysRoleDo - FirstOrInit() (*models.SysRole, error) - FirstOrCreate() (*models.SysRole, error) - FindByPage(offset int, limit int) (result []*models.SysRole, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) ISysRoleDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (s sysRoleDo) Debug() ISysRoleDo { - return s.withDO(s.DO.Debug()) -} - -func (s sysRoleDo) WithContext(ctx context.Context) ISysRoleDo { - return s.withDO(s.DO.WithContext(ctx)) -} - -func (s sysRoleDo) ReadDB() ISysRoleDo { - return s.Clauses(dbresolver.Read) -} - -func (s sysRoleDo) WriteDB() ISysRoleDo { - return s.Clauses(dbresolver.Write) -} - -func (s sysRoleDo) Session(config *gorm.Session) ISysRoleDo { - return s.withDO(s.DO.Session(config)) -} - -func (s sysRoleDo) Clauses(conds ...clause.Expression) ISysRoleDo { - return s.withDO(s.DO.Clauses(conds...)) -} - -func (s sysRoleDo) Returning(value interface{}, columns ...string) ISysRoleDo { - return s.withDO(s.DO.Returning(value, columns...)) -} - -func (s sysRoleDo) Not(conds ...gen.Condition) ISysRoleDo { - return s.withDO(s.DO.Not(conds...)) -} - -func (s sysRoleDo) Or(conds ...gen.Condition) ISysRoleDo { - return s.withDO(s.DO.Or(conds...)) -} - -func (s sysRoleDo) Select(conds ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.Select(conds...)) -} - -func (s sysRoleDo) Where(conds ...gen.Condition) ISysRoleDo { - return s.withDO(s.DO.Where(conds...)) -} - -func (s sysRoleDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) ISysRoleDo { - return s.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (s sysRoleDo) Order(conds ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.Order(conds...)) -} - -func (s sysRoleDo) Distinct(cols ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.Distinct(cols...)) -} - -func (s sysRoleDo) Omit(cols ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.Omit(cols...)) -} - -func (s sysRoleDo) Join(table schema.Tabler, on ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.Join(table, on...)) -} - -func (s sysRoleDo) LeftJoin(table schema.Tabler, on ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.LeftJoin(table, on...)) -} - -func (s sysRoleDo) RightJoin(table schema.Tabler, on ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.RightJoin(table, on...)) -} - -func (s sysRoleDo) Group(cols ...field.Expr) ISysRoleDo { - return s.withDO(s.DO.Group(cols...)) -} - -func (s sysRoleDo) Having(conds ...gen.Condition) ISysRoleDo { - return s.withDO(s.DO.Having(conds...)) -} - -func (s sysRoleDo) Limit(limit int) ISysRoleDo { - return s.withDO(s.DO.Limit(limit)) -} - -func (s sysRoleDo) Offset(offset int) ISysRoleDo { - return s.withDO(s.DO.Offset(offset)) -} - -func (s sysRoleDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ISysRoleDo { - return s.withDO(s.DO.Scopes(funcs...)) -} - -func (s sysRoleDo) Unscoped() ISysRoleDo { - return s.withDO(s.DO.Unscoped()) -} - -func (s sysRoleDo) Create(values ...*models.SysRole) error { - if len(values) == 0 { - return nil - } - return s.DO.Create(values) -} - -func (s sysRoleDo) CreateInBatches(values []*models.SysRole, batchSize int) error { - return s.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (s sysRoleDo) Save(values ...*models.SysRole) error { - if len(values) == 0 { - return nil - } - return s.DO.Save(values) -} - -func (s sysRoleDo) First() (*models.SysRole, error) { - if result, err := s.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.SysRole), nil - } -} - -func (s sysRoleDo) Take() (*models.SysRole, error) { - if result, err := s.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.SysRole), nil - } -} - -func (s sysRoleDo) Last() (*models.SysRole, error) { - if result, err := s.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.SysRole), nil - } -} - -func (s sysRoleDo) Find() ([]*models.SysRole, error) { - result, err := s.DO.Find() - return result.([]*models.SysRole), err -} - -func (s sysRoleDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.SysRole, err error) { - buf := make([]*models.SysRole, 0, batchSize) - err = s.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (s sysRoleDo) FindInBatches(result *[]*models.SysRole, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return s.DO.FindInBatches(result, batchSize, fc) -} - -func (s sysRoleDo) Attrs(attrs ...field.AssignExpr) ISysRoleDo { - return s.withDO(s.DO.Attrs(attrs...)) -} - -func (s sysRoleDo) Assign(attrs ...field.AssignExpr) ISysRoleDo { - return s.withDO(s.DO.Assign(attrs...)) -} - -func (s sysRoleDo) Joins(fields ...field.RelationField) ISysRoleDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Joins(_f)) - } - return &s -} - -func (s sysRoleDo) Preload(fields ...field.RelationField) ISysRoleDo { - for _, _f := range fields { - s = *s.withDO(s.DO.Preload(_f)) - } - return &s -} - -func (s sysRoleDo) FirstOrInit() (*models.SysRole, error) { - if result, err := s.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.SysRole), nil - } -} - -func (s sysRoleDo) FirstOrCreate() (*models.SysRole, error) { - if result, err := s.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.SysRole), nil - } -} - -func (s sysRoleDo) FindByPage(offset int, limit int) (result []*models.SysRole, count int64, err error) { - result, err = s.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = s.Offset(-1).Limit(-1).Count() - return -} - -func (s sysRoleDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = s.Count() - if err != nil { - return - } - - err = s.Offset(offset).Limit(limit).Scan(result) - return -} - -func (s sysRoleDo) Scan(result interface{}) (err error) { - return s.DO.Scan(result) -} - -func (s sysRoleDo) Delete(models ...*models.SysRole) (result gen.ResultInfo, err error) { - return s.DO.Delete(models) -} - -func (s *sysRoleDo) withDO(do gen.Dao) *sysRoleDo { - s.DO = *do.(*gen.DO) - return s -} diff --git a/database/query/user_roles.gen.go b/database/query/user_roles.gen.go deleted file mode 100644 index 21c8ac4..0000000 --- a/database/query/user_roles.gen.go +++ /dev/null @@ -1,394 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newUserRole(db *gorm.DB, opts ...gen.DOOption) userRole { - _userRole := userRole{} - - _userRole.userRoleDo.UseDB(db, opts...) - _userRole.userRoleDo.UseModel(&models.UserRole{}) - - tableName := _userRole.userRoleDo.TableName() - _userRole.ALL = field.NewAsterisk(tableName) - _userRole.UserID = field.NewUint64(tableName, "user_id") - _userRole.RoleID = field.NewUint64(tableName, "role_id") - - _userRole.fillFieldMap() - - return _userRole -} - -type userRole struct { - userRoleDo userRoleDo - - ALL field.Asterisk - UserID field.Uint64 - RoleID field.Uint64 - - fieldMap map[string]field.Expr -} - -func (u userRole) Table(newTableName string) *userRole { - u.userRoleDo.UseTable(newTableName) - return u.updateTableName(newTableName) -} - -func (u userRole) As(alias string) *userRole { - u.userRoleDo.DO = *(u.userRoleDo.As(alias).(*gen.DO)) - return u.updateTableName(alias) -} - -func (u *userRole) updateTableName(table string) *userRole { - u.ALL = field.NewAsterisk(table) - u.UserID = field.NewUint64(table, "user_id") - u.RoleID = field.NewUint64(table, "role_id") - - u.fillFieldMap() - - return u -} - -func (u *userRole) WithContext(ctx context.Context) IUserRoleDo { return u.userRoleDo.WithContext(ctx) } - -func (u userRole) TableName() string { return u.userRoleDo.TableName() } - -func (u userRole) Alias() string { return u.userRoleDo.Alias() } - -func (u *userRole) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := u.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (u *userRole) fillFieldMap() { - u.fieldMap = make(map[string]field.Expr, 2) - u.fieldMap["user_id"] = u.UserID - u.fieldMap["role_id"] = u.RoleID -} - -func (u userRole) clone(db *gorm.DB) userRole { - u.userRoleDo.ReplaceConnPool(db.Statement.ConnPool) - return u -} - -func (u userRole) replaceDB(db *gorm.DB) userRole { - u.userRoleDo.ReplaceDB(db) - return u -} - -type userRoleDo struct{ gen.DO } - -type IUserRoleDo interface { - gen.SubQuery - Debug() IUserRoleDo - WithContext(ctx context.Context) IUserRoleDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IUserRoleDo - WriteDB() IUserRoleDo - As(alias string) gen.Dao - Session(config *gorm.Session) IUserRoleDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IUserRoleDo - Not(conds ...gen.Condition) IUserRoleDo - Or(conds ...gen.Condition) IUserRoleDo - Select(conds ...field.Expr) IUserRoleDo - Where(conds ...gen.Condition) IUserRoleDo - Order(conds ...field.Expr) IUserRoleDo - Distinct(cols ...field.Expr) IUserRoleDo - Omit(cols ...field.Expr) IUserRoleDo - Join(table schema.Tabler, on ...field.Expr) IUserRoleDo - LeftJoin(table schema.Tabler, on ...field.Expr) IUserRoleDo - RightJoin(table schema.Tabler, on ...field.Expr) IUserRoleDo - Group(cols ...field.Expr) IUserRoleDo - Having(conds ...gen.Condition) IUserRoleDo - Limit(limit int) IUserRoleDo - Offset(offset int) IUserRoleDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IUserRoleDo - Unscoped() IUserRoleDo - Create(values ...*models.UserRole) error - CreateInBatches(values []*models.UserRole, batchSize int) error - Save(values ...*models.UserRole) error - First() (*models.UserRole, error) - Take() (*models.UserRole, error) - Last() (*models.UserRole, error) - Find() ([]*models.UserRole, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.UserRole, err error) - FindInBatches(result *[]*models.UserRole, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.UserRole) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) IUserRoleDo - Assign(attrs ...field.AssignExpr) IUserRoleDo - Joins(fields ...field.RelationField) IUserRoleDo - Preload(fields ...field.RelationField) IUserRoleDo - FirstOrInit() (*models.UserRole, error) - FirstOrCreate() (*models.UserRole, error) - FindByPage(offset int, limit int) (result []*models.UserRole, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) IUserRoleDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (u userRoleDo) Debug() IUserRoleDo { - return u.withDO(u.DO.Debug()) -} - -func (u userRoleDo) WithContext(ctx context.Context) IUserRoleDo { - return u.withDO(u.DO.WithContext(ctx)) -} - -func (u userRoleDo) ReadDB() IUserRoleDo { - return u.Clauses(dbresolver.Read) -} - -func (u userRoleDo) WriteDB() IUserRoleDo { - return u.Clauses(dbresolver.Write) -} - -func (u userRoleDo) Session(config *gorm.Session) IUserRoleDo { - return u.withDO(u.DO.Session(config)) -} - -func (u userRoleDo) Clauses(conds ...clause.Expression) IUserRoleDo { - return u.withDO(u.DO.Clauses(conds...)) -} - -func (u userRoleDo) Returning(value interface{}, columns ...string) IUserRoleDo { - return u.withDO(u.DO.Returning(value, columns...)) -} - -func (u userRoleDo) Not(conds ...gen.Condition) IUserRoleDo { - return u.withDO(u.DO.Not(conds...)) -} - -func (u userRoleDo) Or(conds ...gen.Condition) IUserRoleDo { - return u.withDO(u.DO.Or(conds...)) -} - -func (u userRoleDo) Select(conds ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.Select(conds...)) -} - -func (u userRoleDo) Where(conds ...gen.Condition) IUserRoleDo { - return u.withDO(u.DO.Where(conds...)) -} - -func (u userRoleDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) IUserRoleDo { - return u.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (u userRoleDo) Order(conds ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.Order(conds...)) -} - -func (u userRoleDo) Distinct(cols ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.Distinct(cols...)) -} - -func (u userRoleDo) Omit(cols ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.Omit(cols...)) -} - -func (u userRoleDo) Join(table schema.Tabler, on ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.Join(table, on...)) -} - -func (u userRoleDo) LeftJoin(table schema.Tabler, on ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.LeftJoin(table, on...)) -} - -func (u userRoleDo) RightJoin(table schema.Tabler, on ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.RightJoin(table, on...)) -} - -func (u userRoleDo) Group(cols ...field.Expr) IUserRoleDo { - return u.withDO(u.DO.Group(cols...)) -} - -func (u userRoleDo) Having(conds ...gen.Condition) IUserRoleDo { - return u.withDO(u.DO.Having(conds...)) -} - -func (u userRoleDo) Limit(limit int) IUserRoleDo { - return u.withDO(u.DO.Limit(limit)) -} - -func (u userRoleDo) Offset(offset int) IUserRoleDo { - return u.withDO(u.DO.Offset(offset)) -} - -func (u userRoleDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IUserRoleDo { - return u.withDO(u.DO.Scopes(funcs...)) -} - -func (u userRoleDo) Unscoped() IUserRoleDo { - return u.withDO(u.DO.Unscoped()) -} - -func (u userRoleDo) Create(values ...*models.UserRole) error { - if len(values) == 0 { - return nil - } - return u.DO.Create(values) -} - -func (u userRoleDo) CreateInBatches(values []*models.UserRole, batchSize int) error { - return u.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (u userRoleDo) Save(values ...*models.UserRole) error { - if len(values) == 0 { - return nil - } - return u.DO.Save(values) -} - -func (u userRoleDo) First() (*models.UserRole, error) { - if result, err := u.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.UserRole), nil - } -} - -func (u userRoleDo) Take() (*models.UserRole, error) { - if result, err := u.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.UserRole), nil - } -} - -func (u userRoleDo) Last() (*models.UserRole, error) { - if result, err := u.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.UserRole), nil - } -} - -func (u userRoleDo) Find() ([]*models.UserRole, error) { - result, err := u.DO.Find() - return result.([]*models.UserRole), err -} - -func (u userRoleDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.UserRole, err error) { - buf := make([]*models.UserRole, 0, batchSize) - err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (u userRoleDo) FindInBatches(result *[]*models.UserRole, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return u.DO.FindInBatches(result, batchSize, fc) -} - -func (u userRoleDo) Attrs(attrs ...field.AssignExpr) IUserRoleDo { - return u.withDO(u.DO.Attrs(attrs...)) -} - -func (u userRoleDo) Assign(attrs ...field.AssignExpr) IUserRoleDo { - return u.withDO(u.DO.Assign(attrs...)) -} - -func (u userRoleDo) Joins(fields ...field.RelationField) IUserRoleDo { - for _, _f := range fields { - u = *u.withDO(u.DO.Joins(_f)) - } - return &u -} - -func (u userRoleDo) Preload(fields ...field.RelationField) IUserRoleDo { - for _, _f := range fields { - u = *u.withDO(u.DO.Preload(_f)) - } - return &u -} - -func (u userRoleDo) FirstOrInit() (*models.UserRole, error) { - if result, err := u.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.UserRole), nil - } -} - -func (u userRoleDo) FirstOrCreate() (*models.UserRole, error) { - if result, err := u.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.UserRole), nil - } -} - -func (u userRoleDo) FindByPage(offset int, limit int) (result []*models.UserRole, count int64, err error) { - result, err = u.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = u.Offset(-1).Limit(-1).Count() - return -} - -func (u userRoleDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = u.Count() - if err != nil { - return - } - - err = u.Offset(offset).Limit(limit).Scan(result) - return -} - -func (u userRoleDo) Scan(result interface{}) (err error) { - return u.DO.Scan(result) -} - -func (u userRoleDo) Delete(models ...*models.UserRole) (result gen.ResultInfo, err error) { - return u.DO.Delete(models) -} - -func (u *userRoleDo) withDO(do gen.Dao) *userRoleDo { - u.DO = *do.(*gen.DO) - return u -} diff --git a/database/query/users.gen.go b/database/query/users.gen.go deleted file mode 100644 index f39bec9..0000000 --- a/database/query/users.gen.go +++ /dev/null @@ -1,438 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "atom/database/models" -) - -func newUser(db *gorm.DB, opts ...gen.DOOption) user { - _user := user{} - - _user.userDo.UseDB(db, opts...) - _user.userDo.UseModel(&models.User{}) - - tableName := _user.userDo.TableName() - _user.ALL = field.NewAsterisk(tableName) - _user.ID = field.NewUint64(tableName, "id") - _user.CreatedAt = field.NewTime(tableName, "created_at") - _user.UpdatedAt = field.NewTime(tableName, "updated_at") - _user.DeletedAt = field.NewField(tableName, "deleted_at") - _user.UUID = field.NewString(tableName, "uuid") - _user.Username = field.NewString(tableName, "username") - _user.Password = field.NewString(tableName, "password") - _user.Nickname = field.NewString(tableName, "nickname") - _user.Avatar = field.NewString(tableName, "avatar") - _user.RoleID = field.NewUint64(tableName, "role_id") - _user.Phone = field.NewString(tableName, "phone") - _user.Email = field.NewString(tableName, "email") - _user.Status = field.NewString(tableName, "status") - - _user.fillFieldMap() - - return _user -} - -type user struct { - userDo userDo - - ALL field.Asterisk - ID field.Uint64 - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - UUID field.String // UUID - Username field.String // 登录名 - Password field.String // 登录密码 - Nickname field.String // 昵称 - Avatar field.String // 头像 - RoleID field.Uint64 // 角色ID - Phone field.String // 手机号 - Email field.String // 邮箱 - Status field.String // 用户状态 - - fieldMap map[string]field.Expr -} - -func (u user) Table(newTableName string) *user { - u.userDo.UseTable(newTableName) - return u.updateTableName(newTableName) -} - -func (u user) As(alias string) *user { - u.userDo.DO = *(u.userDo.As(alias).(*gen.DO)) - return u.updateTableName(alias) -} - -func (u *user) updateTableName(table string) *user { - u.ALL = field.NewAsterisk(table) - u.ID = field.NewUint64(table, "id") - u.CreatedAt = field.NewTime(table, "created_at") - u.UpdatedAt = field.NewTime(table, "updated_at") - u.DeletedAt = field.NewField(table, "deleted_at") - u.UUID = field.NewString(table, "uuid") - u.Username = field.NewString(table, "username") - u.Password = field.NewString(table, "password") - u.Nickname = field.NewString(table, "nickname") - u.Avatar = field.NewString(table, "avatar") - u.RoleID = field.NewUint64(table, "role_id") - u.Phone = field.NewString(table, "phone") - u.Email = field.NewString(table, "email") - u.Status = field.NewString(table, "status") - - u.fillFieldMap() - - return u -} - -func (u *user) WithContext(ctx context.Context) IUserDo { return u.userDo.WithContext(ctx) } - -func (u user) TableName() string { return u.userDo.TableName() } - -func (u user) Alias() string { return u.userDo.Alias() } - -func (u *user) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := u.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (u *user) fillFieldMap() { - u.fieldMap = make(map[string]field.Expr, 13) - u.fieldMap["id"] = u.ID - u.fieldMap["created_at"] = u.CreatedAt - u.fieldMap["updated_at"] = u.UpdatedAt - u.fieldMap["deleted_at"] = u.DeletedAt - u.fieldMap["uuid"] = u.UUID - u.fieldMap["username"] = u.Username - u.fieldMap["password"] = u.Password - u.fieldMap["nickname"] = u.Nickname - u.fieldMap["avatar"] = u.Avatar - u.fieldMap["role_id"] = u.RoleID - u.fieldMap["phone"] = u.Phone - u.fieldMap["email"] = u.Email - u.fieldMap["status"] = u.Status -} - -func (u user) clone(db *gorm.DB) user { - u.userDo.ReplaceConnPool(db.Statement.ConnPool) - return u -} - -func (u user) replaceDB(db *gorm.DB) user { - u.userDo.ReplaceDB(db) - return u -} - -type userDo struct{ gen.DO } - -type IUserDo interface { - gen.SubQuery - Debug() IUserDo - WithContext(ctx context.Context) IUserDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IUserDo - WriteDB() IUserDo - As(alias string) gen.Dao - Session(config *gorm.Session) IUserDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IUserDo - Not(conds ...gen.Condition) IUserDo - Or(conds ...gen.Condition) IUserDo - Select(conds ...field.Expr) IUserDo - Where(conds ...gen.Condition) IUserDo - Order(conds ...field.Expr) IUserDo - Distinct(cols ...field.Expr) IUserDo - Omit(cols ...field.Expr) IUserDo - Join(table schema.Tabler, on ...field.Expr) IUserDo - LeftJoin(table schema.Tabler, on ...field.Expr) IUserDo - RightJoin(table schema.Tabler, on ...field.Expr) IUserDo - Group(cols ...field.Expr) IUserDo - Having(conds ...gen.Condition) IUserDo - Limit(limit int) IUserDo - Offset(offset int) IUserDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IUserDo - Unscoped() IUserDo - Create(values ...*models.User) error - CreateInBatches(values []*models.User, batchSize int) error - Save(values ...*models.User) error - First() (*models.User, error) - Take() (*models.User, error) - Last() (*models.User, error) - Find() ([]*models.User, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.User, err error) - FindInBatches(result *[]*models.User, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.User) (info gen.ResultInfo, err error) - Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - Updates(value interface{}) (info gen.ResultInfo, err error) - UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error) - UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error) - UpdateColumns(value interface{}) (info gen.ResultInfo, err error) - UpdateFrom(q gen.SubQuery) gen.Dao - Attrs(attrs ...field.AssignExpr) IUserDo - Assign(attrs ...field.AssignExpr) IUserDo - Joins(fields ...field.RelationField) IUserDo - Preload(fields ...field.RelationField) IUserDo - FirstOrInit() (*models.User, error) - FirstOrCreate() (*models.User, error) - FindByPage(offset int, limit int) (result []*models.User, count int64, err error) - ScanByPage(result interface{}, offset int, limit int) (count int64, err error) - Scan(result interface{}) (err error) - Returning(value interface{}, columns ...string) IUserDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (u userDo) Debug() IUserDo { - return u.withDO(u.DO.Debug()) -} - -func (u userDo) WithContext(ctx context.Context) IUserDo { - return u.withDO(u.DO.WithContext(ctx)) -} - -func (u userDo) ReadDB() IUserDo { - return u.Clauses(dbresolver.Read) -} - -func (u userDo) WriteDB() IUserDo { - return u.Clauses(dbresolver.Write) -} - -func (u userDo) Session(config *gorm.Session) IUserDo { - return u.withDO(u.DO.Session(config)) -} - -func (u userDo) Clauses(conds ...clause.Expression) IUserDo { - return u.withDO(u.DO.Clauses(conds...)) -} - -func (u userDo) Returning(value interface{}, columns ...string) IUserDo { - return u.withDO(u.DO.Returning(value, columns...)) -} - -func (u userDo) Not(conds ...gen.Condition) IUserDo { - return u.withDO(u.DO.Not(conds...)) -} - -func (u userDo) Or(conds ...gen.Condition) IUserDo { - return u.withDO(u.DO.Or(conds...)) -} - -func (u userDo) Select(conds ...field.Expr) IUserDo { - return u.withDO(u.DO.Select(conds...)) -} - -func (u userDo) Where(conds ...gen.Condition) IUserDo { - return u.withDO(u.DO.Where(conds...)) -} - -func (u userDo) Exists(subquery interface{ UnderlyingDB() *gorm.DB }) IUserDo { - return u.Where(field.CompareSubQuery(field.ExistsOp, nil, subquery.UnderlyingDB())) -} - -func (u userDo) Order(conds ...field.Expr) IUserDo { - return u.withDO(u.DO.Order(conds...)) -} - -func (u userDo) Distinct(cols ...field.Expr) IUserDo { - return u.withDO(u.DO.Distinct(cols...)) -} - -func (u userDo) Omit(cols ...field.Expr) IUserDo { - return u.withDO(u.DO.Omit(cols...)) -} - -func (u userDo) Join(table schema.Tabler, on ...field.Expr) IUserDo { - return u.withDO(u.DO.Join(table, on...)) -} - -func (u userDo) LeftJoin(table schema.Tabler, on ...field.Expr) IUserDo { - return u.withDO(u.DO.LeftJoin(table, on...)) -} - -func (u userDo) RightJoin(table schema.Tabler, on ...field.Expr) IUserDo { - return u.withDO(u.DO.RightJoin(table, on...)) -} - -func (u userDo) Group(cols ...field.Expr) IUserDo { - return u.withDO(u.DO.Group(cols...)) -} - -func (u userDo) Having(conds ...gen.Condition) IUserDo { - return u.withDO(u.DO.Having(conds...)) -} - -func (u userDo) Limit(limit int) IUserDo { - return u.withDO(u.DO.Limit(limit)) -} - -func (u userDo) Offset(offset int) IUserDo { - return u.withDO(u.DO.Offset(offset)) -} - -func (u userDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IUserDo { - return u.withDO(u.DO.Scopes(funcs...)) -} - -func (u userDo) Unscoped() IUserDo { - return u.withDO(u.DO.Unscoped()) -} - -func (u userDo) Create(values ...*models.User) error { - if len(values) == 0 { - return nil - } - return u.DO.Create(values) -} - -func (u userDo) CreateInBatches(values []*models.User, batchSize int) error { - return u.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (u userDo) Save(values ...*models.User) error { - if len(values) == 0 { - return nil - } - return u.DO.Save(values) -} - -func (u userDo) First() (*models.User, error) { - if result, err := u.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.User), nil - } -} - -func (u userDo) Take() (*models.User, error) { - if result, err := u.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.User), nil - } -} - -func (u userDo) Last() (*models.User, error) { - if result, err := u.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.User), nil - } -} - -func (u userDo) Find() ([]*models.User, error) { - result, err := u.DO.Find() - return result.([]*models.User), err -} - -func (u userDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.User, err error) { - buf := make([]*models.User, 0, batchSize) - err = u.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (u userDo) FindInBatches(result *[]*models.User, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return u.DO.FindInBatches(result, batchSize, fc) -} - -func (u userDo) Attrs(attrs ...field.AssignExpr) IUserDo { - return u.withDO(u.DO.Attrs(attrs...)) -} - -func (u userDo) Assign(attrs ...field.AssignExpr) IUserDo { - return u.withDO(u.DO.Assign(attrs...)) -} - -func (u userDo) Joins(fields ...field.RelationField) IUserDo { - for _, _f := range fields { - u = *u.withDO(u.DO.Joins(_f)) - } - return &u -} - -func (u userDo) Preload(fields ...field.RelationField) IUserDo { - for _, _f := range fields { - u = *u.withDO(u.DO.Preload(_f)) - } - return &u -} - -func (u userDo) FirstOrInit() (*models.User, error) { - if result, err := u.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.User), nil - } -} - -func (u userDo) FirstOrCreate() (*models.User, error) { - if result, err := u.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.User), nil - } -} - -func (u userDo) FindByPage(offset int, limit int) (result []*models.User, count int64, err error) { - result, err = u.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = u.Offset(-1).Limit(-1).Count() - return -} - -func (u userDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = u.Count() - if err != nil { - return - } - - err = u.Offset(offset).Limit(limit).Scan(result) - return -} - -func (u userDo) Scan(result interface{}) (err error) { - return u.DO.Scan(result) -} - -func (u userDo) Delete(models ...*models.User) (result gen.ResultInfo, err error) { - return u.DO.Delete(models) -} - -func (u *userDo) withDO(do gen.Dao) *userDo { - u.DO = *do.(*gen.DO) - return u -} diff --git a/database/seeders/migration.go b/database/seeders/migration.go deleted file mode 100755 index e490436..0000000 --- a/database/seeders/migration.go +++ /dev/null @@ -1,44 +0,0 @@ -package seeders - -import ( - "atom/container" - "atom/contracts" - "atom/database/models" - "log" - - "github.com/brianvoe/gofakeit/v6" - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(NewMigrationSeeder, dig.Group("seeders")); err != nil { - log.Fatal(err) - } -} - -type MigrationSeeder struct { -} - -func NewMigrationSeeder() contracts.Seeder { - return &MigrationSeeder{} -} - -func (s *MigrationSeeder) Run(faker *gofakeit.Faker, db *gorm.DB) { - // times := 10 - // for i := 0; i < times; i++ { - // data := s.Generate(faker, i) - // if i == 0 { - // stmt := &gorm.Statement{DB: db} - // _ = stmt.Parse(&data) - // log.Printf("seeding %s for %d times", stmt.Schema.Table, times) - // } - // db.Create(&data) - // } -} - -func (s *MigrationSeeder) Generate(faker *gofakeit.Faker, idx int) models.Migration { - return models.Migration{ - // fill model fields - } -} diff --git a/database/seeders/placeholder.go b/database/seeders/placeholder.go deleted file mode 100644 index afb1418..0000000 --- a/database/seeders/placeholder.go +++ /dev/null @@ -1,40 +0,0 @@ -package seeders - -import ( - "atom/container" - "atom/contracts" - "log" - - "github.com/brianvoe/gofakeit/v6" - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(NewPlaceholderSeeder, dig.Group("seeders")); err != nil { - log.Fatal(err) - } -} - -type PlaceholderSeeder struct { -} - -func NewPlaceholderSeeder() contracts.Seeder { - return &PlaceholderSeeder{} -} - -type Placeholder struct { - gorm.Model - - Username string -} - -func (s *PlaceholderSeeder) Run(faker *gofakeit.Faker, db *gorm.DB) { - -} - -func (s *PlaceholderSeeder) Generate(faker *gofakeit.Faker, idx int) Placeholder { - return Placeholder{ - Username: faker.Name(), - } -} diff --git a/database/seeders/sys_role.go b/database/seeders/sys_role.go deleted file mode 100755 index 43e731d..0000000 --- a/database/seeders/sys_role.go +++ /dev/null @@ -1,64 +0,0 @@ -package seeders - -import ( - "atom/container" - "atom/contracts" - "atom/database/models" - "log" - - "github.com/brianvoe/gofakeit/v6" - "go.uber.org/dig" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(NewSysRoleSeeder, dig.Group("seeders")); err != nil { - log.Fatal(err) - } -} - -type SysRoleSeeder struct { -} - -func NewSysRoleSeeder() contracts.Seeder { - return &SysRoleSeeder{} -} - -func (s *SysRoleSeeder) Run(faker *gofakeit.Faker, db *gorm.DB) { - times := 50 - for i := 0; i < times; i++ { - data := s.Generate(faker, i) - if i == 0 { - stmt := &gorm.Statement{DB: db} - _ = stmt.Parse(&data) - log.Printf("seeding %s for %d times", stmt.Schema.Table, times) - } - db.Create(&data) - } -} - -func (s *SysRoleSeeder) Generate(faker *gofakeit.Faker, idx int) models.SysRole { - parentID := 0 - if idx > 10 { - parentID = faker.IntRange(1, 10) - } - - if idx > 20 { - parentID = faker.IntRange(10, 20) - } - - if idx > 30 { - parentID = faker.IntRange(20, 30) - } - - if idx > 40 { - parentID = faker.IntRange(30, 40) - } - - return models.SysRole{ - UUID: faker.UUID(), - Name: faker.Name(), - ParentID: uint64(parentID), - DefaultRouter: faker.Name(), - } -} diff --git a/common/request/page.go b/ds/request/page.go similarity index 100% rename from common/request/page.go rename to ds/request/page.go diff --git a/common/response/page.go b/ds/response/page.go similarity index 100% rename from common/response/page.go rename to ds/response/page.go diff --git a/go.mod b/go.mod index bb08453..f0c93d4 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module atom +module github.com/rogeecn/atom go 1.19 diff --git a/main.go b/main.go index ec27bb7..68f04f6 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,7 @@ package main import ( - "atom/cmd" + "github.com/rogeecn/atom/cmd" ) func main() { diff --git a/middleware/cors.go b/middleware/cors.go deleted file mode 100644 index 146b962..0000000 --- a/middleware/cors.go +++ /dev/null @@ -1,71 +0,0 @@ -package middleware - -import ( - "atom/providers/config" - "net/http" - - "github.com/gin-gonic/gin" -) - -// Cors 直接放行所有跨域请求并放行所有 OPTIONS 方法 -func Cors() gin.HandlerFunc { - return func(c *gin.Context) { - method := c.Request.Method - origin := c.Request.Header.Get("Origin") - c.Header("Access-Control-Allow-Origin", origin) - c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id") - c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT") - c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At") - c.Header("Access-Control-Allow-Credentials", "true") - - // 放行所有OPTIONS方法 - if method == "OPTIONS" { - c.AbortWithStatus(http.StatusNoContent) - } - // 处理请求 - c.Next() - } -} - -// CorsByRules 按照配置处理跨域请求 -func CorsByRules(config *config.Config) gin.HandlerFunc { - // 放行全部 - if config.Http.Cors.Mode == "allow-all" { - return Cors() - } - return func(c *gin.Context) { - whitelist := checkCors(config, c.GetHeader("origin")) - - // 通过检查, 添加请求头 - if whitelist != nil { - c.Header("Access-Control-Allow-Origin", whitelist.AllowOrigin) - c.Header("Access-Control-Allow-Headers", whitelist.AllowHeaders) - c.Header("Access-Control-Allow-Methods", whitelist.AllowMethods) - c.Header("Access-Control-Expose-Headers", whitelist.ExposeHeaders) - if whitelist.AllowCredentials { - c.Header("Access-Control-Allow-Credentials", "true") - } - } - - // 严格白名单模式且未通过检查,直接拒绝处理请求 - if whitelist == nil && config.Http.Cors.Mode == "strict-whitelist" && !(c.Request.Method == "GET" && c.Request.URL.Path == "/health") { - c.AbortWithStatus(http.StatusForbidden) - } else if c.Request.Method == http.MethodOptions { - // 非严格白名单模式,无论是否通过检查均放行所有 OPTIONS 方法 - c.AbortWithStatus(http.StatusNoContent) - } - - // 处理请求 - c.Next() - } -} - -func checkCors(conf *config.Config, currentOrigin string) *config.Whitelist { - for _, whitelist := range conf.Http.Cors.Whitelist { - // 遍历配置中的跨域头,寻找匹配项 - if currentOrigin == whitelist.AllowOrigin { - return &whitelist - } - } - return nil -} diff --git a/middleware/jwt.go b/middleware/jwt.go deleted file mode 100644 index dead33a..0000000 --- a/middleware/jwt.go +++ /dev/null @@ -1,41 +0,0 @@ -package middleware - -import ( - "atom/providers/jwt" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/rogeecn/gen" -) - -func JWTAuth(j *jwt.JWT) gin.HandlerFunc { - return func(c *gin.Context) { - // 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录 - token := c.Request.Header.Get("Authorization") - if token == "" { - gen.NewBusError(http.StatusBadRequest, http.StatusBadRequest, "未登录或非法访问").JSON(c, false) - c.Abort() - return - } - - // parseToken 解析token包含的信息 - claims, err := j.ParseToken(token) - if err != nil { - gen.NewBusError(http.StatusBadRequest, http.StatusBadRequest, err.Error()).JSON(c, false) - c.Abort() - return - } - - // 已登录用户被管理员禁用 需要使该用户的jwt失效 此处比较消耗性能 如果需要 请自行打开 - // 用户被删除的逻辑 需要优化 此处比较消耗性能 如果需要 请自行打开 - - // if user, err := userService.FindUserByUuid(claims.UUID.String()); err != nil || user.Enable == 2 { - // _ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: token}) - // response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c) - // c.Abort() - //} - - c.Set(jwt.CtxKey, claims) - c.Next() - } -} diff --git a/middleware/middleware.go b/middleware/middleware.go deleted file mode 100644 index c870d7c..0000000 --- a/middleware/middleware.go +++ /dev/null @@ -1 +0,0 @@ -package middleware diff --git a/middleware/operation.go b/middleware/operation.go deleted file mode 100644 index d657fd1..0000000 --- a/middleware/operation.go +++ /dev/null @@ -1,138 +0,0 @@ -package middleware - -import ( - "atom/database/models" - "atom/providers/jwt" - "atom/providers/log" - "bytes" - "encoding/json" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/gin-gonic/gin" - "go.uber.org/zap" -) - -var respPool sync.Pool - -func init() { - respPool.New = func() interface{} { - return make([]byte, 1024) - } -} - -func OperationRecord() gin.HandlerFunc { - return func(c *gin.Context) { - var body []byte - var userId int64 - if c.Request.Method != http.MethodGet { - var err error - body, err = io.ReadAll(c.Request.Body) - if err != nil { - log.Error("read body from request error:", zap.Error(err)) - } else { - c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) - } - } else { - query := c.Request.URL.RawQuery - query, _ = url.QueryUnescape(query) - split := strings.Split(query, "&") - m := make(map[string]string) - for _, v := range split { - kv := strings.Split(v, "=") - if len(kv) == 2 { - m[kv[0]] = kv[1] - } - } - body, _ = json.Marshal(&m) - } - - claimsCtx, exists := c.Get(jwt.CtxKey) - if !exists { - c.Next() - return - } - - claims := claimsCtx.(jwt.Claims) - if claims.UID != 0 { - userId = int64(claims.UID) - } else { - id, err := strconv.Atoi(c.Request.Header.Get("x-user-id")) - if err != nil { - log.Error(err) - } - userId = int64(id) - } - record := models.SysOperationRecord{ - IP: c.ClientIP(), - Method: c.Request.Method, - Path: c.Request.URL.Path, - Agent: c.Request.UserAgent(), - Body: string(body), - UserID: userId, - } - - // 上传文件时候 中间件日志进行裁断操作 - if strings.Contains(c.GetHeader("Content-Type"), "multipart/form-data") { - if len(record.Body) > 1024 { - // 截断 - newBody := respPool.Get().([]byte) - copy(newBody, record.Body) - record.Body = string(newBody) - defer respPool.Put(&newBody) - } - } - - writer := responseBodyWriter{ - ResponseWriter: c.Writer, - body: &bytes.Buffer{}, - } - c.Writer = writer - now := time.Now() - - c.Next() - - latency := time.Since(now) - record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String() - record.Status = int64(c.Writer.Status()) - record.Latency = int64(latency) - record.Resp = writer.body.String() - - if strings.Contains(c.Writer.Header().Get("Pragma"), "public") || - strings.Contains(c.Writer.Header().Get("Expires"), "0") || - strings.Contains(c.Writer.Header().Get("Cache-Control"), "must-revalidate, post-check=0, pre-check=0") || - strings.Contains(c.Writer.Header().Get("Content-Type"), "application/force-download") || - strings.Contains(c.Writer.Header().Get("Content-Type"), "application/octet-stream") || - strings.Contains(c.Writer.Header().Get("Content-Type"), "application/vnd.ms-excel") || - strings.Contains(c.Writer.Header().Get("Content-Type"), "application/download") || - strings.Contains(c.Writer.Header().Get("Content-Disposition"), "attachment") || - strings.Contains(c.Writer.Header().Get("Content-Transfer-Encoding"), "binary") { - if len(record.Resp) > 1024 { - // 截断 - newBody := respPool.Get().([]byte) - copy(newBody, record.Resp) - record.Body = string(newBody) - defer respPool.Put(&newBody) - } - } - - // if err := operationRecordService.CreateSysOperationRecord(record); err != nil { - // log.Error("create operation record error:", zap.Error(err)) - // } - } -} - -type responseBodyWriter struct { - gin.ResponseWriter - body *bytes.Buffer -} - -func (r responseBodyWriter) Write(b []byte) (int, error) { - r.body.Write(b) - return r.ResponseWriter.Write(b) -} diff --git a/middleware/rbac.go b/middleware/rbac.go deleted file mode 100644 index e3f480c..0000000 --- a/middleware/rbac.go +++ /dev/null @@ -1,45 +0,0 @@ -package middleware - -import ( - "atom/providers/config" - "atom/providers/jwt" - "atom/providers/rbac" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/rogeecn/gen" -) - -// Permission 拦截器 -func CheckPermission(config *config.Config, rbac rbac.IRbac) gin.HandlerFunc { - return func(c *gin.Context) { - if config.App.Mode != "production" { - c.Next() - return - } - - claimsCtx, exists := c.Get(jwt.CtxKey) - if !exists { - gen.NewBusError(http.StatusBadRequest, http.StatusBadRequest, "Token 获取失败").JSON(c, false) - c.Abort() - return - } - claims := claimsCtx.(jwt.Claims) - - // 获取请求的PATH - path := c.Request.URL.Path - - // 获取请求方法 - method := c.Request.Method - - // 获取用户的角色 - role := strconv.Itoa(int(claims.Role)) - - if !rbac.Can(role, method, path) { - gen.NewBusError(http.StatusForbidden, http.StatusForbidden, "未登录或非法访问").JSON(c, false) - c.Abort() - return - } - } -} diff --git a/modules/auth/container/container.go b/modules/auth/container/container.go deleted file mode 100755 index 4568be7..0000000 --- a/modules/auth/container/container.go +++ /dev/null @@ -1,54 +0,0 @@ -package container - -import ( - "atom/container" - "atom/modules/auth/controller" - "atom/modules/auth/dao" - "atom/modules/auth/routes" - "atom/modules/auth/service" - "log" - - "go.uber.org/dig" -) - -func init() { - // controller - if err := container.Container.Provide(controller.NewRoleController); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(controller.NewUserController); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(controller.NewPermissionController); err != nil { - log.Fatal(err) - } - - // service - if err := container.Container.Provide(service.NewRoleService); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(service.NewUserService); err != nil { - log.Fatal(err) - } - - // dao - if err := container.Container.Provide(dao.NewRoleDao); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(dao.NewUserDao); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(dao.NewUserRoleDao); err != nil { - log.Fatal(err) - } - - // routes - if err := container.Container.Provide(routes.NewRoute, dig.Group("route")); err != nil { - log.Fatal(err) - } -} diff --git a/modules/auth/controller/permission.go b/modules/auth/controller/permission.go deleted file mode 100755 index 336865a..0000000 --- a/modules/auth/controller/permission.go +++ /dev/null @@ -1,39 +0,0 @@ -package controller - -import ( - "atom/providers/jwt" - "atom/providers/log" - "atom/providers/rbac" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/rogeecn/gen" -) - -type PermissionController struct { - jwt *jwt.JWT - rbac rbac.IRbac -} - -func NewPermissionController( - jwt *jwt.JWT, - rbac rbac.IRbac, -) *PermissionController { - return &PermissionController{rbac: rbac, jwt: jwt} -} - -func (c *PermissionController) Get(ctx *gin.Context) (string, error) { - claimsCtx, exists := ctx.Get(jwt.CtxKey) - if !exists { - return "", gen.NewBusError(http.StatusBadRequest, http.StatusBadRequest, "Token 获取失败") - } - claims := claimsCtx.(jwt.Claims) - log.Debug("claim: ", claims) - - perm, err := c.rbac.JsonPermissionsForUser("Rogee") - if err != nil { - return "", err - } - - return perm, nil -} diff --git a/modules/auth/controller/role.go b/modules/auth/controller/role.go deleted file mode 100755 index bf401a3..0000000 --- a/modules/auth/controller/role.go +++ /dev/null @@ -1,46 +0,0 @@ -package controller - -import ( - "atom/common/request" - "atom/common/response" - "atom/database/models" - "atom/modules/auth/dto" - "atom/modules/auth/service" - - "github.com/gin-gonic/gin" -) - -type RoleController struct { - roleSvc *service.RoleService -} - -func NewRoleController( - roleSvc *service.RoleService, -) *RoleController { - return &RoleController{ - roleSvc: roleSvc, - } -} - -func (c *RoleController) GetByFilter( - ctx *gin.Context, - filter dto.RoleRequestFilter, - page request.PageFilter, -) (*response.PageResponse[*models.SysRole], error) { - return c.roleSvc.GetByFilter(ctx, filter, page) -} -func (c *RoleController) Tree(ctx *gin.Context) ([]*dto.RoleTree, error) { - return c.roleSvc.Tree(ctx) -} - -func (c *RoleController) Create(ctx *gin.Context, req dto.RoleRequestForm) error { - _, err := c.roleSvc.Create(ctx, req) - return err -} -func (c *RoleController) UpdateByID(ctx *gin.Context, id int, req dto.RoleRequestForm) error { - _, err := c.roleSvc.UpdateByID(ctx, uint64(id), req) - return err -} -func (c *RoleController) Delete(ctx *gin.Context, id int) error { - return c.roleSvc.DeleteByID(ctx, uint64(id)) -} diff --git a/modules/auth/controller/user.go b/modules/auth/controller/user.go deleted file mode 100755 index cd3157d..0000000 --- a/modules/auth/controller/user.go +++ /dev/null @@ -1,44 +0,0 @@ -package controller - -import ( - "atom/modules/auth/dto" - "atom/modules/auth/service" - "atom/providers/config" - "atom/providers/jwt" - - "github.com/gin-gonic/gin" -) - -type UserController struct { - conf *config.Config - user *service.UserService - jwt *jwt.JWT -} - -func NewUserController( - conf *config.Config, - user *service.UserService, - jwt *jwt.JWT, -) *UserController { - return &UserController{ - conf: conf, - user: user, - jwt: jwt, - } -} - -func (c *UserController) Login(ctx *gin.Context, req dto.LoginRequestForm) (*dto.LoginResponse, error) { - user, err := c.user.AuthMatchPassword(ctx, &req) - if err != nil { - return nil, err - } - - token, err := c.user.GenerateJWTTokenFromUser(ctx, user) - if err != nil { - return nil, err - } - - return &dto.LoginResponse{ - Token: token, - }, nil -} diff --git a/modules/auth/dao/role.go b/modules/auth/dao/role.go deleted file mode 100755 index 8ba27b2..0000000 --- a/modules/auth/dao/role.go +++ /dev/null @@ -1,85 +0,0 @@ -package dao - -import ( - "atom/common/request" - "atom/database/models" - "atom/database/query" - "atom/modules/auth/dto" - "context" -) - -type RoleDao struct { - query *query.Query -} - -func NewRoleDao(query *query.Query) *RoleDao { - return &RoleDao{query: query} -} - -func (dao *RoleDao) GetByFilter(ctx context.Context, filter dto.RoleRequestFilter, page request.PageFilter) ([]*models.SysRole, uint64, error) { - role := dao.query.SysRole - query := role.WithContext(ctx) - - if filter.DefaultRouter != nil { - query = query.Where(role.DefaultRouter.Eq(*filter.DefaultRouter)) - } - - if filter.Name != nil { - query = query.Where(role.Name.Like(*filter.Name)) - } - - if filter.ParentID != nil { - query = query.Where(role.ParentID.Eq(uint64(*filter.ParentID))) - } - - total, err := query.Count() - if err != nil { - return nil, 0, err - } - - items, err := query.Find() - if err != nil { - return nil, 0, err - } - - return items, uint64(total), nil -} - -func (dao *RoleDao) All(ctx context.Context) ([]*models.SysRole, error) { - role := dao.query.SysRole - return role.WithContext(ctx).Find() -} - -func (dao *RoleDao) FindByID(ctx context.Context, id uint64) (*models.SysRole, error) { - role := dao.query.SysRole - return role.WithContext(ctx).Where(role.ID.Eq(id)).First() -} - -func (dao *RoleDao) Create(ctx context.Context, model *models.SysRole) (*models.SysRole, error) { - role := dao.query.SysRole - if err := role.WithContext(ctx).Create(model); err != nil { - return nil, err - } - return model, nil -} - -func (dao *RoleDao) UpdateByID(ctx context.Context, model *models.SysRole) (*models.SysRole, error) { - role := dao.query.SysRole - _, err := role.WithContext(ctx).Where(role.ID.Eq(model.ID)).Updates(model) - if err != nil { - return nil, err - } - return model, nil -} - -func (dao *RoleDao) DeleteByID(ctx context.Context, id uint64) error { - role := dao.query.SysRole - _, err := role.WithContext(ctx).Where(role.ID.Eq(id)).Delete() - return err -} - -func (dao *RoleDao) DeletePermanentlyByID(ctx context.Context, id uint64) error { - role := dao.query.SysRole - _, err := role.WithContext(ctx).Unscoped().Where(role.ID.Eq(id)).Delete() - return err -} diff --git a/modules/auth/dao/role_test.go b/modules/auth/dao/role_test.go deleted file mode 100755 index 77c177b..0000000 --- a/modules/auth/dao/role_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package dao - -import ( - "context" - "log" - "testing" - - // 这里的依赖需要被导入,否则会报错 - "atom/container" - "atom/database/models" - "atom/database/query" - _ "atom/providers" - "atom/utils" - - "github.com/brianvoe/gofakeit/v6" - . "github.com/smartystreets/goconvey/convey" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "go.uber.org/dig" - "gorm.io/gorm" -) - -type RoleInjectParams struct { - dig.In - DB *gorm.DB - Dao *RoleDao - Query *query.Query - Faker *gofakeit.Faker -} - -type RoleSuite struct { - suite.Suite - RoleInjectParams -} - -func init() { - if err := container.Container.Provide(NewRoleDao); err != nil { - log.Fatal(err) - } -} - -func Test_RoleSuite(t *testing.T) { - err := container.Container.Invoke(func(p RoleInjectParams) { - s := &RoleSuite{} - s.RoleInjectParams = p - - suite.Run(t, s) - }) - assert.NoError(t, err) -} - -func (s *RoleSuite) BeforeTest(suiteName, testName string) { - log.Println("BeforeTest: ", testName) - utils.TruncateTable(s.DB, s.Query.SysRole.TableName()) - switch testName { - case "Test_FindByID", "Test_UpdateByID", "Test_DeleteByID", "Test_DeletePermanentlyByID": - log.Println("BeforeTest: insert test data") - _, _ = s.Dao.Create(context.Background(), &models.SysRole{ - UUID: s.Faker.UUID(), - Name: s.Faker.Name(), - ParentID: s.Faker.Uint64(), - DefaultRouter: s.Faker.Animal(), - }) - } -} - -func (s *RoleSuite) AfterTest(suiteName, testName string) { - -} - -/////////////////// -// start testing cases -////////////////// - -func (s *RoleSuite) Test_Create() { - Convey("Test_Create", s.T(), func() { - Reset(func() { - s.BeforeTest("_", "Test_Create") - }) - - Convey("create", func() { - model, err := s.Dao.Create(context.Background(), &models.SysRole{ - UUID: s.Faker.UUID(), - Name: s.Faker.Name(), - ParentID: s.Faker.Uint64(), - DefaultRouter: s.Faker.Animal(), - }) - So(err, ShouldBeNil) - So(model.ID, ShouldEqual, 1) - }) - }) -} - -func (s *RoleSuite) Test_FindByID() { - Convey("Test_FindByID", s.T(), func() { - model, err := s.Dao.FindByID(context.Background(), 1) - So(err, ShouldBeNil) - So(model.ID, ShouldEqual, 1) - }) -} - -func (s *RoleSuite) Test_UpdateByID() { - Convey("Test_UpdateByID", s.T(), func() { - model, err := s.Dao.FindByID(context.Background(), 1) - So(err, ShouldBeNil) - So(model.ID, ShouldEqual, 1) - - name := "TEST_UpdateByID" - model.Name = name - newModel, err := s.Dao.UpdateByID(context.Background(), model) - So(err, ShouldBeNil) - So(newModel.Name, ShouldEqual, name) - }) -} - -func (s *RoleSuite) Test_DeleteByID() { - Convey("Test_DeleteByID", s.T(), func() { - model, err := s.Dao.FindByID(context.Background(), 1) - So(err, ShouldBeNil) - So(model.ID, ShouldEqual, 1) - - err = s.Dao.DeleteByID(context.Background(), model.ID) - So(err, ShouldBeNil) - - model, err = s.Query.SysRole. - WithContext(context.TODO()). - Unscoped(). - Where(s.Query.SysRole.ID.Eq(1)). - First() - So(err, ShouldBeNil) - So(model.DeletedAt, ShouldNotBeNil) - }) -} - -func (s *RoleSuite) Test_DeletePermanentlyByID() { - Convey("Test_DeletePermanentlyByID", s.T(), func() { - model, err := s.Dao.FindByID(context.Background(), 1) - So(err, ShouldBeNil) - So(model.ID, ShouldEqual, 1) - - err = s.Dao.DeletePermanentlyByID(context.Background(), model.ID) - So(err, ShouldBeNil) - - _, err = s.Query.SysRole. - WithContext(context.TODO()). - Unscoped(). - Where(s.Query.SysRole.ID.Eq(1)). - First() - So(err, ShouldNotBeNil) - }) -} diff --git a/modules/auth/dao/user.go b/modules/auth/dao/user.go deleted file mode 100755 index 5cd5bb8..0000000 --- a/modules/auth/dao/user.go +++ /dev/null @@ -1,28 +0,0 @@ -package dao - -import ( - "atom/database/models" - "atom/database/query" - "context" -) - -type UserDao struct { - query *query.Query -} - -func NewUserDao(query *query.Query) *UserDao { - return &UserDao{query: query} -} - -func (dao *UserDao) FindByID(ctx context.Context, id uint64) (*models.User, error) { - user := dao.query.User - return user.WithContext(ctx).Where(user.ID.Eq(id)).First() -} - -func (dao *UserDao) Create(ctx context.Context, model *models.User) (*models.User, error) { - user := dao.query.User - if err := user.WithContext(ctx).Create(model); err != nil { - return nil, err - } - return model, nil -} diff --git a/modules/auth/dao/user_role.go b/modules/auth/dao/user_role.go deleted file mode 100755 index d0f58d2..0000000 --- a/modules/auth/dao/user_role.go +++ /dev/null @@ -1,44 +0,0 @@ -package dao - -import ( - "atom/database/models" - "atom/database/query" - "context" -) - -type UserRoleDao struct { - query *query.Query -} - -func NewUserRoleDao(query *query.Query) *UserRoleDao { - return &UserRoleDao{query: query} -} - -func (dao *UserRoleDao) Exists(ctx context.Context, userID int) bool { - userRole := dao.query.UserRole - count, _ := userRole.WithContext(ctx).Where(userRole.UserID.Eq(uint64(userID))).Count() - return count > 0 -} - -func (dao *UserRoleDao) Create(ctx context.Context, userID, roleID int) error { - userRole := dao.query.UserRole - return userRole.WithContext(ctx).Create(&models.UserRole{ - UserID: uint64(userID), - RoleID: uint64(roleID), - }) -} - -func (dao *UserRoleDao) Update(ctx context.Context, userID, roleID int) error { - userRole := dao.query.UserRole - _, err := userRole.WithContext(ctx).Where(userRole.UserID.Eq(uint64(userID))).Update(userRole.RoleID, roleID) - return err -} - -func (dao *UserRoleDao) Delete(ctx context.Context, userID, roleID int) error { - userRole := dao.query.UserRole - _, err := userRole.WithContext(ctx). - Where(userRole.UserID.Eq(uint64(userID))). - Where(userRole.RoleID.Eq(uint64(roleID))). - Delete() - return err -} diff --git a/modules/auth/dao/user_role_test.go b/modules/auth/dao/user_role_test.go deleted file mode 100755 index d47a3d0..0000000 --- a/modules/auth/dao/user_role_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package dao - -import ( - "context" - "log" - "testing" - - // 这里的依赖需要被导入,否则会报错 - "atom/container" - "atom/database/models" - "atom/database/query" - _ "atom/providers" - "atom/utils" - - "github.com/brianvoe/gofakeit/v6" - . "github.com/smartystreets/goconvey/convey" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "go.uber.org/dig" - "gorm.io/gorm" -) - -type UserRoleInjectParams struct { - dig.In - - DB *gorm.DB - Dao *UserRoleDao - Query *query.Query - Faker *gofakeit.Faker -} - -type UserRoleSuite struct { - suite.Suite - UserRoleInjectParams -} - -func init() { - if err := container.Container.Provide(NewUserRoleDao); err != nil { - log.Fatal(err) - } -} - -func Test_UserRoleSuite(t *testing.T) { - err := container.Container.Invoke(func(p UserRoleInjectParams) { - s := &UserRoleSuite{} - s.UserRoleInjectParams = p - - suite.Run(t, s) - }) - assert.NoError(t, err) -} - -func (s *UserRoleSuite) BeforeTest(suiteName, testName string) { - utils.TruncateTable(s.DB, s.Query.UserRole.TableName()) - -} - -func (s *UserRoleSuite) Test_GetByUserID() { - Convey("Test_GetByUserID", s.T(), func() { - Reset(func() { - s.BeforeTest("_", "Test_GetByUserID") - }) - - Convey("not exists", func() { - has := s.Dao.Exists(context.Background(), 1) - So(has, ShouldBeFalse) - }) - - Convey("exists", func() { - _ = s.Query.UserRole.WithContext(context.Background()).Create(&models.UserRole{ - UserID: 1, - RoleID: 1, - }) - - has := s.Dao.Exists(context.Background(), 1) - So(has, ShouldBeTrue) - }) - }) -} diff --git a/modules/auth/dao/user_test.go b/modules/auth/dao/user_test.go deleted file mode 100755 index bb3d58d..0000000 --- a/modules/auth/dao/user_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package dao - -import ( - "context" - "log" - "testing" - - // 这里的依赖需要被导入,否则会报错 - "atom/container" - "atom/database/models" - "atom/database/query" - _ "atom/providers" - "atom/utils" - - "github.com/brianvoe/gofakeit/v6" - . "github.com/smartystreets/goconvey/convey" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "go.uber.org/dig" - "gorm.io/gorm" -) - -type UserInjectParams struct { - dig.In - - DB *gorm.DB - Dao *UserDao - Query *query.Query - Faker *gofakeit.Faker -} - -type UserSuite struct { - suite.Suite - UserInjectParams -} - -func init() { - if err := container.Container.Provide(NewUserDao); err != nil { - log.Fatal(err) - } -} - -func Test_UserSuite(t *testing.T) { - err := container.Container.Invoke(func(p UserInjectParams) { - s := &UserSuite{} - s.UserInjectParams = p - - suite.Run(t, s) - }) - assert.NoError(t, err) -} - -func (s *UserSuite) BeforeTest(suiteName, testName string) { - log.Println("BeforeTest: ", testName) - - utils.TruncateTable(s.DB, s.Query.User.TableName()) - - switch testName { - case "": - log.Println("BeforeTest: insert test data") - _, _ = s.Dao.Create(context.Background(), &models.User{ - UUID: s.Faker.UUID(), - Username: s.Faker.Username(), - Password: s.Faker.Password(true, true, true, true, false, 16), - Nickname: s.Faker.Name(), - Avatar: s.Faker.ImageURL(100, 100), - RoleID: 0, - Phone: s.Faker.Phone(), - Email: s.Faker.Email(), - Status: s.Faker.RandomString([]string{"enable", "disabled"}), - }) - } -} - -func (s *UserSuite) Test_Create() { - Convey("Test_Create", s.T(), func() { - Convey("create", func() { - model, err := s.Dao.Create(context.Background(), &models.User{ - UUID: s.Faker.UUID(), - Username: s.Faker.Username(), - Password: s.Faker.Password(true, true, true, true, false, 16), - Nickname: s.Faker.Name(), - Avatar: s.Faker.ImageURL(100, 100), - RoleID: 0, - Phone: s.Faker.Phone(), - Email: s.Faker.Email(), - Status: s.Faker.RandomString([]string{"enable", "disabled"}), - }) - So(err, ShouldBeNil) - So(model.ID, ShouldEqual, 1) - }) - }) -} diff --git a/modules/auth/dto/role.go b/modules/auth/dto/role.go deleted file mode 100644 index e8f9e63..0000000 --- a/modules/auth/dto/role.go +++ /dev/null @@ -1,22 +0,0 @@ -package dto - -type RoleRequestFilter struct { - Name *string `form:"name"` - ParentID *uint `form:"parent_id"` - DefaultRouter *string `form:"default_router"` -} - -type RoleRequestForm struct { - Name string `json:"name,omitempty"` - ParentID uint `json:"parent_id,omitempty"` - DefaultRouter string `json:"default_router,omitempty"` -} - -type RoleTree struct { - ID uint64 `json:"id,omitempty"` - UUID string `json:"uuid,omitempty"` - Name string `json:"name,omitempty"` - ParentID uint64 `json:"parent_id,omitempty"` - DefaultRouter string `json:"default_router,omitempty"` - Children []*RoleTree `json:"children,omitempty"` -} diff --git a/modules/auth/dto/user.go b/modules/auth/dto/user.go deleted file mode 100644 index 2ff76b6..0000000 --- a/modules/auth/dto/user.go +++ /dev/null @@ -1,10 +0,0 @@ -package dto - -type LoginRequestForm struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` -} - -type LoginResponse struct { - Token string `json:"token,omitempty"` -} diff --git a/modules/auth/routes/routes.go b/modules/auth/routes/routes.go deleted file mode 100755 index f05a54c..0000000 --- a/modules/auth/routes/routes.go +++ /dev/null @@ -1,72 +0,0 @@ -package routes - -import ( - "atom/common/err" - "atom/common/request" - "atom/contracts" - "atom/modules/auth/controller" - "atom/modules/auth/dto" - "atom/providers/http" - - "github.com/rogeecn/gen" -) - -type Route struct { - svc *http.Service - user *controller.UserController - role *controller.RoleController - permission *controller.PermissionController -} - -func NewRoute( - svc *http.Service, - role *controller.RoleController, - user *controller.UserController, - permission *controller.PermissionController, -) contracts.Route { - return &Route{ - svc: svc, - role: role, - user: user, - permission: permission, - } -} - -func (r *Route) Register() { - group := r.svc.Engine.Group("auth") - { - // common functions - group.GET("/login", gen.DataFunc1( - r.user.Login, - gen.BindBody(dto.LoginRequestForm{}, err.BindBodyFailed), - )) - - roleGroup := group.Group("roles") - roleGroup.GET("", gen.DataFunc2( - r.role.GetByFilter, - gen.BindQuery(dto.RoleRequestFilter{}, err.BindQueryFailed), - gen.BindQuery(request.PageFilter{}, err.BindQueryFailed), - )) - - roleGroup.GET("/tree", gen.DataFunc(r.role.Tree)) - - roleGroup.POST("", gen.Func1( - r.role.Create, - gen.BindBody(dto.RoleRequestForm{}, err.BindBodyFailed), - )) - - roleGroup.PUT("/:id", gen.Func2( - r.role.UpdateByID, - gen.Int("role_id", err.BindPathFailed.Format("id")), - gen.BindBody(dto.RoleRequestForm{}, err.BindBodyFailed), - )) - - roleGroup.DELETE("/:id", gen.Func1( - r.role.Delete, - gen.Int("role_id", err.BindPathFailed.Format("id")), - )) - - permissionGroup := group.Group("permissions") - permissionGroup.GET("", gen.DataFunc(r.permission.Get)) - } -} diff --git a/modules/auth/service/role.go b/modules/auth/service/role.go deleted file mode 100755 index e497555..0000000 --- a/modules/auth/service/role.go +++ /dev/null @@ -1,94 +0,0 @@ -package service - -import ( - "atom/common/request" - "atom/common/response" - "atom/database/models" - "atom/modules/auth/dao" - "atom/modules/auth/dto" - "atom/providers/uuid" - "context" -) - -type RoleService struct { - dao *dao.RoleDao - uuid *uuid.Generator -} - -func NewRoleService( - dao *dao.RoleDao, - uuid *uuid.Generator, -) *RoleService { - return &RoleService{ - dao: dao, - uuid: uuid, - } -} - -func (svc *RoleService) GetByFilter( - ctx context.Context, - filter dto.RoleRequestFilter, - page request.PageFilter, -) (*response.PageResponse[*models.SysRole], error) { - items, count, err := svc.dao.GetByFilter(ctx, filter, page) - if err != nil { - return nil, err - } - - return &response.PageResponse[*models.SysRole]{ - Items: items, - Total: count, - }, nil -} - -func (svc *RoleService) treeMaker(ctx context.Context, models []*models.SysRole, pid uint64) []*dto.RoleTree { - items := []*dto.RoleTree{} - for _, model := range models { - if model.ParentID == pid { - items = append(items, &dto.RoleTree{ - ID: model.ID, - UUID: model.UUID, - Name: model.Name, - ParentID: 0, - DefaultRouter: model.DefaultRouter, - Children: svc.treeMaker(ctx, models, model.ID), - }) - } - } - return items -} - -func (svc *RoleService) Tree(ctx context.Context) ([]*dto.RoleTree, error) { - models, err := svc.dao.All(ctx) - if err != nil { - return nil, err - } - - return svc.treeMaker(ctx, models, 0), nil -} - -func (svc *RoleService) Create(ctx context.Context, req dto.RoleRequestForm) (*models.SysRole, error) { - model := models.SysRole{ - UUID: svc.uuid.MustGenerate(), - Name: req.Name, - ParentID: uint64(req.ParentID), - DefaultRouter: req.DefaultRouter, - } - return svc.dao.Create(ctx, &model) -} -func (svc *RoleService) UpdateByID(ctx context.Context, id uint64, req dto.RoleRequestForm) (*models.SysRole, error) { - model, err := svc.dao.FindByID(ctx, id) - if err != nil { - return nil, err - } - - model.Name = req.Name - model.ParentID = uint64(req.ParentID) - model.DefaultRouter = req.DefaultRouter - - return svc.dao.UpdateByID(ctx, model) -} - -func (svc *RoleService) DeleteByID(ctx context.Context, id uint64) error { - return svc.dao.DeleteByID(ctx, id) -} diff --git a/modules/auth/service/user.go b/modules/auth/service/user.go deleted file mode 100755 index f2af901..0000000 --- a/modules/auth/service/user.go +++ /dev/null @@ -1,59 +0,0 @@ -package service - -import ( - "atom/database/models" - "atom/modules/auth/dao" - "atom/modules/auth/dto" - "atom/providers/jwt" - "context" -) - -type UserService struct { - userRoleDao *dao.UserRoleDao - userDao *dao.UserDao - jwt *jwt.JWT -} - -func NewUserService( - userRoleDao *dao.UserRoleDao, - userDao *dao.UserDao, - jwt *jwt.JWT, -) *UserService { - return &UserService{ - userRoleDao: userRoleDao, - userDao: userDao, - jwt: jwt, - } -} - -func (svc *UserService) AttachRole(ctx context.Context, userID, roleID int) error { - if svc.userRoleDao.Exists(ctx, userID) { - return svc.userRoleDao.Update(ctx, userID, roleID) - } - return svc.userRoleDao.Create(ctx, userID, roleID) -} - -func (svc *UserService) DetachRole(ctx context.Context, userID, roleID int) error { - if !svc.userRoleDao.Exists(ctx, userID) { - return nil - } - return svc.userRoleDao.Delete(ctx, userID, roleID) -} -func (svc *UserService) AuthMatchPassword(ctx context.Context, req *dto.LoginRequestForm) (*models.User, error) { - return &models.User{ - ID: 10, - UUID: "1", - Username: "2", - Password: "3", - Nickname: "4", - Avatar: "5", - RoleID: 66, - }, nil -} - -func (svc *UserService) GenerateJWTTokenFromUser(ctx context.Context, user *models.User) (string, error) { - return svc.jwt.CreateToken(svc.jwt.CreateClaims(jwt.BaseClaims{ - UID: user.ID, - Role: user.RoleID, - })) -} diff --git a/modules/modules.go b/modules/modules.go deleted file mode 100644 index 5ac7bac..0000000 --- a/modules/modules.go +++ /dev/null @@ -1,7 +0,0 @@ -package modules - -import ( - _ "atom/modules/auth/container" - _ "atom/modules/resources/container" - _ "atom/modules/system/container" -) diff --git a/modules/resources/.keep b/modules/resources/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/modules/resources/container/container.go b/modules/resources/container/container.go deleted file mode 100644 index be7cf1f..0000000 --- a/modules/resources/container/container.go +++ /dev/null @@ -1,15 +0,0 @@ -package container - -import ( - "atom/container" - "atom/modules/resources/routes" - "log" - - "go.uber.org/dig" -) - -func init() { - if err := container.Container.Provide(routes.NewRoute, dig.Group("route")); err != nil { - log.Fatal(err) - } -} diff --git a/modules/resources/routes/routes.go b/modules/resources/routes/routes.go deleted file mode 100644 index 5672e5f..0000000 --- a/modules/resources/routes/routes.go +++ /dev/null @@ -1,18 +0,0 @@ -package routes - -import ( - "atom/contracts" - "atom/providers/http" -) - -type Route struct { - svc *http.Service -} - -func NewRoute(svc *http.Service) contracts.Route { - return &Route{svc: svc} -} - -func (r *Route) Register() { - // r.svc.Engine.Static("/resources/form-generator", "./resources/form-generator") -} diff --git a/modules/system/container/container.go b/modules/system/container/container.go deleted file mode 100644 index 24fe7bb..0000000 --- a/modules/system/container/container.go +++ /dev/null @@ -1,30 +0,0 @@ -package container - -import ( - "atom/container" - "atom/modules/system/controller" - "atom/modules/system/dao" - "atom/modules/system/routes" - "atom/modules/system/service" - "log" - - "go.uber.org/dig" -) - -func init() { - if err := container.Container.Provide(dao.NewDao); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(service.NewSystemService); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(controller.NewCaptchaController); err != nil { - log.Fatal(err) - } - - if err := container.Container.Provide(routes.NewRoute, dig.Group("route")); err != nil { - log.Fatal(err) - } -} diff --git a/modules/system/controller/captcha.go b/modules/system/controller/captcha.go deleted file mode 100755 index c4d8691..0000000 --- a/modules/system/controller/captcha.go +++ /dev/null @@ -1,27 +0,0 @@ -package controller - -import ( - "atom/providers/captcha" - "atom/providers/config" - - "github.com/gin-gonic/gin" -) - -type CaptchaController struct { - conf *config.Config - captcha *captcha.Captcha -} - -func NewCaptchaController( - conf *config.Config, - captcha *captcha.Captcha, -) *CaptchaController { - return &CaptchaController{ - conf: conf, - captcha: captcha, - } -} - -func (c *CaptchaController) Show(ctx *gin.Context) (*captcha.CaptchaResponse, error) { - return c.captcha.Generate() -} diff --git a/modules/system/dao/dao.go b/modules/system/dao/dao.go deleted file mode 100644 index 466bdb3..0000000 --- a/modules/system/dao/dao.go +++ /dev/null @@ -1,25 +0,0 @@ -package dao - -import ( - "atom/providers/config" - "context" - "errors" - - "gorm.io/gorm" -) - -type Dao struct { - Conf *config.Config - DB *gorm.DB -} - -func NewDao(db *gorm.DB) *Dao { - return &Dao{DB: db} -} - -func (c *Dao) Release(ctx context.Context, a int, b string) error { - if a == 20 { - return errors.New("A cant't be 20 ") - } - return nil -} diff --git a/modules/system/dao/dao_test.go b/modules/system/dao/dao_test.go deleted file mode 100644 index 677b4a3..0000000 --- a/modules/system/dao/dao_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package dao - -import ( - "atom/container" - "context" - "testing" - - "atom/providers/config" - _ "atom/providers/database" - _ "atom/providers/http" - _ "atom/providers/log" - - "go.uber.org/dig" - "gorm.io/gorm" -) - -type Fields struct { - dig.In - - Conf *config.Config - DB *gorm.DB -} - -func TestDaoImpl_Release(t *testing.T) { - var ff Fields - err := container.Container.Invoke(func(f Fields) { - ff = f - }) - if err != nil { - t.Error(err) - t.FailNow() - } - - type args struct { - ctx context.Context - a int - b string - } - tests := []struct { - name string - fields Fields - args args - wantErr bool - }{ - {"1. ", ff, args{context.Background(), 10, "Rogee"}, false}, - {"2. ", ff, args{context.Background(), 20, "Rogee"}, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - c := &Dao{ - Conf: tt.fields.Conf, - DB: tt.fields.DB, - } - if err := c.Release(tt.args.ctx, tt.args.a, tt.args.b); (err != nil) != tt.wantErr { - t.Errorf("DaoImpl.Release() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} diff --git a/modules/system/dto/captcha.go b/modules/system/dto/captcha.go deleted file mode 100644 index 76d3a17..0000000 --- a/modules/system/dto/captcha.go +++ /dev/null @@ -1 +0,0 @@ -package dto diff --git a/modules/system/routes/routes.go b/modules/system/routes/routes.go deleted file mode 100644 index 3f3138d..0000000 --- a/modules/system/routes/routes.go +++ /dev/null @@ -1,22 +0,0 @@ -package routes - -import ( - "atom/contracts" - "atom/modules/system/controller" - "atom/providers/http" - - "github.com/rogeecn/gen" -) - -type Route struct { - captcha *controller.CaptchaController - svc *http.Service -} - -func NewRoute(captcha *controller.CaptchaController, svc *http.Service) contracts.Route { - return &Route{captcha: captcha, svc: svc} -} - -func (r *Route) Register() { - r.svc.Engine.GET("/captcha", gen.DataFunc(r.captcha.Show)) -} diff --git a/modules/system/service/service.go b/modules/system/service/service.go deleted file mode 100644 index bb1bd63..0000000 --- a/modules/system/service/service.go +++ /dev/null @@ -1,13 +0,0 @@ -package service - -import ( - "atom/modules/system/dao" -) - -type SystemService struct { - dao dao.Dao -} - -func NewSystemService(dao dao.Dao) *SystemService { - return &SystemService{dao: dao} -} diff --git a/proto/.gitignore b/proto/.gitignore deleted file mode 100644 index ec4a860..0000000 --- a/proto/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.go -!.gitignore \ No newline at end of file diff --git a/proto/web_api.proto b/proto/web_api.proto deleted file mode 100644 index dce901f..0000000 --- a/proto/web_api.proto +++ /dev/null @@ -1,44 +0,0 @@ -syntax = "proto3"; - -package proto; - -option go_package = "./proto;proto"; - -service WebApi { - rpc Call(CallRequest) returns (CallResponse) {} - rpc ClientStream(stream ClientStreamRequest) returns (ClientStreamResponse) {} - rpc ServerStream(ServerStreamRequest) returns (stream ServerStreamResponse) {} - rpc BidiStream(stream BidiStreamRequest) returns (stream BidiStreamResponse) {} -} - -message CallRequest { - string name = 1; -} - -message CallResponse { - string msg = 1; -} - -message ClientStreamRequest { - int64 stroke = 1; -} - -message ClientStreamResponse { - int64 count = 1; -} - -message ServerStreamRequest { - int64 count = 1; -} - -message ServerStreamResponse { - int64 count = 1; -} - -message BidiStreamRequest { - int64 stroke = 1; -} - -message BidiStreamResponse { - int64 stroke = 1; -} diff --git a/providers/captcha/captcha.go b/providers/captcha/captcha.go index 00bb447..5fca0e6 100644 --- a/providers/captcha/captcha.go +++ b/providers/captcha/captcha.go @@ -1,20 +1,16 @@ package captcha import ( - "atom/container" - "atom/providers/config" "errors" "log" + "time" "github.com/mojocn/base64Captcha" + "github.com/rogeecn/atom/container" + "github.com/spf13/viper" + "go.uber.org/dig" ) -func init() { - if err := container.Container.Provide(NewCaptcha); err != nil { - log.Fatal(err) - } -} - type CaptchaResponse struct { CaptchaId string `json:"captcha_id,omitempty"` PicPath string `json:"pic_path,omitempty"` @@ -23,16 +19,32 @@ type CaptchaResponse struct { } type Captcha struct { - conf *config.Config captcha *base64Captcha.Captcha } -func NewCaptcha(conf *config.Config, driver base64Captcha.Driver) (*Captcha, error) { - var store = base64Captcha.DefaultMemStore - return &Captcha{ - conf: conf, - captcha: base64Captcha.NewCaptcha(driver, store), - }, nil +func Provide(conf *Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*Captcha, error) { + driver := base64Captcha.NewDriverDigit( + int(conf.Width), + int(conf.Height), + int(conf.Long), + conf.MaxScrew, + conf.DotCount, + ) + + store := base64Captcha.DefaultMemStore + return &Captcha{ + captcha: base64Captcha.NewCaptcha(driver, store), + }, nil + }) +} + +func (c *Captcha) OpenCaptchaTimeOutDuration() time.Duration { + d, err := time.ParseDuration(viper.GetString("CAPTCHA_IMG_OPEN_TIMEOUT")) + if err != nil { + log.Panic(err) + } + return d } func (c *Captcha) Generate() (*CaptchaResponse, error) { @@ -44,8 +56,8 @@ func (c *Captcha) Generate() (*CaptchaResponse, error) { return &CaptchaResponse{ CaptchaId: id, PicPath: b64s, - CaptchaLength: c.conf.Captcha.KeyLong, - OpenCaptcha: c.conf.Captcha.OpenCaptcha, + CaptchaLength: viper.GetUint("CAPTCHA_IMG_KEY_LONG"), + OpenCaptcha: viper.GetUint("CAPTCHA_IMG_OPEN"), }, nil } diff --git a/providers/captcha/config.go b/providers/captcha/config.go new file mode 100644 index 0000000..7ce78bf --- /dev/null +++ b/providers/captcha/config.go @@ -0,0 +1,25 @@ +package captcha + +import ( + "log" + "time" +) + +type Config struct { + Long uint // 验证码长度 + Width uint // 验证码宽度 + Height uint // 验证码高度 + Open uint // 防爆破验证码开启此数,0代表每次登录都需要验证码,其他数字代表错误密码此数,如3代表错误三次后出现验证码 + OpenTimeOut string // 防爆破验证码超时时间,单位:s(秒) + MaxScrew float64 // MaxSkew max absolute skew factor of a single digit. + DotCount int // Number of background circles. + +} + +func (c *Config) OpenCaptchaTimeOutDuration() time.Duration { + d, err := time.ParseDuration(c.OpenTimeOut) + if err != nil { + log.Panic(err) + } + return d +} diff --git a/providers/captcha/driver/digit.go b/providers/captcha/driver/digit.go deleted file mode 100644 index b8be9f6..0000000 --- a/providers/captcha/driver/digit.go +++ /dev/null @@ -1,26 +0,0 @@ -package storage - -import ( - "atom/container" - "atom/providers/config" - "log" - - "github.com/mojocn/base64Captcha" -) - -func init() { - if err := container.Container.Provide(NewCaptchaDriverDigit); err != nil { - log.Fatal(err) - } -} - -func NewCaptchaDriverDigit(conf *config.Config) (base64Captcha.Driver, error) { - // 字符,公式,验证码配置 - // 生成默认数字的driver - return base64Captcha.NewDriverDigit( - int(conf.Captcha.ImgHeight), - int(conf.Captcha.ImgWidth), - int(conf.Captcha.KeyLong), - 0.7, - 80), nil -} diff --git a/providers/config/loader.go b/providers/config/loader.go deleted file mode 100644 index e1b1838..0000000 --- a/providers/config/loader.go +++ /dev/null @@ -1,56 +0,0 @@ -package config - -import ( - "atom/container" - "atom/utils" - "atom/utils/fs" - "log" - - "github.com/pkg/errors" - "github.com/rogeecn/fabfile" - "github.com/spf13/viper" -) - -type Config struct { - App App - Captcha Captcha - Http Http - Log Log - Database Database - Storage Storage -} - -func init() { - if err := container.Container.Provide(Load); err != nil { - log.Fatal(err) - } -} - -func Load() (*Config, error) { - var err error - confFile := utils.ShareConfigFile - if confFile == "" { - confFile, err = fabfile.Find("config.toml") - if err != nil { - return nil, err - } - } - path, name, _ := fs.FilePathInfo(confFile) - - viper.SetConfigName(name) // name of config file (without extension) - viper.SetConfigType("toml") // REQUIRED if the config file does not have the extension in the name - viper.AddConfigPath("$HOME/") // call multiple times to add many search paths - viper.AddConfigPath(path) // optionally look for config in the working directory - viper.AddConfigPath(".") // optionally look for config in the working directory - // Find and read the config file - if err := viper.ReadInConfig(); err != nil { // Handle errors reading the config file - return nil, errors.Wrapf(err, "read config failed, %s", confFile) - } - - config := &Config{} - if err := viper.Unmarshal(&config); err != nil { - return nil, errors.Wrapf(err, "unmarshal data failed, %s", confFile) - } - - return config, nil -} diff --git a/providers/config/section_app.go b/providers/config/section_app.go deleted file mode 100644 index ac1e5c1..0000000 --- a/providers/config/section_app.go +++ /dev/null @@ -1,18 +0,0 @@ -package config - -import "atom/utils" - -type App struct { - Mode string -} - -func (a App) IsDebug() bool { - return a.Mode == "debug" -} - -func (a App) IsRelease() bool { - return a.Mode == "release" -} -func (a App) IsTesting() bool { - return a.Mode == "testing" || utils.IsInTesting() -} diff --git a/providers/config/section_captcha.go b/providers/config/section_captcha.go deleted file mode 100644 index 7edbf5c..0000000 --- a/providers/config/section_captcha.go +++ /dev/null @@ -1,22 +0,0 @@ -package config - -import ( - "log" - "time" -) - -type Captcha struct { - KeyLong uint // 验证码长度 - ImgWidth uint // 验证码宽度 - ImgHeight uint // 验证码高度 - OpenCaptcha uint // 防爆破验证码开启此数,0代表每次登录都需要验证码,其他数字代表错误密码此数,如3代表错误三次后出现验证码 - OpenCaptchaTimeOut string // 防爆破验证码超时时间,单位:s(秒) -} - -func (c *Captcha) OpenCaptchaTimeOutDuration() time.Duration { - d, err := time.ParseDuration(c.OpenCaptchaTimeOut) - if err != nil { - log.Panic(err) - } - return d -} diff --git a/providers/config/section_database.go b/providers/config/section_database.go deleted file mode 100755 index bccce71..0000000 --- a/providers/config/section_database.go +++ /dev/null @@ -1,109 +0,0 @@ -package config - -import ( - "fmt" -) - -// Database database config -type Database struct { - Driver string - MySQL *MySQL - SQLite *SQLite - Redis *Redis - PostgreSQL *PostgreSQL -} - -// MySQL database config -type MySQL struct { - Host string - Port uint - Database string - Username string - Password string - Prefix string // 表前缀 - Singular bool // 是否开启全局禁用复数,true表示开启 - MaxIdleConns int // 空闲中的最大连接数 - MaxOpenConns int // 打开到数据库的最大连接数 - Engine string // 数据库引擎,默认InnoDB -} - -func (m *MySQL) CreateDatabaseSql() string { - return fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", m.Database) -} -func (m *MySQL) EmptyDsn() string { - dsnTpl := "%s@tcp(%s:%d)/" - - authString := func() string { - if len(m.Password) > 0 { - return m.Username + ":" + m.Password - } - return m.Username - } - - return fmt.Sprintf(dsnTpl, authString(), m.Host, m.Port) -} - -// DSN connection dsn -func (m *MySQL) DSN() string { - dsnTpl := "%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local" - - authString := func() string { - if len(m.Password) > 0 { - return m.Username + ":" + m.Password - } - return m.Username - } - - return fmt.Sprintf(dsnTpl, authString(), m.Host, m.Port, m.Database) -} - -type PostgreSQL struct { - Username string - Password string - Database string - Host string - Port uint - SslMode string - TimeZone string - Prefix string // 表前缀 - Singular bool // 是否开启全局禁用复数,true表示开启 - MaxIdleConns int // 空闲中的最大连接数 - MaxOpenConns int // 打开到数据库的最大连接数 -} - -func (m *PostgreSQL) EmptyDsn() string { - dsnTpl := "host=%s user=%s password=%s port=%d dbname=postgres sslmode=disable TimeZone=Asia/Shanghai" - - return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Port) -} - -// DSN connection dsn -func (m *PostgreSQL) DSN() string { - dsnTpl := "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s" - return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Database, m.Port, m.SslMode, m.TimeZone) -} - -type Redis struct { - Host string - Port uint - Database uint - Username string - Password string -} - -// DSN connection dsn -func (m *Redis) DSN() string { - dsnTpl := "%s:%d" - return fmt.Sprintf(dsnTpl, m.Host, m.Port) -} - -type SQLite struct { - File string -} - -func (m *SQLite) CreateDatabaseSql() string { - return "" -} -func (m *SQLite) EmptyDsn() string { - return m.File -} diff --git a/providers/config/section_log.go b/providers/config/section_log.go deleted file mode 100644 index 6f4f1c5..0000000 --- a/providers/config/section_log.go +++ /dev/null @@ -1,5 +0,0 @@ -package config - -type Log struct { - Level string -} diff --git a/providers/config/section_storage.go b/providers/config/section_storage.go deleted file mode 100644 index 6c0b3c9..0000000 --- a/providers/config/section_storage.go +++ /dev/null @@ -1,29 +0,0 @@ -package config - -type Storage struct { - Driver string - AliYunOSS AliYunOSS - AwsS3 AwsS3 -} - -type AliYunOSS struct { - Bucket string - Region string - Endpoint string - AccessKeyID string - AccessKeySecret string - BaseURL string - Path string -} - -type AwsS3 struct { - Bucket string - Region string - Endpoint string - DisableSSL bool - SecretID string - SecretKey string - BaseURL string - Path string - S3ForcePathStyle bool -} diff --git a/providers/database/database.go b/providers/database/database.go deleted file mode 100644 index 33d80ba..0000000 --- a/providers/database/database.go +++ /dev/null @@ -1,35 +0,0 @@ -package database - -import ( - "atom/container" - "atom/providers/config" - "errors" - "log" - - "gorm.io/gorm" -) - -const ( - DriverMySQL = "mysql" - DriverSQLite = "sqlite" - DriverPostgres = "postgres" - DriverSQLServer = "sqlserver" -) - -func init() { - if err := container.Container.Provide(NewDatabase); err != nil { - log.Fatal(err) - } -} - -func NewDatabase(config *config.Config) (*gorm.DB, error) { - switch config.Database.Driver { - case DriverMySQL: - return NewMySQL(config.Database.MySQL) - case DriverSQLite: - return NewSQLite(config.Database.SQLite) - case DriverPostgres: - return NewPostgres(config.Database.PostgreSQL) - } - return nil, errors.New("failed to connect to db") -} diff --git a/providers/database/mysql.go b/providers/database/mysql.go deleted file mode 100644 index 01e1087..0000000 --- a/providers/database/mysql.go +++ /dev/null @@ -1,73 +0,0 @@ -package database - -import ( - "atom/providers/config" - "atom/providers/log" - "database/sql" - - "gorm.io/driver/mysql" - "gorm.io/gorm" - "gorm.io/gorm/schema" -) - -func NewMySQL(conf *config.MySQL) (*gorm.DB, error) { - if err := createMySQLDatabase(conf.EmptyDsn(), "mysql", conf.CreateDatabaseSql()); err != nil { - return nil, err - } - - mysqlConfig := mysql.Config{ - DSN: conf.DSN(), // DSN data source name - DefaultStringSize: 191, // string 类型字段的默认长度 - SkipInitializeWithVersion: false, // 根据版本自动配置 - } - - gormConfig := gorm.Config{ - NamingStrategy: schema.NamingStrategy{ - TablePrefix: conf.Prefix, - SingularTable: conf.Singular, - }, - DisableForeignKeyConstraintWhenMigrating: true, - } - - // TODO: config logger - // _default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{ - // SlowThreshold: 200 * time.Millisecond, - // LogLevel: logger.Warn, - // Colorful: true, - // }) - // conf.Logger = _default.LogMode(logger.Warn) - - db, err := gorm.Open(mysql.New(mysqlConfig), &gormConfig) - if err != nil { - return nil, err - } - - // config instance - db.InstanceSet("gorm:table_options", "ENGINE="+conf.Engine) - - sqlDB, _ := db.DB() - sqlDB.SetMaxIdleConns(conf.MaxIdleConns) - sqlDB.SetMaxOpenConns(conf.MaxOpenConns) - - return db, err -} - -// createDatabase 创建数据库 -func createMySQLDatabase(dsn, driver, createSql string) error { - db, err := sql.Open(driver, dsn) - if err != nil { - return err - } - defer func(db *sql.DB) { - err = db.Close() - if err != nil { - log.Error(err) - } - }(db) - err = db.Ping() - if err != nil { - return err - } - _, err = db.Exec(createSql) - return err -} diff --git a/providers/database/mysql/config.go b/providers/database/mysql/config.go new file mode 100755 index 0000000..8cc5b31 --- /dev/null +++ b/providers/database/mysql/config.go @@ -0,0 +1,50 @@ +package mysql + +import ( + "fmt" +) + +// MySQL database config +type Config struct { + Host string + Port uint + Database string + Username string + Password string + Prefix string // 表前缀 + Singular bool // 是否开启全局禁用复数,true表示开启 + MaxIdleConns int // 空闲中的最大连接数 + MaxOpenConns int // 打开到数据库的最大连接数 + Engine string // 数据库引擎,默认InnoDB +} + +func (m *Config) CreateDatabaseSql() string { + return fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", m.Database) +} + +func (m *Config) EmptyDsn() string { + dsnTpl := "%s@tcp(%s:%d)/" + + authString := func() string { + if len(m.Password) > 0 { + return m.Username + ":" + m.Password + } + return m.Username + } + + return fmt.Sprintf(dsnTpl, authString(), m.Host, m.Port) +} + +// DSN connection dsn +func (m *Config) DSN() string { + dsnTpl := "%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local" + + authString := func() string { + if len(m.Password) > 0 { + return m.Username + ":" + m.Password + } + return m.Username + } + + return fmt.Sprintf(dsnTpl, authString(), m.Host, m.Port, m.Database) +} diff --git a/providers/database/mysql/mysql.go b/providers/database/mysql/mysql.go new file mode 100644 index 0000000..ea0a1fb --- /dev/null +++ b/providers/database/mysql/mysql.go @@ -0,0 +1,77 @@ +package mysql + +import ( + "database/sql" + + "github.com/rogeecn/atom/container" + "github.com/rogeecn/atom/providers/log" + "go.uber.org/dig" + + "gorm.io/driver/mysql" + "gorm.io/gorm" + "gorm.io/gorm/schema" +) + +func Provide(conf *Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*gorm.DB, error) { + if err := createMySQLDatabase(conf.EmptyDsn(), "mysql", conf.CreateDatabaseSql()); err != nil { + return nil, err + } + + mysqlConfig := mysql.Config{ + DSN: conf.DSN(), // DSN data source name + DefaultStringSize: 191, // string 类型字段的默认长度 + SkipInitializeWithVersion: false, // 根据版本自动配置 + } + + gormConfig := gorm.Config{ + NamingStrategy: schema.NamingStrategy{ + TablePrefix: conf.Prefix, + SingularTable: conf.Singular, + }, + DisableForeignKeyConstraintWhenMigrating: true, + } + + // TODO: config logger + // _default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{ + // SlowThreshold: 200 * time.Millisecond, + // LogLevel: logger.Warn, + // Colorful: true, + // }) + // conf.Logger = _default.LogMode(logger.Warn) + + db, err := gorm.Open(mysql.New(mysqlConfig), &gormConfig) + if err != nil { + return nil, err + } + + // config instance + db.InstanceSet("gorm:table_options", "ENGINE="+conf.Engine) + + sqlDB, _ := db.DB() + sqlDB.SetMaxIdleConns(conf.MaxIdleConns) + sqlDB.SetMaxOpenConns(conf.MaxOpenConns) + + return db, err + }, opts...) +} + +// createDatabase 创建数据库 +func createMySQLDatabase(dsn, driver, createSql string) error { + db, err := sql.Open(driver, dsn) + if err != nil { + return err + } + defer func(db *sql.DB) { + err = db.Close() + if err != nil { + log.Error(err) + } + }(db) + err = db.Ping() + if err != nil { + return err + } + _, err = db.Exec(createSql) + return err +} diff --git a/providers/database/postgres.go b/providers/database/postgres.go deleted file mode 100644 index 464cf0e..0000000 --- a/providers/database/postgres.go +++ /dev/null @@ -1,36 +0,0 @@ -package database - -import ( - "atom/providers/config" - "log" - - "gorm.io/driver/postgres" - "gorm.io/gorm" - "gorm.io/gorm/schema" -) - -func NewPostgres(conf *config.PostgreSQL) (*gorm.DB, error) { - dbConfig := postgres.Config{ - DSN: conf.DSN(), // DSN data source name - } - log.Println("PostgreSQL DSN: ", dbConfig.DSN) - - gormConfig := gorm.Config{ - NamingStrategy: schema.NamingStrategy{ - TablePrefix: conf.Prefix, - SingularTable: conf.Singular, - }, - DisableForeignKeyConstraintWhenMigrating: true, - } - - db, err := gorm.Open(postgres.New(dbConfig), &gormConfig) - if err != nil { - return nil, err - } - - sqlDB, _ := db.DB() - sqlDB.SetMaxIdleConns(conf.MaxIdleConns) - sqlDB.SetMaxOpenConns(conf.MaxOpenConns) - - return db, err -} diff --git a/providers/database/postgres/config.go b/providers/database/postgres/config.go new file mode 100755 index 0000000..02f070f --- /dev/null +++ b/providers/database/postgres/config.go @@ -0,0 +1,31 @@ +package postgres + +import ( + "fmt" +) + +type Config struct { + Username string + Password string + Database string + Host string + Port uint + SslMode string + TimeZone string + Prefix string // 表前缀 + Singular bool // 是否开启全局禁用复数,true表示开启 + MaxIdleConns int // 空闲中的最大连接数 + MaxOpenConns int // 打开到数据库的最大连接数 +} + +func (m *Config) EmptyDsn() string { + dsnTpl := "host=%s user=%s password=%s port=%d dbname=postgres sslmode=disable TimeZone=Asia/Shanghai" + + return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Port) +} + +// DSN connection dsn +func (m *Config) DSN() string { + dsnTpl := "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s" + return fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Database, m.Port, m.SslMode, m.TimeZone) +} diff --git a/providers/database/postgres/postgres.go b/providers/database/postgres/postgres.go new file mode 100644 index 0000000..c581fe8 --- /dev/null +++ b/providers/database/postgres/postgres.go @@ -0,0 +1,40 @@ +package postgres + +import ( + "log" + + "github.com/rogeecn/atom/container" + "go.uber.org/dig" + + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/schema" +) + +func Provide(conf *Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*gorm.DB, error) { + dbConfig := postgres.Config{ + DSN: conf.DSN(), // DSN data source name + } + log.Println("PostgreSQL DSN: ", dbConfig.DSN) + + gormConfig := gorm.Config{ + NamingStrategy: schema.NamingStrategy{ + TablePrefix: conf.Prefix, + SingularTable: conf.Singular, + }, + DisableForeignKeyConstraintWhenMigrating: true, + } + + db, err := gorm.Open(postgres.New(dbConfig), &gormConfig) + if err != nil { + return nil, err + } + + sqlDB, _ := db.DB() + sqlDB.SetMaxIdleConns(conf.MaxIdleConns) + sqlDB.SetMaxOpenConns(conf.MaxOpenConns) + + return db, err + }, opts...) +} diff --git a/providers/database/redis/todo.go b/providers/database/redis/todo.go new file mode 100644 index 0000000..65a229e --- /dev/null +++ b/providers/database/redis/todo.go @@ -0,0 +1 @@ +package redis diff --git a/providers/database/sqlite.go b/providers/database/sqlite.go deleted file mode 100644 index 229039a..0000000 --- a/providers/database/sqlite.go +++ /dev/null @@ -1,18 +0,0 @@ -package database - -import ( - "atom/providers/config" - - // "gorm.io/driver/sqlite" - "github.com/glebarez/sqlite" - "gorm.io/gorm" -) - -func NewSQLite(conf *config.SQLite) (*gorm.DB, error) { - db, err := gorm.Open(sqlite.Open(conf.File), &gorm.Config{}) - if err != nil { - return nil, err - } - - return db, err -} diff --git a/providers/database/sqlite/config.go b/providers/database/sqlite/config.go new file mode 100755 index 0000000..fdff74b --- /dev/null +++ b/providers/database/sqlite/config.go @@ -0,0 +1,13 @@ +package sqlite + +type Config struct { + File string +} + +func (m *Config) CreateDatabaseSql() string { + return "" +} + +func (m *Config) EmptyDsn() string { + return m.File +} diff --git a/providers/database/sqlite/sqlite.go b/providers/database/sqlite/sqlite.go new file mode 100644 index 0000000..c4b64ad --- /dev/null +++ b/providers/database/sqlite/sqlite.go @@ -0,0 +1,21 @@ +package sqlite + +import ( + "github.com/rogeecn/atom/container" + "go.uber.org/dig" + + // "gorm.io/driver/sqlite" + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +func Provide(conf *Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*gorm.DB, error) { + db, err := gorm.Open(sqlite.Open(conf.File), &gorm.Config{}) + if err != nil { + return nil, err + } + + return db, err + }, opts...) +} diff --git a/providers/dictionary/dict.go b/providers/dictionary/dict.go deleted file mode 100644 index 29214d2..0000000 --- a/providers/dictionary/dict.go +++ /dev/null @@ -1,116 +0,0 @@ -package dictionary - -import ( - "atom/container" - "atom/database/query" - "context" - "errors" - "log" -) - -type Dict struct { - dict map[uint64]*DictInfo - dictItems []*DictInfo - mapAlias map[string]uint64 - query *query.Query -} - -func init() { - if err := container.Container.Provide(NewDictionary); err != nil { - log.Fatal(err) - } -} - -func NewDictionary(query *query.Query) (*Dict, error) { - dict := &Dict{ - query: query, - dict: make(map[uint64]*DictInfo), - dictItems: []*DictInfo{}, - mapAlias: make(map[string]uint64), - } - - if err := dict.Load(); err != nil { - return nil, err - } - return dict, nil -} - -func (dict *Dict) Load() error { - dictTable := dict.query.SysDictionary - items, err := dictTable.WithContext(context.Background()).Where(dictTable.Status.Is(true)).Find() - if err != nil { - return err - } - - ids := []uint64{} - for _, item := range items { - ids = append(ids, item.ID) - dict.mapAlias[item.Alias_] = item.ID - } - - dictDetailTable := dict.query.SysDictionaryDetail - dictItems, err := dictDetailTable.WithContext(context.Background()). - Where(dictDetailTable.Status.Is(true)). - Where(dictDetailTable.ID.In(ids...)). - Order(dictDetailTable.Weight.Desc()). - Find() - if err != nil { - return err - } - - idItems := make(map[uint64][]*DictItem) - for _, dictItem := range dictItems { - id := uint64(dictItem.SysDictionaryID) - idItems[id] = append(idItems[id], &DictItem{ - Label: dictItem.Label, - Value: dictItem.Value, - }) - } - for _, item := range items { - info := &DictInfo{ - ID: item.ID, - Name: item.Name, - Alias: item.Alias_, - Description: item.Description, - Items: idItems[item.ID], - } - dict.dictItems = append(dict.dictItems, info) - dict.dict[item.ID] = info - } - - return nil -} - -// GetLabelByValue -func (dict *Dict) GetLabelByValue(alias, value string) (string, error) { - items, err := dict.GetItems(alias) - if err != nil { - return "", err - } - - for _, item := range items { - if item.Value == value { - return item.Label, nil - } - } - - return "", errors.New("dict item not exists") -} - -// GetLabelByValue -func (dict *Dict) GetItems(alias string) ([]*DictItem, error) { - dictID, ok := dict.mapAlias[alias] - if !ok { - return nil, errors.New("dict not exists") - } - - dictItem, ok := dict.dict[dictID] - if !ok { - return nil, errors.New("dict not exists") - } - return dictItem.Items, nil -} - -func (dict *Dict) All(alias string) []*DictInfo { - return dict.dictItems -} diff --git a/providers/dictionary/info.go b/providers/dictionary/info.go deleted file mode 100644 index decb255..0000000 --- a/providers/dictionary/info.go +++ /dev/null @@ -1,14 +0,0 @@ -package dictionary - -type DictInfo struct { - ID uint64 - Name string - Alias string - Description string - Items []*DictItem -} - -type DictItem struct { - Label string - Value string -} diff --git a/providers/faker/faker.go b/providers/faker/faker.go index 0d926e7..e9a639a 100644 --- a/providers/faker/faker.go +++ b/providers/faker/faker.go @@ -1,22 +1,19 @@ package faker import ( - "atom/container" - "log" "time" + "github.com/rogeecn/atom/container" + "go.uber.org/dig" + "github.com/brianvoe/gofakeit/v6" ) -func init() { - if err := container.Container.Provide(NewFaker); err != nil { - log.Fatal(err) - } -} +func Provide(opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*gofakeit.Faker, error) { + faker := gofakeit.New(time.Now().UnixNano()) + gofakeit.SetGlobalFaker(faker) -func NewFaker() *gofakeit.Faker { - faker := gofakeit.New(time.Now().UnixNano()) - gofakeit.SetGlobalFaker(faker) - - return faker + return faker, nil + }, opts...) } diff --git a/providers/config/section_http.go b/providers/http/config.go similarity index 51% rename from providers/config/section_http.go rename to providers/http/config.go index 8a1fffa..8c743ea 100644 --- a/providers/config/section_http.go +++ b/providers/http/config.go @@ -1,12 +1,10 @@ -package config +package http import ( "fmt" - "log" - "time" ) -type Http struct { +type Config struct { Static string Host string Port uint @@ -17,21 +15,6 @@ type Http struct { Mode string Whitelist []Whitelist } - JWT JWT -} - -type JWT struct { - SigningKey string // jwt签名 - ExpiresTime string // 过期时间 - Issuer string // 签发者 -} - -func (j JWT) ExpiresTimeDuration() time.Duration { - d, err := time.ParseDuration(j.ExpiresTime) - if err != nil { - log.Fatal(err) - } - return d } type Whitelist struct { @@ -42,10 +25,10 @@ type Whitelist struct { AllowCredentials bool } -func (h *Http) Address() string { +func (h *Config) Address() string { return fmt.Sprintf("%s:%d", h.Host, h.Port) } -func (h *Http) PortString() string { +func (h *Config) PortString() string { return fmt.Sprintf(":%d", h.Port) } diff --git a/providers/http/contracts.go b/providers/http/contracts.go new file mode 100644 index 0000000..c91e939 --- /dev/null +++ b/providers/http/contracts.go @@ -0,0 +1,9 @@ +package http + +type Route interface { + Register() +} + +type Service interface { + Serve() error +} diff --git a/providers/http/engine.go b/providers/http/engine.go deleted file mode 100644 index f223a8f..0000000 --- a/providers/http/engine.go +++ /dev/null @@ -1,61 +0,0 @@ -package http - -import ( - "atom/container" - "atom/providers/config" - "atom/providers/log" - "fmt" - "time" - - "github.com/gin-gonic/gin" - "go.uber.org/zap" -) - -func init() { - if err := container.Container.Provide(NewService); err != nil { - log.Fatal(err) - } -} - -type Service struct { - Engine *gin.Engine - conf *config.Config -} - -func (e *Service) Serve() error { - if e.conf.Http.Https { - return e.Engine.RunTLS(e.conf.Http.PortString(), e.conf.Http.HttpsCert, e.conf.Http.HttpKey) - } - return e.Engine.Run(e.conf.Http.PortString()) -} - -func NewService(cfg *config.Config, logger *log.Logger) *Service { - gin.DefaultWriter = logger.LevelWriter(zap.InfoLevel) - gin.DefaultErrorWriter = logger.LevelWriter(zap.ErrorLevel) - - if cfg.App.IsDebug() { - gin.SetMode(gin.DebugMode) - } else { - gin.SetMode(gin.ReleaseMode) - } - - engine := gin.New() - - engine.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { - return fmt.Sprintf(`%s - [%s] "%s %s %s %d %s '%q' %s"\n`, - param.ClientIP, - param.TimeStamp.Format(time.RFC1123), - param.Method, - param.Path, - param.Request.Proto, - param.StatusCode, - param.Latency, - param.Request.UserAgent(), - param.ErrorMessage, - ) - })) - - engine.Use(gin.Recovery()) - - return &Service{Engine: engine, conf: cfg} -} diff --git a/providers/http/gin/engine.go b/providers/http/gin/engine.go new file mode 100644 index 0000000..f759b59 --- /dev/null +++ b/providers/http/gin/engine.go @@ -0,0 +1,54 @@ +package gin + +import ( + "fmt" + "time" + + "github.com/rogeecn/atom/container" + "github.com/rogeecn/atom/providers/http" + "github.com/rogeecn/atom/providers/log" + "go.uber.org/dig" + + "github.com/gin-gonic/gin" +) + +type Service struct { + conf *http.Config + Engine *gin.Engine +} + +func (e *Service) Use(middleware ...gin.HandlerFunc) gin.IRoutes { + return e.Engine.Use(middleware...) +} + +func (e *Service) Serve() error { + if e.conf.Https { + return e.Engine.RunTLS(e.conf.PortString(), e.conf.HttpsCert, e.conf.HttpKey) + } + return e.Engine.Run(e.conf.PortString()) +} + +func Provide(cfg *http.Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (http.Service, error) { + gin.DefaultWriter = log.LevelWriter{Level: log.InfoLevel} + gin.DefaultErrorWriter = log.LevelWriter{Level: log.ErrorLevel} + + engine := gin.New() + engine.Use(gin.Recovery()) + engine.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { + return fmt.Sprintf(`%s - [%s] "%s %s %s %d %s '%q' %s"\n`, + param.ClientIP, + param.TimeStamp.Format(time.RFC1123), + param.Method, + param.Path, + param.Request.Proto, + param.StatusCode, + param.Latency, + param.Request.UserAgent(), + param.ErrorMessage, + ) + })) + + return &Service{Engine: engine, conf: cfg}, nil + }, opts...) +} diff --git a/providers/jwt/config.go b/providers/jwt/config.go new file mode 100644 index 0000000..ef6aadd --- /dev/null +++ b/providers/jwt/config.go @@ -0,0 +1,21 @@ +package jwt + +import ( + "time" + + "github.com/rogeecn/atom/providers/log" +) + +type Config struct { + SigningKey string // jwt签名 + ExpiresTime string // 过期时间 + Issuer string // 签发者 +} + +func (c *Config) ExpiresTimeDuration() time.Duration { + d, err := time.ParseDuration(c.ExpiresTime) + if err != nil { + log.Fatal(err) + } + return d +} diff --git a/providers/jwt/jwt.go b/providers/jwt/jwt.go index 2a4ad64..ee37bfe 100644 --- a/providers/jwt/jwt.go +++ b/providers/jwt/jwt.go @@ -1,13 +1,13 @@ package jwt import ( - "atom/container" - "atom/providers/config" - "atom/providers/log" "errors" "strings" "time" + "github.com/rogeecn/atom/container" + "go.uber.org/dig" + jwt "github.com/golang-jwt/jwt/v4" "golang.org/x/sync/singleflight" ) @@ -17,12 +17,6 @@ const ( HttpHeader = "Authorization" ) -func init() { - if err := container.Container.Provide(NewJWT); err != nil { - log.Fatal(err) - } -} - type BaseClaims struct { UID uint64 `json:"uid,omitempty"` Role uint64 `json:"role,omitempty"` @@ -37,8 +31,8 @@ type Claims struct { const TOKEN_PREFIX = "Bearer " type JWT struct { - config *config.Config singleflight *singleflight.Group + config *Config SigningKey []byte } @@ -49,21 +43,23 @@ var ( TokenInvalid = errors.New("Couldn't handle this token:") ) -func NewJWT(config *config.Config) (*JWT, error) { - return &JWT{ - config: config, - SigningKey: []byte(config.Http.JWT.SigningKey), - }, nil +func Provide(config *Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*JWT, error) { + return &JWT{ + config: config, + SigningKey: []byte(config.SigningKey), + }, nil + }, opts...) } func (j *JWT) CreateClaims(baseClaims BaseClaims) *Claims { - ep, _ := time.ParseDuration(j.config.Http.JWT.ExpiresTime) + ep, _ := time.ParseDuration(j.config.ExpiresTime) claims := Claims{ BaseClaims: baseClaims, RegisteredClaims: jwt.RegisteredClaims{ NotBefore: jwt.NewNumericDate(time.Now().Add(-time.Second * 10)), // 签名生效时间 ExpiresAt: jwt.NewNumericDate(time.Now().Add(ep)), // 过期时间 7天 配置文件 - Issuer: j.config.Http.JWT.Issuer, // 签名的发行者 + Issuer: j.config.Issuer, // 签名的发行者 }, } return &claims diff --git a/providers/log/config.go b/providers/log/config.go new file mode 100644 index 0000000..f56bb95 --- /dev/null +++ b/providers/log/config.go @@ -0,0 +1,28 @@ +package log + +type Config struct { + Level Level +} + +type Level int8 + +const ( + // DebugLevel logs are typically voluminous, and are usually disabled in + // production. + DebugLevel Level = iota - 1 + // InfoLevel is the default logging priority. + InfoLevel + // WarnLevel logs are more important than Info, but don't need individual + // human review. + WarnLevel + // ErrorLevel logs are high-priority. If an application is running smoothly, + // it shouldn't generate any error-level logs. + ErrorLevel + // DPanicLevel logs are particularly important errors. In development the + // logger panics after writing the message. + DPanicLevel + // PanicLevel logs a message, then panics. + PanicLevel + // FatalLevel logs a message, then calls os.Exit(1). + FatalLevel +) diff --git a/providers/log/gin_level_writer.go b/providers/log/gin_level_writer.go index dc312a3..b5ed7fe 100644 --- a/providers/log/gin_level_writer.go +++ b/providers/log/gin_level_writer.go @@ -2,20 +2,18 @@ package log import ( "strings" - - "go.uber.org/zap/zapcore" ) type LevelWriter struct { - Level zapcore.Level + Level Level } func (w LevelWriter) Write(p []byte) (n int, err error) { str := strings.TrimSpace(string(p)) switch w.Level { - case zapcore.InfoLevel: + case InfoLevel: Info(str) - case zapcore.ErrorLevel: + case ErrorLevel: Error(str) } return len(p), nil diff --git a/providers/log/logger.go b/providers/log/logger.go index 04d6c8f..a0184b0 100644 --- a/providers/log/logger.go +++ b/providers/log/logger.go @@ -1,99 +1,103 @@ package log import ( - "atom/container" - "log" + "github.com/rogeecn/atom/container" + "go.uber.org/dig" "go.uber.org/zap" - "go.uber.org/zap/zapcore" ) -func init() { - if err := container.Container.Provide(NewZapLogger); err != nil { - log.Fatal(err) - } +func Provide(config *Config, opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*Logger, error) { + logger, err := newZapLogger(config) + if err != nil { + return nil, err + } + defaultLogger = logger + return logger, nil + }, opts...) } -var DefaultLogger *Logger +var defaultLogger *Logger type Logger struct { logger *zap.SugaredLogger } -func (l *Logger) LevelWriter(level zapcore.Level) *LevelWriter { +func (l *Logger) LevelWriter(level Level) *LevelWriter { return &LevelWriter{Level: level} } // Debug uses fmt.Sprint to construct and log a message. func Debug(args ...interface{}) { - DefaultLogger.logger.Debug(args...) + defaultLogger.logger.Debug(args...) } // Info uses fmt.Sprint to construct and log a message. func Info(args ...interface{}) { - DefaultLogger.logger.Info(args...) + defaultLogger.logger.Info(args...) } // Warn uses fmt.Sprint to construct and log a message. func Warn(args ...interface{}) { - DefaultLogger.logger.Warn(args...) + defaultLogger.logger.Warn(args...) } // Error uses fmt.Sprint to construct and log a message. func Error(args ...interface{}) { - DefaultLogger.logger.Error(args...) + defaultLogger.logger.Error(args...) } // DPanic uses fmt.Sprint to construct and log a message. In development, the // logger then panics. (See DPanicLevel for details.) func DPanic(args ...interface{}) { - DefaultLogger.logger.DPanic(args...) + defaultLogger.logger.DPanic(args...) } // Panic uses fmt.Sprint to construct and log a message, then panics. func Panic(args ...interface{}) { - DefaultLogger.logger.Panic(args...) + defaultLogger.logger.Panic(args...) } // Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit. func Fatal(args ...interface{}) { - DefaultLogger.logger.Fatal(args...) + defaultLogger.logger.Fatal(args...) } // Debugf uses fmt.Sprintf to log a templated message. func Debugf(template string, args ...interface{}) { - DefaultLogger.logger.Debugf(template, args...) + defaultLogger.logger.Debugf(template, args...) } // Infof uses fmt.Sprintf to log a templated message. func Infof(template string, args ...interface{}) { - DefaultLogger.logger.Infof(template, args...) + defaultLogger.logger.Infof(template, args...) } // Warnf uses fmt.Sprintf to log a templated message. func Warnf(template string, args ...interface{}) { - DefaultLogger.logger.Warnf(template, args...) + defaultLogger.logger.Warnf(template, args...) } // Errorf uses fmt.Sprintf to log a templated message. func Errorf(template string, args ...interface{}) { - DefaultLogger.logger.Errorf(template, args...) + defaultLogger.logger.Errorf(template, args...) } // DPanicf uses fmt.Sprintf to log a templated message. In development, the // logger then panics. (See DPanicLevel for details.) func DPanicf(template string, args ...interface{}) { - DefaultLogger.logger.DPanicf(template, args...) + defaultLogger.logger.DPanicf(template, args...) } // Panicf uses fmt.Sprintf to log a templated message, then panics. func Panicf(template string, args ...interface{}) { - DefaultLogger.logger.Panicf(template, args...) + defaultLogger.logger.Panicf(template, args...) } // Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit. func Fatalf(template string, args ...interface{}) { - DefaultLogger.logger.Fatalf(template, args...) + defaultLogger.logger.Fatalf(template, args...) } // Debugw logs a message with some additional context. The variadic key-value @@ -103,47 +107,47 @@ func Fatalf(template string, args ...interface{}) { // // s.With(keysAndValues).Debug(msg) func Debugw(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.Debugw(msg, keysAndValues...) + defaultLogger.logger.Debugw(msg, keysAndValues...) } // Infow logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func Infow(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.Infow(msg, keysAndValues...) + defaultLogger.logger.Infow(msg, keysAndValues...) } // Warnw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func Warnw(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.Warnw(msg, keysAndValues...) + defaultLogger.logger.Warnw(msg, keysAndValues...) } // Errorw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. func Errorw(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.Errorw(msg, keysAndValues...) + defaultLogger.logger.Errorw(msg, keysAndValues...) } // DPanicw logs a message with some additional context. In development, the // logger then panics. (See DPanicLevel for details.) The variadic key-value // pairs are treated as they are in With. func DPanicw(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.DPanicw(msg, keysAndValues...) + defaultLogger.logger.DPanicw(msg, keysAndValues...) } // Panicw logs a message with some additional context, then panics. The // variadic key-value pairs are treated as they are in With. func Panicw(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.Panicw(msg, keysAndValues...) + defaultLogger.logger.Panicw(msg, keysAndValues...) } // Fatalw logs a message with some additional context, then calls os.Exit. The // variadic key-value pairs are treated as they are in With. func Fatalw(msg string, keysAndValues ...interface{}) { - DefaultLogger.logger.Fatalw(msg, keysAndValues...) + defaultLogger.logger.Fatalw(msg, keysAndValues...) } // Sync flushes any buffered log entries. func Sync() error { - return DefaultLogger.logger.Sync() + return defaultLogger.logger.Sync() } diff --git a/providers/log/zap.go b/providers/log/zap.go index a621c90..dbe9246 100644 --- a/providers/log/zap.go +++ b/providers/log/zap.go @@ -1,16 +1,13 @@ package log import ( - "atom/providers/config" - "go.uber.org/zap" ) -func NewZapLogger(conf *config.Config) (*Logger, error) { +func newZapLogger(conf *Config) (*Logger, error) { logger, err := zap.NewDevelopment() if err != nil { return nil, err } - DefaultLogger = &Logger{logger: logger.Sugar()} - return DefaultLogger, nil + return &Logger{logger: logger.Sugar()}, nil } diff --git a/providers/provider.go b/providers/provider.go deleted file mode 100644 index 2a9206f..0000000 --- a/providers/provider.go +++ /dev/null @@ -1,17 +0,0 @@ -package providers - -import ( - _ "atom/providers/captcha" - _ "atom/providers/captcha/driver" - _ "atom/providers/config" - _ "atom/providers/database" - _ "atom/providers/dictionary" - _ "atom/providers/faker" - _ "atom/providers/http" - _ "atom/providers/jwt" - _ "atom/providers/log" - _ "atom/providers/query" - _ "atom/providers/rbac" - _ "atom/providers/single_flight" - _ "atom/providers/uuid" -) diff --git a/providers/query/query.go b/providers/query/query.go deleted file mode 100644 index 3907d51..0000000 --- a/providers/query/query.go +++ /dev/null @@ -1,19 +0,0 @@ -package query - -import ( - "atom/container" - "atom/database/query" - "log" - - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(NewQuery); err != nil { - log.Fatal(err) - } -} - -func NewQuery(db *gorm.DB) *query.Query { - return query.Use(db) -} diff --git a/providers/rbac/casbin.go b/providers/rbac/casbin.go deleted file mode 100644 index d627ecc..0000000 --- a/providers/rbac/casbin.go +++ /dev/null @@ -1,134 +0,0 @@ -package rbac - -import ( - "atom/container" - "atom/database/query" - "atom/providers/log" - "context" - "errors" - "strconv" - - "github.com/casbin/casbin/v2" - "github.com/casbin/casbin/v2/model" - gormadapter "github.com/casbin/gorm-adapter/v3" - _ "github.com/go-sql-driver/mysql" - "gorm.io/gorm" -) - -func init() { - if err := container.Container.Provide(NewCasbin); err != nil { - log.Fatal(err) - } -} - -type Casbin struct { - query *query.Query - enforcer *casbin.CachedEnforcer -} - -type CasbinInfo struct { - Path string `json:"path"` // 路径 - Method string `json:"method"` // 方法 -} - -func NewCasbin(query *query.Query, db *gorm.DB) (IRbac, error) { - cb := &Casbin{query: query} - - a, _ := gormadapter.NewAdapterByDB(db) - text := ` - [request_definition] - r = sub, obj, act - - [policy_definition] - p = sub, obj, act - - [role_definition] - g = _, _ - - [policy_effect] - e = some(where (p.eft == allow)) - - [matchers] - m = r.sub == p.sub && keyMatch2(r.obj,p.obj) && r.act == p.act - ` - m, err := model.NewModelFromString(text) - if err != nil { - log.Error(err, "字符串加载模型失败!") - return nil, err - } - cb.enforcer, _ = casbin.NewCachedEnforcer(m, a) - - cb.enforcer.SetExpireTime(60 * 60) - _ = cb.enforcer.LoadPolicy() - return cb, nil -} - -func (cb *Casbin) Can(role, method, path string) bool { - return false -} - -func (cb *Casbin) Reload() error { - return nil -} - -func (cb *Casbin) JsonPermissionsForUser(username string) (string, error) { - return casbin.CasbinJsGetPermissionForUser(cb.enforcer, username) -} - -func (cb *Casbin) Update(roleID uint, infos []CasbinInfo) error { - roleIdStr := strconv.Itoa(int(roleID)) - cb.Clear(0, roleIdStr) - - rules := [][]string{} - for _, v := range infos { - rules = append(rules, []string{roleIdStr, v.Path, v.Method}) - } - - success, _ := cb.enforcer.AddPolicies(rules) - if !success { - return errors.New("存在相同api,添加失败,请联系管理员") - } - - err := cb.enforcer.InvalidateCache() - if err != nil { - return err - } - - return nil -} - -func (cb *Casbin) UpdateApi(before, after CasbinInfo) error { - rule := cb.query.CasbinRule - - _, err := rule.WithContext(context.Background()). - Where(rule.V1.Eq(before.Path)). - Where(rule.V1.Eq(before.Method)). - UpdateSimple( - rule.V1.Value(after.Path), - rule.V2.Value(after.Method), - ) - if err != nil { - return err - } - - return cb.enforcer.InvalidateCache() -} - -// 获取权限列表 -func (cb *Casbin) GetPolicyPathByRoleID(roleID uint) (pathMaps []CasbinInfo) { - roleIdStr := strconv.Itoa(int(roleID)) - list := cb.enforcer.GetFilteredPolicy(0, roleIdStr) - for _, v := range list { - pathMaps = append(pathMaps, CasbinInfo{ - Path: v[1], - Method: v[2], - }) - } - return pathMaps -} - -// 清除匹配的权限 -func (cb *Casbin) Clear(v int, p ...string) bool { - success, _ := cb.enforcer.RemoveFilteredPolicy(v, p...) - return success -} diff --git a/providers/rbac/rbac.go b/providers/rbac/rbac.go deleted file mode 100644 index d9e7cb0..0000000 --- a/providers/rbac/rbac.go +++ /dev/null @@ -1,7 +0,0 @@ -package rbac - -type IRbac interface { - Can(role, method, path string) bool - JsonPermissionsForUser(string) (string, error) - Reload() error -} diff --git a/providers/single_flight/flight.go b/providers/single_flight/flight.go index 933a014..02d3dc1 100644 --- a/providers/single_flight/flight.go +++ b/providers/single_flight/flight.go @@ -1,18 +1,13 @@ package single_flight import ( - "atom/container" - "log" - + "github.com/rogeecn/atom/container" + "go.uber.org/dig" "golang.org/x/sync/singleflight" ) -func init() { - if err := container.Container.Provide(NewSingleFlight); err != nil { - log.Fatal(err) - } -} - -func NewSingleFlight() (*singleflight.Group, error) { - return &singleflight.Group{}, nil +func Provide(opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*singleflight.Group, error) { + return &singleflight.Group{}, nil + }, opts...) } diff --git a/providers/uuid/uuid.go b/providers/uuid/uuid.go index 8e7e0da..ad7affa 100644 --- a/providers/uuid/uuid.go +++ b/providers/uuid/uuid.go @@ -1,26 +1,22 @@ package uuid import ( - "atom/container" - "log" + "github.com/rogeecn/atom/container" + "go.uber.org/dig" "github.com/gofrs/uuid" ) -func init() { - if err := container.Container.Provide(NewUUID); err != nil { - log.Fatal(err) - } -} - type Generator struct { generator uuid.Generator } -func NewUUID() (*Generator, error) { - return &Generator{ - generator: uuid.DefaultGenerator, - }, nil +func Provide(opts ...dig.ProvideOption) error { + return container.Container.Provide(func() (*Generator, error) { + return &Generator{ + generator: uuid.DefaultGenerator, + }, nil + }) } func (u *Generator) MustGenerate() string { diff --git a/services/http.go b/services/http.go new file mode 100644 index 0000000..2a1423f --- /dev/null +++ b/services/http.go @@ -0,0 +1,24 @@ +package http + +import ( + "github.com/rogeecn/atom/container" + "github.com/rogeecn/atom/providers/http" + "go.uber.org/dig" +) + +type Http struct { + dig.In + + Service http.Service + Routes []http.Route `group:"route"` +} + +func ServeHttp() error { + return container.Container.Invoke(func(http Http) error { + for _, route := range http.Routes { + route.Register() + } + + return http.Service.Serve() + }) +} diff --git a/services/http/http.go b/services/http/http.go deleted file mode 100644 index ccbf459..0000000 --- a/services/http/http.go +++ /dev/null @@ -1,30 +0,0 @@ -package http - -import ( - _ "atom/modules" - - "atom/contracts" - "atom/providers/config" - "atom/providers/http" - "atom/providers/log" - - "go.uber.org/dig" -) - -type Http struct { - dig.In - - Conf *config.Config - Service *http.Service - Routes []contracts.Route `group:"route"` -} - -func Serve(http Http) error { - log.Infof("http service port %s", http.Conf.Http.Address()) - for _, route := range http.Routes { - route.Register() - } - - log.Infof("starting server on %s", http.Conf.Http.Address()) - return http.Service.Serve() -} diff --git a/utils/db.go b/utils/db/db.go similarity index 90% rename from utils/db.go rename to utils/db/db.go index 5a95f45..6a99220 100644 --- a/utils/db.go +++ b/utils/db/db.go @@ -1,4 +1,4 @@ -package utils +package db import ( "fmt" diff --git a/common/err/common.go b/utils/err/common.go similarity index 100% rename from common/err/common.go rename to utils/err/common.go diff --git a/utils/share.go b/utils/share.go deleted file mode 100644 index 7e0b1ef..0000000 --- a/utils/share.go +++ /dev/null @@ -1,8 +0,0 @@ -package utils - -var ShareConfigFile string - -var Version string = "v1.0.0" -var Service string = "api" -var BuildAt string = "-" -var GitHash string = ""