From 6c960ba40af1e0b67a5f73756f4f00c8cf52d6d1 Mon Sep 17 00:00:00 2001 From: Tine Date: Sat, 24 Feb 2024 22:07:49 +0100 Subject: [PATCH] feat: rename worker to worker-group --- deploy/docker-compose.yaml | 2 +- example.env | 2 +- internal/config/worker.go | 2 +- internal/database.go | 9 +- internal/handlers/api.go | 6 +- internal/handlers/authentication.go | 5 +- internal/handlers/settings.go | 6 +- internal/handlers/settingsmonitors.go | 87 ++- internal/handlers/settingsworkergroups.go | 124 +++++ internal/handlers/settingsworkers.go | 124 ----- internal/jwt/jwt.go | 4 +- internal/models/models.go | 35 +- .../models/query/cronjob_histories.gen.go | 486 ----------------- internal/models/query/cronjobs.gen.go | 416 -------------- internal/models/query/gen.go | 32 +- internal/models/query/monitors.gen.go | 134 ++++- internal/models/query/worker_groups.gen.go | 516 ++++++++++++++++++ internal/models/query/workers.gen.go | 416 -------------- internal/services/monitor.go | 29 +- internal/services/worker.go | 20 - internal/services/worker_group.go | 44 ++ internal/temporal/temporal.go | 3 +- justfile | 4 +- pkg/server/server.go | 10 +- pkg/worker/worker.go | 8 +- process-compose.yml | 15 - tools/generate/main.go | 4 +- web/static/css/main.css | 15 + web/static/css/tailwind.css | 40 +- web/templates/pages/incidents.tmpl | 2 +- web/templates/pages/settings_monitors.tmpl | 26 +- .../pages/settings_monitors_describe.tmpl | 2 +- web/templates/pages/settings_overview.tmpl | 24 +- ...rkers.tmpl => settings_worker_groups.tmpl} | 52 +- .../pages/settings_worker_groups_create.tmpl | 10 + ...l => settings_worker_groups_describe.tmpl} | 17 +- .../pages/settings_workers_create.tmpl | 17 - web/templates/tempaltes.go | 20 +- 38 files changed, 1051 insertions(+), 1717 deletions(-) create mode 100644 internal/handlers/settingsworkergroups.go delete mode 100644 internal/handlers/settingsworkers.go delete mode 100644 internal/models/query/cronjob_histories.gen.go delete mode 100644 internal/models/query/cronjobs.gen.go create mode 100644 internal/models/query/worker_groups.gen.go delete mode 100644 internal/models/query/workers.gen.go delete mode 100644 internal/services/worker.go create mode 100644 internal/services/worker_group.go delete mode 100644 process-compose.yml rename web/templates/pages/{settings_workers.tmpl => settings_worker_groups.tmpl} (53%) create mode 100644 web/templates/pages/settings_worker_groups_create.tmpl rename web/templates/pages/{settings_workers_describe.tmpl => settings_worker_groups_describe.tmpl} (71%) delete mode 100644 web/templates/pages/settings_workers_create.tmpl diff --git a/deploy/docker-compose.yaml b/deploy/docker-compose.yaml index da8cce6..e3ccfb6 100644 --- a/deploy/docker-compose.yaml +++ b/deploy/docker-compose.yaml @@ -37,5 +37,5 @@ services: image: ghcr.io/mentos1386/zdravko:main command: ["--worker"] environment: - - WORKER_TOKEN=change-me + - WORKER_GROUP_TOKEN=change-me - WORKER_API_URL=http://server:8000 diff --git a/example.env b/example.env index 56d764d..1e9e763 100644 --- a/example.env +++ b/example.env @@ -12,7 +12,7 @@ JWT_PRIVATE_KEY="" # To generate worker token, go to website and # create new worker. Then copy the token. -WORKER_TOKEN="" +WORKER_GROUP_TOKEN="" # OAUTH2 # The redirect/callback url is ${ROOT_URL}/oauth2/callback diff --git a/internal/config/worker.go b/internal/config/worker.go index 87f30f1..1b25fcb 100644 --- a/internal/config/worker.go +++ b/internal/config/worker.go @@ -17,7 +17,7 @@ func NewWorkerConfig() *WorkerConfig { v := newViper() // Set defaults - v.SetDefault("token", os.Getenv("WORKER_TOKEN")) + v.SetDefault("token", os.Getenv("WORKER_GROUP_TOKEN")) v.SetDefault("apiurl", GetEnvOrDefault("WORKER_API_URL", "http://localhost:8000")) err := v.ReadInConfig() diff --git a/internal/database.go b/internal/database.go index 23cb656..0770265 100644 --- a/internal/database.go +++ b/internal/database.go @@ -5,21 +5,22 @@ import ( "code.tjo.space/mentos1386/zdravko/internal/models/query" "gorm.io/driver/sqlite" "gorm.io/gorm" + "gorm.io/gorm/logger" ) //go:generate just _generate-gorm func ConnectToDatabase(path string) (*gorm.DB, *query.Query, error) { - db, err := gorm.Open(sqlite.Open(path), &gorm.Config{}) + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + }) if err != nil { return nil, nil, err } err = db.AutoMigrate( - models.Worker{}, models.Monitor{}, + models.WorkerGroup{}, models.MonitorHistory{}, - models.Cronjob{}, - models.CronjobHistory{}, models.OAuth2State{}, ) if err != nil { diff --git a/internal/handlers/api.go b/internal/handlers/api.go index 51844e0..6f3676b 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -15,14 +15,13 @@ import ( type ApiV1WorkersConnectGETResponse struct { Endpoint string `json:"endpoint"` Group string `json:"group"` - Slug string `json:"slug"` } func (h *BaseHandler) ApiV1WorkersConnectGET(c echo.Context) error { ctx := context.Background() cc := c.(AuthenticatedContext) - worker, err := services.GetWorker(ctx, h.query, cc.Principal.Worker.Slug) + workerGroup, err := services.GetWorkerGroup(ctx, h.query, cc.Principal.Worker.Group) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return echo.NewHTTPError(http.StatusUnauthorized, "Token invalid") @@ -32,8 +31,7 @@ func (h *BaseHandler) ApiV1WorkersConnectGET(c echo.Context) error { response := ApiV1WorkersConnectGETResponse{ Endpoint: h.config.Temporal.ServerHost, - Group: worker.Group, - Slug: worker.Slug, + Group: workerGroup.Slug, } return c.JSON(http.StatusOK, response) diff --git a/internal/handlers/authentication.go b/internal/handlers/authentication.go index 5f334ad..626bc5b 100644 --- a/internal/handlers/authentication.go +++ b/internal/handlers/authentication.go @@ -28,7 +28,6 @@ type AuthenticatedUser struct { } type AuthenticatedWorker struct { - Slug string Group string } @@ -100,9 +99,9 @@ func (h *BaseHandler) AuthenticateRequestWithToken(r *http.Request) (*Authentica if splitSubject[0] == "user" { user = &AuthenticatedUser{} - } else if splitSubject[0] == "worker" { + } else if splitSubject[0] == "worker-group" { worker = &AuthenticatedWorker{ - Slug: splitSubject[1], + Group: splitSubject[1], } } diff --git a/internal/handlers/settings.go b/internal/handlers/settings.go index d818a3b..2d73b0b 100644 --- a/internal/handlers/settings.go +++ b/internal/handlers/settings.go @@ -32,8 +32,8 @@ var SettingsPages = []*components.Page{ {Path: "/settings", Title: "Overview", Breadcrumb: "Overview"}, {Path: "/settings/monitors", Title: "Monitors", Breadcrumb: "Monitors"}, {Path: "/settings/monitors/create", Title: "Monitors Create", Breadcrumb: "Create"}, - {Path: "/settings/workers", Title: "Workers", Breadcrumb: "Workers"}, - {Path: "/settings/workers/create", Title: "Workers Create", Breadcrumb: "Create"}, + {Path: "/settings/worker-groups", Title: "Worker Groups", Breadcrumb: "Worker Groups"}, + {Path: "/settings/worker-groups/create", Title: "Worker Groups Create", Breadcrumb: "Create"}, {Path: "/settings/notifications", Title: "Notifications", Breadcrumb: "Notifications"}, {Path: "/settings/temporal", Title: "Temporal", Breadcrumb: "Temporal"}, {Path: "/oauth2/logout", Title: "Logout", Breadcrumb: "Logout"}, @@ -42,7 +42,7 @@ var SettingsPages = []*components.Page{ var SettingsNavbar = []*components.Page{ GetPageByTitle(SettingsPages, "Overview"), GetPageByTitle(SettingsPages, "Monitors"), - GetPageByTitle(SettingsPages, "Workers"), + GetPageByTitle(SettingsPages, "Worker Groups"), GetPageByTitle(SettingsPages, "Notifications"), GetPageByTitle(SettingsPages, "Temporal"), GetPageByTitle(SettingsPages, "Logout"), diff --git a/internal/handlers/settingsmonitors.go b/internal/handlers/settingsmonitors.go index 0f7ce2d..49a8414 100644 --- a/internal/handlers/settingsmonitors.go +++ b/internal/handlers/settingsmonitors.go @@ -14,6 +14,19 @@ import ( "github.com/labstack/echo/v4" ) +type CreateMonitor struct { + Name string `validate:"required"` + WorkerGroups string `validate:"required"` + Schedule string `validate:"required,cron"` + Script string `validate:"required"` +} + +type UpdateMonitor struct { + WorkerGroups string `validate:"required"` + Schedule string `validate:"required,cron"` + Script string `validate:"required"` +} + type SettingsMonitors struct { *Settings Monitors []*models.Monitor @@ -28,7 +41,7 @@ type SettingsMonitor struct { func (h *BaseHandler) SettingsMonitorsGET(c echo.Context) error { cc := c.(AuthenticatedContext) - monitors, err := h.query.Monitor.WithContext(context.Background()).Find() + monitors, err := services.GetMonitors(context.Background(), h.query) if err != nil { return err } @@ -72,42 +85,56 @@ func (h *BaseHandler) SettingsMonitorsDescribeGET(c echo.Context) error { func (h *BaseHandler) SettingsMonitorsDescribePOST(c echo.Context) error { ctx := context.Background() + monitorSlug := c.Param("slug") - slug := c.Param("slug") - - monitor, err := services.GetMonitor(ctx, h.query, slug) - if err != nil { - return err - } - - update := &models.Monitor{ - Slug: monitor.Slug, - Name: monitor.Name, + update := UpdateMonitor{ + WorkerGroups: strings.TrimSpace(c.FormValue("workergroups")), Schedule: c.FormValue("schedule"), - WorkerGroups: strings.Split(c.FormValue("workergroups"), " "), Script: c.FormValue("script"), } - - err = validator.New(validator.WithRequiredStructEnabled()).Struct(update) + err := validator.New(validator.WithRequiredStructEnabled()).Struct(update) if err != nil { return err } + monitor, err := services.GetMonitor(ctx, h.query, monitorSlug) + if err != nil { + return err + } + monitor.Schedule = update.Schedule + monitor.Script = update.Script + err = services.UpdateMonitor( ctx, h.query, - update, + monitor, ) if err != nil { return err } + workerGroups := []*models.WorkerGroup{} + for _, group := range strings.Split(update.WorkerGroups, " ") { + if group == "" { + continue + } + workerGroup, err := services.GetOrCreateWorkerGroup(ctx, h.query, models.WorkerGroup{Name: group, Slug: slug.Make(group)}) + if err != nil { + return err + } + workerGroups = append(workerGroups, workerGroup) + } + err = services.UpdateMonitorWorkerGroups(ctx, h.query, monitor, workerGroups) + if err != nil { + return err + } + err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor) if err != nil { return err } - return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/monitors/%s", slug)) + return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/monitors/%s", monitorSlug)) } func (h *BaseHandler) SettingsMonitorsCreateGET(c echo.Context) error { @@ -125,33 +152,45 @@ func (h *BaseHandler) SettingsMonitorsCreateGET(c echo.Context) error { func (h *BaseHandler) SettingsMonitorsCreatePOST(c echo.Context) error { ctx := context.Background() + monitorSlug := slug.Make(c.FormValue("name")) - monitorHttp := &models.Monitor{ + create := CreateMonitor{ Name: c.FormValue("name"), - Slug: slug.Make(c.FormValue("name")), Schedule: c.FormValue("schedule"), - WorkerGroups: strings.Split(c.FormValue("workergroups"), " "), + WorkerGroups: c.FormValue("workergroups"), Script: c.FormValue("script"), } - - err := validator.New(validator.WithRequiredStructEnabled()).Struct(monitorHttp) + err := validator.New(validator.WithRequiredStructEnabled()).Struct(create) if err != nil { return err } + workerGroups := []models.WorkerGroup{} + for _, group := range strings.Split(create.WorkerGroups, " ") { + workerGroups = append(workerGroups, models.WorkerGroup{Name: group, Slug: slug.Make(group)}) + } + + monitor := &models.Monitor{ + Name: create.Name, + Slug: monitorSlug, + Schedule: create.Schedule, + Script: create.Script, + WorkerGroups: workerGroups, + } + err = services.CreateMonitor( ctx, h.query, - monitorHttp, + monitor, ) if err != nil { return err } - err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitorHttp) + err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor) if err != nil { return err } - return c.Redirect(http.StatusSeeOther, "/settings/monitors") + return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/monitors/%s", monitorSlug)) } diff --git a/internal/handlers/settingsworkergroups.go b/internal/handlers/settingsworkergroups.go new file mode 100644 index 0000000..5c74b91 --- /dev/null +++ b/internal/handlers/settingsworkergroups.go @@ -0,0 +1,124 @@ +package handlers + +import ( + "context" + "fmt" + "net/http" + + "code.tjo.space/mentos1386/zdravko/internal/jwt" + "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/internal/services" + "code.tjo.space/mentos1386/zdravko/web/templates/components" + "github.com/go-playground/validator/v10" + "github.com/gosimple/slug" + "github.com/labstack/echo/v4" +) + +type WorkerWithToken struct { + *models.WorkerGroup + Token string +} + +type SettingsWorkerGroups struct { + *Settings + WorkerGroups []*models.WorkerGroup + WorkerGroupsLength int +} + +type SettingsWorker struct { + *Settings + Worker *WorkerWithToken +} + +func (h *BaseHandler) SettingsWorkerGroupsGET(c echo.Context) error { + cc := c.(AuthenticatedContext) + + workerGroups, err := services.GetWorkerGroups(context.Background(), h.query) + if err != nil { + return err + } + + return c.Render(http.StatusOK, "settings_worker_groups.tmpl", &SettingsWorkerGroups{ + Settings: NewSettings( + cc.Principal.User, + GetPageByTitle(SettingsPages, "Worker Groups"), + []*components.Page{GetPageByTitle(SettingsPages, "Worker Groups")}, + ), + WorkerGroups: workerGroups, + WorkerGroupsLength: len(workerGroups), + }) +} + +func (h *BaseHandler) SettingsWorkerGroupsDescribeGET(c echo.Context) error { + cc := c.(AuthenticatedContext) + + slug := c.Param("slug") + + worker, err := services.GetWorkerGroup(context.Background(), h.query, slug) + if err != nil { + return err + } + + // Allow write access to default namespace + token, err := jwt.NewTokenForWorker(h.config.Jwt.PrivateKey, h.config.Jwt.PublicKey, worker) + if err != nil { + return err + } + + return c.Render(http.StatusOK, "settings_worker_groups_describe.tmpl", &SettingsWorker{ + Settings: NewSettings( + cc.Principal.User, + GetPageByTitle(SettingsPages, "Worker Groups"), + []*components.Page{ + GetPageByTitle(SettingsPages, "Worker Groups"), + { + Path: fmt.Sprintf("/settings/worker-groups/%s", slug), + Title: "Describe", + Breadcrumb: worker.Name, + }, + }), + Worker: &WorkerWithToken{ + WorkerGroup: worker, + Token: token, + }, + }) +} + +func (h *BaseHandler) SettingsWorkerGroupsCreateGET(c echo.Context) error { + cc := c.(AuthenticatedContext) + + return c.Render(http.StatusOK, "settings_worker_groups_create.tmpl", NewSettings( + cc.Principal.User, + GetPageByTitle(SettingsPages, "Worker Groups"), + []*components.Page{ + GetPageByTitle(SettingsPages, "Worker Groups"), + GetPageByTitle(SettingsPages, "Worker Groups Create"), + }, + )) +} + +func (h *BaseHandler) SettingsWorkerGroupsCreatePOST(c echo.Context) error { + ctx := context.Background() + slug := slug.Make(c.FormValue("name")) + + worker := models.WorkerGroup{ + Name: c.FormValue("name"), + Slug: slug, + } + + err := validator.New(validator.WithRequiredStructEnabled()).Struct(worker) + if err != nil { + return err + } + + _, err = services.GetOrCreateWorkerGroup( + ctx, + h.query, + worker, + ) + if err != nil { + return err + } + + return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/worker-groups/%s", slug)) +} diff --git a/internal/handlers/settingsworkers.go b/internal/handlers/settingsworkers.go deleted file mode 100644 index 6f697e7..0000000 --- a/internal/handlers/settingsworkers.go +++ /dev/null @@ -1,124 +0,0 @@ -package handlers - -import ( - "context" - "fmt" - "net/http" - - "code.tjo.space/mentos1386/zdravko/internal/jwt" - "code.tjo.space/mentos1386/zdravko/internal/models" - "code.tjo.space/mentos1386/zdravko/internal/services" - "code.tjo.space/mentos1386/zdravko/web/templates/components" - "github.com/go-playground/validator/v10" - "github.com/gosimple/slug" - "github.com/labstack/echo/v4" -) - -type WorkerWithToken struct { - *models.Worker - Token string -} - -type SettingsWorkers struct { - *Settings - Workers []*models.Worker - WorkersLength int -} - -type SettingsWorker struct { - *Settings - Worker *WorkerWithToken -} - -func (h *BaseHandler) SettingsWorkersGET(c echo.Context) error { - cc := c.(AuthenticatedContext) - - workers, err := h.query.Worker.WithContext(context.Background()).Find() - if err != nil { - return err - } - - return c.Render(http.StatusOK, "settings_workers.tmpl", &SettingsWorkers{ - Settings: NewSettings( - cc.Principal.User, - GetPageByTitle(SettingsPages, "Workers"), - []*components.Page{GetPageByTitle(SettingsPages, "Workers")}, - ), - Workers: workers, - WorkersLength: len(workers), - }) -} - -func (h *BaseHandler) SettingsWorkersDescribeGET(c echo.Context) error { - cc := c.(AuthenticatedContext) - - slug := c.Param("slug") - - worker, err := services.GetWorker(context.Background(), h.query, slug) - if err != nil { - return err - } - - // Allow write access to default namespace - token, err := jwt.NewTokenForWorker(h.config.Jwt.PrivateKey, h.config.Jwt.PublicKey, worker) - if err != nil { - return err - } - - return c.Render(http.StatusOK, "settings_workers_describe.tmpl", &SettingsWorker{ - Settings: NewSettings( - cc.Principal.User, - GetPageByTitle(SettingsPages, "Workers"), - []*components.Page{ - GetPageByTitle(SettingsPages, "Workers"), - { - Path: fmt.Sprintf("/settings/workers/%s", slug), - Title: "Describe", - Breadcrumb: worker.Name, - }, - }), - Worker: &WorkerWithToken{ - Worker: worker, - Token: token, - }, - }) -} - -func (h *BaseHandler) SettingsWorkersCreateGET(c echo.Context) error { - cc := c.(AuthenticatedContext) - - return c.Render(http.StatusOK, "settings_workers_create.tmpl", NewSettings( - cc.Principal.User, - GetPageByTitle(SettingsPages, "Workers"), - []*components.Page{ - GetPageByTitle(SettingsPages, "Workers"), - GetPageByTitle(SettingsPages, "Workers Create"), - }, - )) -} - -func (h *BaseHandler) SettingsWorkersCreatePOST(c echo.Context) error { - ctx := context.Background() - - worker := &models.Worker{ - Name: c.FormValue("name"), - Slug: slug.Make(c.FormValue("name")), - Group: c.FormValue("group"), - } - - err := validator.New(validator.WithRequiredStructEnabled()).Struct(worker) - if err != nil { - return err - } - - err = services.CreateWorker( - ctx, - h.query, - worker, - ) - if err != nil { - return err - } - - return c.Redirect(http.StatusSeeOther, "/settings/workers") -} diff --git a/internal/jwt/jwt.go b/internal/jwt/jwt.go index decce98..77a5252 100644 --- a/internal/jwt/jwt.go +++ b/internal/jwt/jwt.go @@ -71,7 +71,7 @@ func NewTokenForServer(privateKey string, publicKey string) (string, error) { return NewToken(privateKey, publicKey, claims) } -func NewTokenForWorker(privateKey string, publicKey string, worker *models.Worker) (string, error) { +func NewTokenForWorker(privateKey string, publicKey string, workerGroup *models.WorkerGroup) (string, error) { // Create claims with multiple fields populated claims := Claims{ jwt.RegisteredClaims{ @@ -79,7 +79,7 @@ func NewTokenForWorker(privateKey string, publicKey string, worker *models.Worke IssuedAt: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now()), Issuer: "zdravko", - Subject: "worker:" + worker.Slug, + Subject: "worker-group:" + workerGroup.Slug, }, // Ref: https://docs.temporal.io/self-hosted-guide/security#authorization []string{"default:read", "default:write", "default:worker"}, diff --git a/internal/models/models.go b/internal/models/models.go index 2ec2a69..c4b57a2 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -3,7 +3,6 @@ package models import ( "time" - "github.com/lib/pq" "gorm.io/gorm" ) @@ -12,14 +11,6 @@ type OAuth2State struct { Expiry time.Time } -type Worker struct { - gorm.Model - Name string `gorm:"unique" validate:"required"` - Slug string `gorm:"unique"` - Group string `validate:"required"` - Status string -} - const ( MonitorSuccess string = "SUCCESS" MonitorFailure string = "FAILURE" @@ -30,33 +21,27 @@ const ( type Monitor struct { gorm.Model Slug string `gorm:"unique"` - Name string `gorm:"unique" validate:"required"` + Name string `gorm:"unique"` - Schedule string `validate:"required,cron"` - WorkerGroups pq.StringArray `gorm:"type:text[]"` + Schedule string + WorkerGroups []WorkerGroup `gorm:"many2many:monitor_worker_groups;"` Script string `validate:"required"` History []MonitorHistory `gorm:"foreignKey:Monitor"` } -type Cronjob struct { - gorm.Model - Slug string `gorm:"unique"` - Name string `gorm:"unique"` - Schedule string - Buffer int -} - type MonitorHistory struct { gorm.Model Monitor uint - Status string - Note string + Status string + Note string } -type CronjobHistory struct { +type WorkerGroup struct { gorm.Model - Cronjob Cronjob `gorm:"foreignkey:ID"` - Status string + Name string `gorm:"unique"` + Slug string `gorm:"unique"` + + Monitors []Monitor `gorm:"many2many:monitor_worker_groups;"` } diff --git a/internal/models/query/cronjob_histories.gen.go b/internal/models/query/cronjob_histories.gen.go deleted file mode 100644 index 50d8863..0000000 --- a/internal/models/query/cronjob_histories.gen.go +++ /dev/null @@ -1,486 +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" - - "code.tjo.space/mentos1386/zdravko/internal/models" -) - -func newCronjobHistory(db *gorm.DB, opts ...gen.DOOption) cronjobHistory { - _cronjobHistory := cronjobHistory{} - - _cronjobHistory.cronjobHistoryDo.UseDB(db, opts...) - _cronjobHistory.cronjobHistoryDo.UseModel(&models.CronjobHistory{}) - - tableName := _cronjobHistory.cronjobHistoryDo.TableName() - _cronjobHistory.ALL = field.NewAsterisk(tableName) - _cronjobHistory.ID = field.NewUint(tableName, "id") - _cronjobHistory.CreatedAt = field.NewTime(tableName, "created_at") - _cronjobHistory.UpdatedAt = field.NewTime(tableName, "updated_at") - _cronjobHistory.DeletedAt = field.NewField(tableName, "deleted_at") - _cronjobHistory.Status = field.NewString(tableName, "status") - _cronjobHistory.Cronjob = cronjobHistoryHasOneCronjob{ - db: db.Session(&gorm.Session{}), - - RelationField: field.NewRelation("Cronjob", "models.Cronjob"), - } - - _cronjobHistory.fillFieldMap() - - return _cronjobHistory -} - -type cronjobHistory struct { - cronjobHistoryDo cronjobHistoryDo - - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Status field.String - Cronjob cronjobHistoryHasOneCronjob - - fieldMap map[string]field.Expr -} - -func (c cronjobHistory) Table(newTableName string) *cronjobHistory { - c.cronjobHistoryDo.UseTable(newTableName) - return c.updateTableName(newTableName) -} - -func (c cronjobHistory) As(alias string) *cronjobHistory { - c.cronjobHistoryDo.DO = *(c.cronjobHistoryDo.As(alias).(*gen.DO)) - return c.updateTableName(alias) -} - -func (c *cronjobHistory) updateTableName(table string) *cronjobHistory { - c.ALL = field.NewAsterisk(table) - c.ID = field.NewUint(table, "id") - c.CreatedAt = field.NewTime(table, "created_at") - c.UpdatedAt = field.NewTime(table, "updated_at") - c.DeletedAt = field.NewField(table, "deleted_at") - c.Status = field.NewString(table, "status") - - c.fillFieldMap() - - return c -} - -func (c *cronjobHistory) WithContext(ctx context.Context) ICronjobHistoryDo { - return c.cronjobHistoryDo.WithContext(ctx) -} - -func (c cronjobHistory) TableName() string { return c.cronjobHistoryDo.TableName() } - -func (c cronjobHistory) Alias() string { return c.cronjobHistoryDo.Alias() } - -func (c cronjobHistory) Columns(cols ...field.Expr) gen.Columns { - return c.cronjobHistoryDo.Columns(cols...) -} - -func (c *cronjobHistory) 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 *cronjobHistory) fillFieldMap() { - c.fieldMap = make(map[string]field.Expr, 6) - c.fieldMap["id"] = c.ID - c.fieldMap["created_at"] = c.CreatedAt - c.fieldMap["updated_at"] = c.UpdatedAt - c.fieldMap["deleted_at"] = c.DeletedAt - c.fieldMap["status"] = c.Status - -} - -func (c cronjobHistory) clone(db *gorm.DB) cronjobHistory { - c.cronjobHistoryDo.ReplaceConnPool(db.Statement.ConnPool) - return c -} - -func (c cronjobHistory) replaceDB(db *gorm.DB) cronjobHistory { - c.cronjobHistoryDo.ReplaceDB(db) - return c -} - -type cronjobHistoryHasOneCronjob struct { - db *gorm.DB - - field.RelationField -} - -func (a cronjobHistoryHasOneCronjob) Where(conds ...field.Expr) *cronjobHistoryHasOneCronjob { - if len(conds) == 0 { - return &a - } - - exprs := make([]clause.Expression, 0, len(conds)) - for _, cond := range conds { - exprs = append(exprs, cond.BeCond().(clause.Expression)) - } - a.db = a.db.Clauses(clause.Where{Exprs: exprs}) - return &a -} - -func (a cronjobHistoryHasOneCronjob) WithContext(ctx context.Context) *cronjobHistoryHasOneCronjob { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a cronjobHistoryHasOneCronjob) Session(session *gorm.Session) *cronjobHistoryHasOneCronjob { - a.db = a.db.Session(session) - return &a -} - -func (a cronjobHistoryHasOneCronjob) Model(m *models.CronjobHistory) *cronjobHistoryHasOneCronjobTx { - return &cronjobHistoryHasOneCronjobTx{a.db.Model(m).Association(a.Name())} -} - -type cronjobHistoryHasOneCronjobTx struct{ tx *gorm.Association } - -func (a cronjobHistoryHasOneCronjobTx) Find() (result *models.Cronjob, err error) { - return result, a.tx.Find(&result) -} - -func (a cronjobHistoryHasOneCronjobTx) Append(values ...*models.Cronjob) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a cronjobHistoryHasOneCronjobTx) Replace(values ...*models.Cronjob) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a cronjobHistoryHasOneCronjobTx) Delete(values ...*models.Cronjob) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a cronjobHistoryHasOneCronjobTx) Clear() error { - return a.tx.Clear() -} - -func (a cronjobHistoryHasOneCronjobTx) Count() int64 { - return a.tx.Count() -} - -type cronjobHistoryDo struct{ gen.DO } - -type ICronjobHistoryDo interface { - gen.SubQuery - Debug() ICronjobHistoryDo - WithContext(ctx context.Context) ICronjobHistoryDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ICronjobHistoryDo - WriteDB() ICronjobHistoryDo - As(alias string) gen.Dao - Session(config *gorm.Session) ICronjobHistoryDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ICronjobHistoryDo - Not(conds ...gen.Condition) ICronjobHistoryDo - Or(conds ...gen.Condition) ICronjobHistoryDo - Select(conds ...field.Expr) ICronjobHistoryDo - Where(conds ...gen.Condition) ICronjobHistoryDo - Order(conds ...field.Expr) ICronjobHistoryDo - Distinct(cols ...field.Expr) ICronjobHistoryDo - Omit(cols ...field.Expr) ICronjobHistoryDo - Join(table schema.Tabler, on ...field.Expr) ICronjobHistoryDo - LeftJoin(table schema.Tabler, on ...field.Expr) ICronjobHistoryDo - RightJoin(table schema.Tabler, on ...field.Expr) ICronjobHistoryDo - Group(cols ...field.Expr) ICronjobHistoryDo - Having(conds ...gen.Condition) ICronjobHistoryDo - Limit(limit int) ICronjobHistoryDo - Offset(offset int) ICronjobHistoryDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ICronjobHistoryDo - Unscoped() ICronjobHistoryDo - Create(values ...*models.CronjobHistory) error - CreateInBatches(values []*models.CronjobHistory, batchSize int) error - Save(values ...*models.CronjobHistory) error - First() (*models.CronjobHistory, error) - Take() (*models.CronjobHistory, error) - Last() (*models.CronjobHistory, error) - Find() ([]*models.CronjobHistory, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.CronjobHistory, err error) - FindInBatches(result *[]*models.CronjobHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.CronjobHistory) (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) ICronjobHistoryDo - Assign(attrs ...field.AssignExpr) ICronjobHistoryDo - Joins(fields ...field.RelationField) ICronjobHistoryDo - Preload(fields ...field.RelationField) ICronjobHistoryDo - FirstOrInit() (*models.CronjobHistory, error) - FirstOrCreate() (*models.CronjobHistory, error) - FindByPage(offset int, limit int) (result []*models.CronjobHistory, 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) ICronjobHistoryDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (c cronjobHistoryDo) Debug() ICronjobHistoryDo { - return c.withDO(c.DO.Debug()) -} - -func (c cronjobHistoryDo) WithContext(ctx context.Context) ICronjobHistoryDo { - return c.withDO(c.DO.WithContext(ctx)) -} - -func (c cronjobHistoryDo) ReadDB() ICronjobHistoryDo { - return c.Clauses(dbresolver.Read) -} - -func (c cronjobHistoryDo) WriteDB() ICronjobHistoryDo { - return c.Clauses(dbresolver.Write) -} - -func (c cronjobHistoryDo) Session(config *gorm.Session) ICronjobHistoryDo { - return c.withDO(c.DO.Session(config)) -} - -func (c cronjobHistoryDo) Clauses(conds ...clause.Expression) ICronjobHistoryDo { - return c.withDO(c.DO.Clauses(conds...)) -} - -func (c cronjobHistoryDo) Returning(value interface{}, columns ...string) ICronjobHistoryDo { - return c.withDO(c.DO.Returning(value, columns...)) -} - -func (c cronjobHistoryDo) Not(conds ...gen.Condition) ICronjobHistoryDo { - return c.withDO(c.DO.Not(conds...)) -} - -func (c cronjobHistoryDo) Or(conds ...gen.Condition) ICronjobHistoryDo { - return c.withDO(c.DO.Or(conds...)) -} - -func (c cronjobHistoryDo) Select(conds ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.Select(conds...)) -} - -func (c cronjobHistoryDo) Where(conds ...gen.Condition) ICronjobHistoryDo { - return c.withDO(c.DO.Where(conds...)) -} - -func (c cronjobHistoryDo) Order(conds ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.Order(conds...)) -} - -func (c cronjobHistoryDo) Distinct(cols ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.Distinct(cols...)) -} - -func (c cronjobHistoryDo) Omit(cols ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.Omit(cols...)) -} - -func (c cronjobHistoryDo) Join(table schema.Tabler, on ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.Join(table, on...)) -} - -func (c cronjobHistoryDo) LeftJoin(table schema.Tabler, on ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.LeftJoin(table, on...)) -} - -func (c cronjobHistoryDo) RightJoin(table schema.Tabler, on ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.RightJoin(table, on...)) -} - -func (c cronjobHistoryDo) Group(cols ...field.Expr) ICronjobHistoryDo { - return c.withDO(c.DO.Group(cols...)) -} - -func (c cronjobHistoryDo) Having(conds ...gen.Condition) ICronjobHistoryDo { - return c.withDO(c.DO.Having(conds...)) -} - -func (c cronjobHistoryDo) Limit(limit int) ICronjobHistoryDo { - return c.withDO(c.DO.Limit(limit)) -} - -func (c cronjobHistoryDo) Offset(offset int) ICronjobHistoryDo { - return c.withDO(c.DO.Offset(offset)) -} - -func (c cronjobHistoryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ICronjobHistoryDo { - return c.withDO(c.DO.Scopes(funcs...)) -} - -func (c cronjobHistoryDo) Unscoped() ICronjobHistoryDo { - return c.withDO(c.DO.Unscoped()) -} - -func (c cronjobHistoryDo) Create(values ...*models.CronjobHistory) error { - if len(values) == 0 { - return nil - } - return c.DO.Create(values) -} - -func (c cronjobHistoryDo) CreateInBatches(values []*models.CronjobHistory, 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 cronjobHistoryDo) Save(values ...*models.CronjobHistory) error { - if len(values) == 0 { - return nil - } - return c.DO.Save(values) -} - -func (c cronjobHistoryDo) First() (*models.CronjobHistory, error) { - if result, err := c.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.CronjobHistory), nil - } -} - -func (c cronjobHistoryDo) Take() (*models.CronjobHistory, error) { - if result, err := c.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.CronjobHistory), nil - } -} - -func (c cronjobHistoryDo) Last() (*models.CronjobHistory, error) { - if result, err := c.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.CronjobHistory), nil - } -} - -func (c cronjobHistoryDo) Find() ([]*models.CronjobHistory, error) { - result, err := c.DO.Find() - return result.([]*models.CronjobHistory), err -} - -func (c cronjobHistoryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.CronjobHistory, err error) { - buf := make([]*models.CronjobHistory, 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 cronjobHistoryDo) FindInBatches(result *[]*models.CronjobHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return c.DO.FindInBatches(result, batchSize, fc) -} - -func (c cronjobHistoryDo) Attrs(attrs ...field.AssignExpr) ICronjobHistoryDo { - return c.withDO(c.DO.Attrs(attrs...)) -} - -func (c cronjobHistoryDo) Assign(attrs ...field.AssignExpr) ICronjobHistoryDo { - return c.withDO(c.DO.Assign(attrs...)) -} - -func (c cronjobHistoryDo) Joins(fields ...field.RelationField) ICronjobHistoryDo { - for _, _f := range fields { - c = *c.withDO(c.DO.Joins(_f)) - } - return &c -} - -func (c cronjobHistoryDo) Preload(fields ...field.RelationField) ICronjobHistoryDo { - for _, _f := range fields { - c = *c.withDO(c.DO.Preload(_f)) - } - return &c -} - -func (c cronjobHistoryDo) FirstOrInit() (*models.CronjobHistory, error) { - if result, err := c.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.CronjobHistory), nil - } -} - -func (c cronjobHistoryDo) FirstOrCreate() (*models.CronjobHistory, error) { - if result, err := c.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.CronjobHistory), nil - } -} - -func (c cronjobHistoryDo) FindByPage(offset int, limit int) (result []*models.CronjobHistory, 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 cronjobHistoryDo) 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 cronjobHistoryDo) Scan(result interface{}) (err error) { - return c.DO.Scan(result) -} - -func (c cronjobHistoryDo) Delete(models ...*models.CronjobHistory) (result gen.ResultInfo, err error) { - return c.DO.Delete(models) -} - -func (c *cronjobHistoryDo) withDO(do gen.Dao) *cronjobHistoryDo { - c.DO = *do.(*gen.DO) - return c -} diff --git a/internal/models/query/cronjobs.gen.go b/internal/models/query/cronjobs.gen.go deleted file mode 100644 index 27c1dc4..0000000 --- a/internal/models/query/cronjobs.gen.go +++ /dev/null @@ -1,416 +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" - - "code.tjo.space/mentos1386/zdravko/internal/models" -) - -func newCronjob(db *gorm.DB, opts ...gen.DOOption) cronjob { - _cronjob := cronjob{} - - _cronjob.cronjobDo.UseDB(db, opts...) - _cronjob.cronjobDo.UseModel(&models.Cronjob{}) - - tableName := _cronjob.cronjobDo.TableName() - _cronjob.ALL = field.NewAsterisk(tableName) - _cronjob.ID = field.NewUint(tableName, "id") - _cronjob.CreatedAt = field.NewTime(tableName, "created_at") - _cronjob.UpdatedAt = field.NewTime(tableName, "updated_at") - _cronjob.DeletedAt = field.NewField(tableName, "deleted_at") - _cronjob.Slug = field.NewString(tableName, "slug") - _cronjob.Name = field.NewString(tableName, "name") - _cronjob.Schedule = field.NewString(tableName, "schedule") - _cronjob.Buffer = field.NewInt(tableName, "buffer") - - _cronjob.fillFieldMap() - - return _cronjob -} - -type cronjob struct { - cronjobDo cronjobDo - - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Slug field.String - Name field.String - Schedule field.String - Buffer field.Int - - fieldMap map[string]field.Expr -} - -func (c cronjob) Table(newTableName string) *cronjob { - c.cronjobDo.UseTable(newTableName) - return c.updateTableName(newTableName) -} - -func (c cronjob) As(alias string) *cronjob { - c.cronjobDo.DO = *(c.cronjobDo.As(alias).(*gen.DO)) - return c.updateTableName(alias) -} - -func (c *cronjob) updateTableName(table string) *cronjob { - c.ALL = field.NewAsterisk(table) - c.ID = field.NewUint(table, "id") - c.CreatedAt = field.NewTime(table, "created_at") - c.UpdatedAt = field.NewTime(table, "updated_at") - c.DeletedAt = field.NewField(table, "deleted_at") - c.Slug = field.NewString(table, "slug") - c.Name = field.NewString(table, "name") - c.Schedule = field.NewString(table, "schedule") - c.Buffer = field.NewInt(table, "buffer") - - c.fillFieldMap() - - return c -} - -func (c *cronjob) WithContext(ctx context.Context) ICronjobDo { return c.cronjobDo.WithContext(ctx) } - -func (c cronjob) TableName() string { return c.cronjobDo.TableName() } - -func (c cronjob) Alias() string { return c.cronjobDo.Alias() } - -func (c cronjob) Columns(cols ...field.Expr) gen.Columns { return c.cronjobDo.Columns(cols...) } - -func (c *cronjob) 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 *cronjob) fillFieldMap() { - c.fieldMap = make(map[string]field.Expr, 8) - c.fieldMap["id"] = c.ID - c.fieldMap["created_at"] = c.CreatedAt - c.fieldMap["updated_at"] = c.UpdatedAt - c.fieldMap["deleted_at"] = c.DeletedAt - c.fieldMap["slug"] = c.Slug - c.fieldMap["name"] = c.Name - c.fieldMap["schedule"] = c.Schedule - c.fieldMap["buffer"] = c.Buffer -} - -func (c cronjob) clone(db *gorm.DB) cronjob { - c.cronjobDo.ReplaceConnPool(db.Statement.ConnPool) - return c -} - -func (c cronjob) replaceDB(db *gorm.DB) cronjob { - c.cronjobDo.ReplaceDB(db) - return c -} - -type cronjobDo struct{ gen.DO } - -type ICronjobDo interface { - gen.SubQuery - Debug() ICronjobDo - WithContext(ctx context.Context) ICronjobDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() ICronjobDo - WriteDB() ICronjobDo - As(alias string) gen.Dao - Session(config *gorm.Session) ICronjobDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) ICronjobDo - Not(conds ...gen.Condition) ICronjobDo - Or(conds ...gen.Condition) ICronjobDo - Select(conds ...field.Expr) ICronjobDo - Where(conds ...gen.Condition) ICronjobDo - Order(conds ...field.Expr) ICronjobDo - Distinct(cols ...field.Expr) ICronjobDo - Omit(cols ...field.Expr) ICronjobDo - Join(table schema.Tabler, on ...field.Expr) ICronjobDo - LeftJoin(table schema.Tabler, on ...field.Expr) ICronjobDo - RightJoin(table schema.Tabler, on ...field.Expr) ICronjobDo - Group(cols ...field.Expr) ICronjobDo - Having(conds ...gen.Condition) ICronjobDo - Limit(limit int) ICronjobDo - Offset(offset int) ICronjobDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) ICronjobDo - Unscoped() ICronjobDo - Create(values ...*models.Cronjob) error - CreateInBatches(values []*models.Cronjob, batchSize int) error - Save(values ...*models.Cronjob) error - First() (*models.Cronjob, error) - Take() (*models.Cronjob, error) - Last() (*models.Cronjob, error) - Find() ([]*models.Cronjob, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Cronjob, err error) - FindInBatches(result *[]*models.Cronjob, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.Cronjob) (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) ICronjobDo - Assign(attrs ...field.AssignExpr) ICronjobDo - Joins(fields ...field.RelationField) ICronjobDo - Preload(fields ...field.RelationField) ICronjobDo - FirstOrInit() (*models.Cronjob, error) - FirstOrCreate() (*models.Cronjob, error) - FindByPage(offset int, limit int) (result []*models.Cronjob, 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) ICronjobDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (c cronjobDo) Debug() ICronjobDo { - return c.withDO(c.DO.Debug()) -} - -func (c cronjobDo) WithContext(ctx context.Context) ICronjobDo { - return c.withDO(c.DO.WithContext(ctx)) -} - -func (c cronjobDo) ReadDB() ICronjobDo { - return c.Clauses(dbresolver.Read) -} - -func (c cronjobDo) WriteDB() ICronjobDo { - return c.Clauses(dbresolver.Write) -} - -func (c cronjobDo) Session(config *gorm.Session) ICronjobDo { - return c.withDO(c.DO.Session(config)) -} - -func (c cronjobDo) Clauses(conds ...clause.Expression) ICronjobDo { - return c.withDO(c.DO.Clauses(conds...)) -} - -func (c cronjobDo) Returning(value interface{}, columns ...string) ICronjobDo { - return c.withDO(c.DO.Returning(value, columns...)) -} - -func (c cronjobDo) Not(conds ...gen.Condition) ICronjobDo { - return c.withDO(c.DO.Not(conds...)) -} - -func (c cronjobDo) Or(conds ...gen.Condition) ICronjobDo { - return c.withDO(c.DO.Or(conds...)) -} - -func (c cronjobDo) Select(conds ...field.Expr) ICronjobDo { - return c.withDO(c.DO.Select(conds...)) -} - -func (c cronjobDo) Where(conds ...gen.Condition) ICronjobDo { - return c.withDO(c.DO.Where(conds...)) -} - -func (c cronjobDo) Order(conds ...field.Expr) ICronjobDo { - return c.withDO(c.DO.Order(conds...)) -} - -func (c cronjobDo) Distinct(cols ...field.Expr) ICronjobDo { - return c.withDO(c.DO.Distinct(cols...)) -} - -func (c cronjobDo) Omit(cols ...field.Expr) ICronjobDo { - return c.withDO(c.DO.Omit(cols...)) -} - -func (c cronjobDo) Join(table schema.Tabler, on ...field.Expr) ICronjobDo { - return c.withDO(c.DO.Join(table, on...)) -} - -func (c cronjobDo) LeftJoin(table schema.Tabler, on ...field.Expr) ICronjobDo { - return c.withDO(c.DO.LeftJoin(table, on...)) -} - -func (c cronjobDo) RightJoin(table schema.Tabler, on ...field.Expr) ICronjobDo { - return c.withDO(c.DO.RightJoin(table, on...)) -} - -func (c cronjobDo) Group(cols ...field.Expr) ICronjobDo { - return c.withDO(c.DO.Group(cols...)) -} - -func (c cronjobDo) Having(conds ...gen.Condition) ICronjobDo { - return c.withDO(c.DO.Having(conds...)) -} - -func (c cronjobDo) Limit(limit int) ICronjobDo { - return c.withDO(c.DO.Limit(limit)) -} - -func (c cronjobDo) Offset(offset int) ICronjobDo { - return c.withDO(c.DO.Offset(offset)) -} - -func (c cronjobDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ICronjobDo { - return c.withDO(c.DO.Scopes(funcs...)) -} - -func (c cronjobDo) Unscoped() ICronjobDo { - return c.withDO(c.DO.Unscoped()) -} - -func (c cronjobDo) Create(values ...*models.Cronjob) error { - if len(values) == 0 { - return nil - } - return c.DO.Create(values) -} - -func (c cronjobDo) CreateInBatches(values []*models.Cronjob, 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 cronjobDo) Save(values ...*models.Cronjob) error { - if len(values) == 0 { - return nil - } - return c.DO.Save(values) -} - -func (c cronjobDo) First() (*models.Cronjob, error) { - if result, err := c.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.Cronjob), nil - } -} - -func (c cronjobDo) Take() (*models.Cronjob, error) { - if result, err := c.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.Cronjob), nil - } -} - -func (c cronjobDo) Last() (*models.Cronjob, error) { - if result, err := c.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.Cronjob), nil - } -} - -func (c cronjobDo) Find() ([]*models.Cronjob, error) { - result, err := c.DO.Find() - return result.([]*models.Cronjob), err -} - -func (c cronjobDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Cronjob, err error) { - buf := make([]*models.Cronjob, 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 cronjobDo) FindInBatches(result *[]*models.Cronjob, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return c.DO.FindInBatches(result, batchSize, fc) -} - -func (c cronjobDo) Attrs(attrs ...field.AssignExpr) ICronjobDo { - return c.withDO(c.DO.Attrs(attrs...)) -} - -func (c cronjobDo) Assign(attrs ...field.AssignExpr) ICronjobDo { - return c.withDO(c.DO.Assign(attrs...)) -} - -func (c cronjobDo) Joins(fields ...field.RelationField) ICronjobDo { - for _, _f := range fields { - c = *c.withDO(c.DO.Joins(_f)) - } - return &c -} - -func (c cronjobDo) Preload(fields ...field.RelationField) ICronjobDo { - for _, _f := range fields { - c = *c.withDO(c.DO.Preload(_f)) - } - return &c -} - -func (c cronjobDo) FirstOrInit() (*models.Cronjob, error) { - if result, err := c.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.Cronjob), nil - } -} - -func (c cronjobDo) FirstOrCreate() (*models.Cronjob, error) { - if result, err := c.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.Cronjob), nil - } -} - -func (c cronjobDo) FindByPage(offset int, limit int) (result []*models.Cronjob, 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 cronjobDo) 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 cronjobDo) Scan(result interface{}) (err error) { - return c.DO.Scan(result) -} - -func (c cronjobDo) Delete(models ...*models.Cronjob) (result gen.ResultInfo, err error) { - return c.DO.Delete(models) -} - -func (c *cronjobDo) withDO(do gen.Dao) *cronjobDo { - c.DO = *do.(*gen.DO) - return c -} diff --git a/internal/models/query/gen.go b/internal/models/query/gen.go index fd0f308..ce04cee 100644 --- a/internal/models/query/gen.go +++ b/internal/models/query/gen.go @@ -17,45 +17,37 @@ import ( var ( Q = new(Query) - Cronjob *cronjob - CronjobHistory *cronjobHistory Monitor *monitor MonitorHistory *monitorHistory OAuth2State *oAuth2State - Worker *worker + WorkerGroup *workerGroup ) func SetDefault(db *gorm.DB, opts ...gen.DOOption) { *Q = *Use(db, opts...) - Cronjob = &Q.Cronjob - CronjobHistory = &Q.CronjobHistory Monitor = &Q.Monitor MonitorHistory = &Q.MonitorHistory OAuth2State = &Q.OAuth2State - Worker = &Q.Worker + WorkerGroup = &Q.WorkerGroup } func Use(db *gorm.DB, opts ...gen.DOOption) *Query { return &Query{ db: db, - Cronjob: newCronjob(db, opts...), - CronjobHistory: newCronjobHistory(db, opts...), Monitor: newMonitor(db, opts...), MonitorHistory: newMonitorHistory(db, opts...), OAuth2State: newOAuth2State(db, opts...), - Worker: newWorker(db, opts...), + WorkerGroup: newWorkerGroup(db, opts...), } } type Query struct { db *gorm.DB - Cronjob cronjob - CronjobHistory cronjobHistory Monitor monitor MonitorHistory monitorHistory OAuth2State oAuth2State - Worker worker + WorkerGroup workerGroup } func (q *Query) Available() bool { return q.db != nil } @@ -63,12 +55,10 @@ func (q *Query) Available() bool { return q.db != nil } func (q *Query) clone(db *gorm.DB) *Query { return &Query{ db: db, - Cronjob: q.Cronjob.clone(db), - CronjobHistory: q.CronjobHistory.clone(db), Monitor: q.Monitor.clone(db), MonitorHistory: q.MonitorHistory.clone(db), OAuth2State: q.OAuth2State.clone(db), - Worker: q.Worker.clone(db), + WorkerGroup: q.WorkerGroup.clone(db), } } @@ -83,32 +73,26 @@ func (q *Query) WriteDB() *Query { func (q *Query) ReplaceDB(db *gorm.DB) *Query { return &Query{ db: db, - Cronjob: q.Cronjob.replaceDB(db), - CronjobHistory: q.CronjobHistory.replaceDB(db), Monitor: q.Monitor.replaceDB(db), MonitorHistory: q.MonitorHistory.replaceDB(db), OAuth2State: q.OAuth2State.replaceDB(db), - Worker: q.Worker.replaceDB(db), + WorkerGroup: q.WorkerGroup.replaceDB(db), } } type queryCtx struct { - Cronjob ICronjobDo - CronjobHistory ICronjobHistoryDo Monitor IMonitorDo MonitorHistory IMonitorHistoryDo OAuth2State IOAuth2StateDo - Worker IWorkerDo + WorkerGroup IWorkerGroupDo } func (q *Query) WithContext(ctx context.Context) *queryCtx { return &queryCtx{ - Cronjob: q.Cronjob.WithContext(ctx), - CronjobHistory: q.CronjobHistory.WithContext(ctx), Monitor: q.Monitor.WithContext(ctx), MonitorHistory: q.MonitorHistory.WithContext(ctx), OAuth2State: q.OAuth2State.WithContext(ctx), - Worker: q.Worker.WithContext(ctx), + WorkerGroup: q.WorkerGroup.WithContext(ctx), } } diff --git a/internal/models/query/monitors.gen.go b/internal/models/query/monitors.gen.go index 75729b2..294a520 100644 --- a/internal/models/query/monitors.gen.go +++ b/internal/models/query/monitors.gen.go @@ -34,7 +34,6 @@ func newMonitor(db *gorm.DB, opts ...gen.DOOption) monitor { _monitor.Slug = field.NewString(tableName, "slug") _monitor.Name = field.NewString(tableName, "name") _monitor.Schedule = field.NewString(tableName, "schedule") - _monitor.WorkerGroups = field.NewField(tableName, "worker_groups") _monitor.Script = field.NewString(tableName, "script") _monitor.History = monitorHasManyHistory{ db: db.Session(&gorm.Session{}), @@ -42,6 +41,33 @@ func newMonitor(db *gorm.DB, opts ...gen.DOOption) monitor { RelationField: field.NewRelation("History", "models.MonitorHistory"), } + _monitor.WorkerGroups = monitorManyToManyWorkerGroups{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("WorkerGroups", "models.WorkerGroup"), + Monitors: struct { + field.RelationField + History struct { + field.RelationField + } + WorkerGroups struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("WorkerGroups.Monitors", "models.Monitor"), + History: struct { + field.RelationField + }{ + RelationField: field.NewRelation("WorkerGroups.Monitors.History", "models.MonitorHistory"), + }, + WorkerGroups: struct { + field.RelationField + }{ + RelationField: field.NewRelation("WorkerGroups.Monitors.WorkerGroups", "models.WorkerGroup"), + }, + }, + } + _monitor.fillFieldMap() return _monitor @@ -50,17 +76,18 @@ func newMonitor(db *gorm.DB, opts ...gen.DOOption) monitor { type monitor struct { monitorDo monitorDo - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Slug field.String - Name field.String - Schedule field.String - WorkerGroups field.Field - Script field.String - History monitorHasManyHistory + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + Slug field.String + Name field.String + Schedule field.String + Script field.String + History monitorHasManyHistory + + WorkerGroups monitorManyToManyWorkerGroups fieldMap map[string]field.Expr } @@ -84,7 +111,6 @@ func (m *monitor) updateTableName(table string) *monitor { m.Slug = field.NewString(table, "slug") m.Name = field.NewString(table, "name") m.Schedule = field.NewString(table, "schedule") - m.WorkerGroups = field.NewField(table, "worker_groups") m.Script = field.NewString(table, "script") m.fillFieldMap() @@ -118,7 +144,6 @@ func (m *monitor) fillFieldMap() { m.fieldMap["slug"] = m.Slug m.fieldMap["name"] = m.Name m.fieldMap["schedule"] = m.Schedule - m.fieldMap["worker_groups"] = m.WorkerGroups m.fieldMap["script"] = m.Script } @@ -204,6 +229,87 @@ func (a monitorHasManyHistoryTx) Count() int64 { return a.tx.Count() } +type monitorManyToManyWorkerGroups struct { + db *gorm.DB + + field.RelationField + + Monitors struct { + field.RelationField + History struct { + field.RelationField + } + WorkerGroups struct { + field.RelationField + } + } +} + +func (a monitorManyToManyWorkerGroups) Where(conds ...field.Expr) *monitorManyToManyWorkerGroups { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a monitorManyToManyWorkerGroups) WithContext(ctx context.Context) *monitorManyToManyWorkerGroups { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a monitorManyToManyWorkerGroups) Session(session *gorm.Session) *monitorManyToManyWorkerGroups { + a.db = a.db.Session(session) + return &a +} + +func (a monitorManyToManyWorkerGroups) Model(m *models.Monitor) *monitorManyToManyWorkerGroupsTx { + return &monitorManyToManyWorkerGroupsTx{a.db.Model(m).Association(a.Name())} +} + +type monitorManyToManyWorkerGroupsTx struct{ tx *gorm.Association } + +func (a monitorManyToManyWorkerGroupsTx) Find() (result []*models.WorkerGroup, err error) { + return result, a.tx.Find(&result) +} + +func (a monitorManyToManyWorkerGroupsTx) Append(values ...*models.WorkerGroup) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a monitorManyToManyWorkerGroupsTx) Replace(values ...*models.WorkerGroup) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a monitorManyToManyWorkerGroupsTx) Delete(values ...*models.WorkerGroup) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a monitorManyToManyWorkerGroupsTx) Clear() error { + return a.tx.Clear() +} + +func (a monitorManyToManyWorkerGroupsTx) Count() int64 { + return a.tx.Count() +} + type monitorDo struct{ gen.DO } type IMonitorDo interface { diff --git a/internal/models/query/worker_groups.gen.go b/internal/models/query/worker_groups.gen.go new file mode 100644 index 0000000..d14f9dc --- /dev/null +++ b/internal/models/query/worker_groups.gen.go @@ -0,0 +1,516 @@ +// 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" + + "code.tjo.space/mentos1386/zdravko/internal/models" +) + +func newWorkerGroup(db *gorm.DB, opts ...gen.DOOption) workerGroup { + _workerGroup := workerGroup{} + + _workerGroup.workerGroupDo.UseDB(db, opts...) + _workerGroup.workerGroupDo.UseModel(&models.WorkerGroup{}) + + tableName := _workerGroup.workerGroupDo.TableName() + _workerGroup.ALL = field.NewAsterisk(tableName) + _workerGroup.ID = field.NewUint(tableName, "id") + _workerGroup.CreatedAt = field.NewTime(tableName, "created_at") + _workerGroup.UpdatedAt = field.NewTime(tableName, "updated_at") + _workerGroup.DeletedAt = field.NewField(tableName, "deleted_at") + _workerGroup.Name = field.NewString(tableName, "name") + _workerGroup.Slug = field.NewString(tableName, "slug") + _workerGroup.Monitors = workerGroupManyToManyMonitors{ + db: db.Session(&gorm.Session{}), + + RelationField: field.NewRelation("Monitors", "models.Monitor"), + History: struct { + field.RelationField + }{ + RelationField: field.NewRelation("Monitors.History", "models.MonitorHistory"), + }, + WorkerGroups: struct { + field.RelationField + Monitors struct { + field.RelationField + } + }{ + RelationField: field.NewRelation("Monitors.WorkerGroups", "models.WorkerGroup"), + Monitors: struct { + field.RelationField + }{ + RelationField: field.NewRelation("Monitors.WorkerGroups.Monitors", "models.Monitor"), + }, + }, + } + + _workerGroup.fillFieldMap() + + return _workerGroup +} + +type workerGroup struct { + workerGroupDo workerGroupDo + + ALL field.Asterisk + ID field.Uint + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + Name field.String + Slug field.String + Monitors workerGroupManyToManyMonitors + + fieldMap map[string]field.Expr +} + +func (w workerGroup) Table(newTableName string) *workerGroup { + w.workerGroupDo.UseTable(newTableName) + return w.updateTableName(newTableName) +} + +func (w workerGroup) As(alias string) *workerGroup { + w.workerGroupDo.DO = *(w.workerGroupDo.As(alias).(*gen.DO)) + return w.updateTableName(alias) +} + +func (w *workerGroup) updateTableName(table string) *workerGroup { + w.ALL = field.NewAsterisk(table) + w.ID = field.NewUint(table, "id") + w.CreatedAt = field.NewTime(table, "created_at") + w.UpdatedAt = field.NewTime(table, "updated_at") + w.DeletedAt = field.NewField(table, "deleted_at") + w.Name = field.NewString(table, "name") + w.Slug = field.NewString(table, "slug") + + w.fillFieldMap() + + return w +} + +func (w *workerGroup) WithContext(ctx context.Context) IWorkerGroupDo { + return w.workerGroupDo.WithContext(ctx) +} + +func (w workerGroup) TableName() string { return w.workerGroupDo.TableName() } + +func (w workerGroup) Alias() string { return w.workerGroupDo.Alias() } + +func (w workerGroup) Columns(cols ...field.Expr) gen.Columns { return w.workerGroupDo.Columns(cols...) } + +func (w *workerGroup) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := w.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (w *workerGroup) fillFieldMap() { + w.fieldMap = make(map[string]field.Expr, 7) + w.fieldMap["id"] = w.ID + w.fieldMap["created_at"] = w.CreatedAt + w.fieldMap["updated_at"] = w.UpdatedAt + w.fieldMap["deleted_at"] = w.DeletedAt + w.fieldMap["name"] = w.Name + w.fieldMap["slug"] = w.Slug + +} + +func (w workerGroup) clone(db *gorm.DB) workerGroup { + w.workerGroupDo.ReplaceConnPool(db.Statement.ConnPool) + return w +} + +func (w workerGroup) replaceDB(db *gorm.DB) workerGroup { + w.workerGroupDo.ReplaceDB(db) + return w +} + +type workerGroupManyToManyMonitors struct { + db *gorm.DB + + field.RelationField + + History struct { + field.RelationField + } + WorkerGroups struct { + field.RelationField + Monitors struct { + field.RelationField + } + } +} + +func (a workerGroupManyToManyMonitors) Where(conds ...field.Expr) *workerGroupManyToManyMonitors { + if len(conds) == 0 { + return &a + } + + exprs := make([]clause.Expression, 0, len(conds)) + for _, cond := range conds { + exprs = append(exprs, cond.BeCond().(clause.Expression)) + } + a.db = a.db.Clauses(clause.Where{Exprs: exprs}) + return &a +} + +func (a workerGroupManyToManyMonitors) WithContext(ctx context.Context) *workerGroupManyToManyMonitors { + a.db = a.db.WithContext(ctx) + return &a +} + +func (a workerGroupManyToManyMonitors) Session(session *gorm.Session) *workerGroupManyToManyMonitors { + a.db = a.db.Session(session) + return &a +} + +func (a workerGroupManyToManyMonitors) Model(m *models.WorkerGroup) *workerGroupManyToManyMonitorsTx { + return &workerGroupManyToManyMonitorsTx{a.db.Model(m).Association(a.Name())} +} + +type workerGroupManyToManyMonitorsTx struct{ tx *gorm.Association } + +func (a workerGroupManyToManyMonitorsTx) Find() (result []*models.Monitor, err error) { + return result, a.tx.Find(&result) +} + +func (a workerGroupManyToManyMonitorsTx) Append(values ...*models.Monitor) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Append(targetValues...) +} + +func (a workerGroupManyToManyMonitorsTx) Replace(values ...*models.Monitor) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Replace(targetValues...) +} + +func (a workerGroupManyToManyMonitorsTx) Delete(values ...*models.Monitor) (err error) { + targetValues := make([]interface{}, len(values)) + for i, v := range values { + targetValues[i] = v + } + return a.tx.Delete(targetValues...) +} + +func (a workerGroupManyToManyMonitorsTx) Clear() error { + return a.tx.Clear() +} + +func (a workerGroupManyToManyMonitorsTx) Count() int64 { + return a.tx.Count() +} + +type workerGroupDo struct{ gen.DO } + +type IWorkerGroupDo interface { + gen.SubQuery + Debug() IWorkerGroupDo + WithContext(ctx context.Context) IWorkerGroupDo + WithResult(fc func(tx gen.Dao)) gen.ResultInfo + ReplaceDB(db *gorm.DB) + ReadDB() IWorkerGroupDo + WriteDB() IWorkerGroupDo + As(alias string) gen.Dao + Session(config *gorm.Session) IWorkerGroupDo + Columns(cols ...field.Expr) gen.Columns + Clauses(conds ...clause.Expression) IWorkerGroupDo + Not(conds ...gen.Condition) IWorkerGroupDo + Or(conds ...gen.Condition) IWorkerGroupDo + Select(conds ...field.Expr) IWorkerGroupDo + Where(conds ...gen.Condition) IWorkerGroupDo + Order(conds ...field.Expr) IWorkerGroupDo + Distinct(cols ...field.Expr) IWorkerGroupDo + Omit(cols ...field.Expr) IWorkerGroupDo + Join(table schema.Tabler, on ...field.Expr) IWorkerGroupDo + LeftJoin(table schema.Tabler, on ...field.Expr) IWorkerGroupDo + RightJoin(table schema.Tabler, on ...field.Expr) IWorkerGroupDo + Group(cols ...field.Expr) IWorkerGroupDo + Having(conds ...gen.Condition) IWorkerGroupDo + Limit(limit int) IWorkerGroupDo + Offset(offset int) IWorkerGroupDo + Count() (count int64, err error) + Scopes(funcs ...func(gen.Dao) gen.Dao) IWorkerGroupDo + Unscoped() IWorkerGroupDo + Create(values ...*models.WorkerGroup) error + CreateInBatches(values []*models.WorkerGroup, batchSize int) error + Save(values ...*models.WorkerGroup) error + First() (*models.WorkerGroup, error) + Take() (*models.WorkerGroup, error) + Last() (*models.WorkerGroup, error) + Find() ([]*models.WorkerGroup, error) + FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.WorkerGroup, err error) + FindInBatches(result *[]*models.WorkerGroup, batchSize int, fc func(tx gen.Dao, batch int) error) error + Pluck(column field.Expr, dest interface{}) error + Delete(...*models.WorkerGroup) (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) IWorkerGroupDo + Assign(attrs ...field.AssignExpr) IWorkerGroupDo + Joins(fields ...field.RelationField) IWorkerGroupDo + Preload(fields ...field.RelationField) IWorkerGroupDo + FirstOrInit() (*models.WorkerGroup, error) + FirstOrCreate() (*models.WorkerGroup, error) + FindByPage(offset int, limit int) (result []*models.WorkerGroup, 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) IWorkerGroupDo + UnderlyingDB() *gorm.DB + schema.Tabler +} + +func (w workerGroupDo) Debug() IWorkerGroupDo { + return w.withDO(w.DO.Debug()) +} + +func (w workerGroupDo) WithContext(ctx context.Context) IWorkerGroupDo { + return w.withDO(w.DO.WithContext(ctx)) +} + +func (w workerGroupDo) ReadDB() IWorkerGroupDo { + return w.Clauses(dbresolver.Read) +} + +func (w workerGroupDo) WriteDB() IWorkerGroupDo { + return w.Clauses(dbresolver.Write) +} + +func (w workerGroupDo) Session(config *gorm.Session) IWorkerGroupDo { + return w.withDO(w.DO.Session(config)) +} + +func (w workerGroupDo) Clauses(conds ...clause.Expression) IWorkerGroupDo { + return w.withDO(w.DO.Clauses(conds...)) +} + +func (w workerGroupDo) Returning(value interface{}, columns ...string) IWorkerGroupDo { + return w.withDO(w.DO.Returning(value, columns...)) +} + +func (w workerGroupDo) Not(conds ...gen.Condition) IWorkerGroupDo { + return w.withDO(w.DO.Not(conds...)) +} + +func (w workerGroupDo) Or(conds ...gen.Condition) IWorkerGroupDo { + return w.withDO(w.DO.Or(conds...)) +} + +func (w workerGroupDo) Select(conds ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.Select(conds...)) +} + +func (w workerGroupDo) Where(conds ...gen.Condition) IWorkerGroupDo { + return w.withDO(w.DO.Where(conds...)) +} + +func (w workerGroupDo) Order(conds ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.Order(conds...)) +} + +func (w workerGroupDo) Distinct(cols ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.Distinct(cols...)) +} + +func (w workerGroupDo) Omit(cols ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.Omit(cols...)) +} + +func (w workerGroupDo) Join(table schema.Tabler, on ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.Join(table, on...)) +} + +func (w workerGroupDo) LeftJoin(table schema.Tabler, on ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.LeftJoin(table, on...)) +} + +func (w workerGroupDo) RightJoin(table schema.Tabler, on ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.RightJoin(table, on...)) +} + +func (w workerGroupDo) Group(cols ...field.Expr) IWorkerGroupDo { + return w.withDO(w.DO.Group(cols...)) +} + +func (w workerGroupDo) Having(conds ...gen.Condition) IWorkerGroupDo { + return w.withDO(w.DO.Having(conds...)) +} + +func (w workerGroupDo) Limit(limit int) IWorkerGroupDo { + return w.withDO(w.DO.Limit(limit)) +} + +func (w workerGroupDo) Offset(offset int) IWorkerGroupDo { + return w.withDO(w.DO.Offset(offset)) +} + +func (w workerGroupDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IWorkerGroupDo { + return w.withDO(w.DO.Scopes(funcs...)) +} + +func (w workerGroupDo) Unscoped() IWorkerGroupDo { + return w.withDO(w.DO.Unscoped()) +} + +func (w workerGroupDo) Create(values ...*models.WorkerGroup) error { + if len(values) == 0 { + return nil + } + return w.DO.Create(values) +} + +func (w workerGroupDo) CreateInBatches(values []*models.WorkerGroup, batchSize int) error { + return w.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 (w workerGroupDo) Save(values ...*models.WorkerGroup) error { + if len(values) == 0 { + return nil + } + return w.DO.Save(values) +} + +func (w workerGroupDo) First() (*models.WorkerGroup, error) { + if result, err := w.DO.First(); err != nil { + return nil, err + } else { + return result.(*models.WorkerGroup), nil + } +} + +func (w workerGroupDo) Take() (*models.WorkerGroup, error) { + if result, err := w.DO.Take(); err != nil { + return nil, err + } else { + return result.(*models.WorkerGroup), nil + } +} + +func (w workerGroupDo) Last() (*models.WorkerGroup, error) { + if result, err := w.DO.Last(); err != nil { + return nil, err + } else { + return result.(*models.WorkerGroup), nil + } +} + +func (w workerGroupDo) Find() ([]*models.WorkerGroup, error) { + result, err := w.DO.Find() + return result.([]*models.WorkerGroup), err +} + +func (w workerGroupDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.WorkerGroup, err error) { + buf := make([]*models.WorkerGroup, 0, batchSize) + err = w.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 (w workerGroupDo) FindInBatches(result *[]*models.WorkerGroup, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return w.DO.FindInBatches(result, batchSize, fc) +} + +func (w workerGroupDo) Attrs(attrs ...field.AssignExpr) IWorkerGroupDo { + return w.withDO(w.DO.Attrs(attrs...)) +} + +func (w workerGroupDo) Assign(attrs ...field.AssignExpr) IWorkerGroupDo { + return w.withDO(w.DO.Assign(attrs...)) +} + +func (w workerGroupDo) Joins(fields ...field.RelationField) IWorkerGroupDo { + for _, _f := range fields { + w = *w.withDO(w.DO.Joins(_f)) + } + return &w +} + +func (w workerGroupDo) Preload(fields ...field.RelationField) IWorkerGroupDo { + for _, _f := range fields { + w = *w.withDO(w.DO.Preload(_f)) + } + return &w +} + +func (w workerGroupDo) FirstOrInit() (*models.WorkerGroup, error) { + if result, err := w.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*models.WorkerGroup), nil + } +} + +func (w workerGroupDo) FirstOrCreate() (*models.WorkerGroup, error) { + if result, err := w.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*models.WorkerGroup), nil + } +} + +func (w workerGroupDo) FindByPage(offset int, limit int) (result []*models.WorkerGroup, count int64, err error) { + result, err = w.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 = w.Offset(-1).Limit(-1).Count() + return +} + +func (w workerGroupDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = w.Count() + if err != nil { + return + } + + err = w.Offset(offset).Limit(limit).Scan(result) + return +} + +func (w workerGroupDo) Scan(result interface{}) (err error) { + return w.DO.Scan(result) +} + +func (w workerGroupDo) Delete(models ...*models.WorkerGroup) (result gen.ResultInfo, err error) { + return w.DO.Delete(models) +} + +func (w *workerGroupDo) withDO(do gen.Dao) *workerGroupDo { + w.DO = *do.(*gen.DO) + return w +} diff --git a/internal/models/query/workers.gen.go b/internal/models/query/workers.gen.go deleted file mode 100644 index 046d81a..0000000 --- a/internal/models/query/workers.gen.go +++ /dev/null @@ -1,416 +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" - - "code.tjo.space/mentos1386/zdravko/internal/models" -) - -func newWorker(db *gorm.DB, opts ...gen.DOOption) worker { - _worker := worker{} - - _worker.workerDo.UseDB(db, opts...) - _worker.workerDo.UseModel(&models.Worker{}) - - tableName := _worker.workerDo.TableName() - _worker.ALL = field.NewAsterisk(tableName) - _worker.ID = field.NewUint(tableName, "id") - _worker.CreatedAt = field.NewTime(tableName, "created_at") - _worker.UpdatedAt = field.NewTime(tableName, "updated_at") - _worker.DeletedAt = field.NewField(tableName, "deleted_at") - _worker.Name = field.NewString(tableName, "name") - _worker.Slug = field.NewString(tableName, "slug") - _worker.Group = field.NewString(tableName, "group") - _worker.Status = field.NewString(tableName, "status") - - _worker.fillFieldMap() - - return _worker -} - -type worker struct { - workerDo workerDo - - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Name field.String - Slug field.String - Group field.String - Status field.String - - fieldMap map[string]field.Expr -} - -func (w worker) Table(newTableName string) *worker { - w.workerDo.UseTable(newTableName) - return w.updateTableName(newTableName) -} - -func (w worker) As(alias string) *worker { - w.workerDo.DO = *(w.workerDo.As(alias).(*gen.DO)) - return w.updateTableName(alias) -} - -func (w *worker) updateTableName(table string) *worker { - w.ALL = field.NewAsterisk(table) - w.ID = field.NewUint(table, "id") - w.CreatedAt = field.NewTime(table, "created_at") - w.UpdatedAt = field.NewTime(table, "updated_at") - w.DeletedAt = field.NewField(table, "deleted_at") - w.Name = field.NewString(table, "name") - w.Slug = field.NewString(table, "slug") - w.Group = field.NewString(table, "group") - w.Status = field.NewString(table, "status") - - w.fillFieldMap() - - return w -} - -func (w *worker) WithContext(ctx context.Context) IWorkerDo { return w.workerDo.WithContext(ctx) } - -func (w worker) TableName() string { return w.workerDo.TableName() } - -func (w worker) Alias() string { return w.workerDo.Alias() } - -func (w worker) Columns(cols ...field.Expr) gen.Columns { return w.workerDo.Columns(cols...) } - -func (w *worker) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := w.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (w *worker) fillFieldMap() { - w.fieldMap = make(map[string]field.Expr, 8) - w.fieldMap["id"] = w.ID - w.fieldMap["created_at"] = w.CreatedAt - w.fieldMap["updated_at"] = w.UpdatedAt - w.fieldMap["deleted_at"] = w.DeletedAt - w.fieldMap["name"] = w.Name - w.fieldMap["slug"] = w.Slug - w.fieldMap["group"] = w.Group - w.fieldMap["status"] = w.Status -} - -func (w worker) clone(db *gorm.DB) worker { - w.workerDo.ReplaceConnPool(db.Statement.ConnPool) - return w -} - -func (w worker) replaceDB(db *gorm.DB) worker { - w.workerDo.ReplaceDB(db) - return w -} - -type workerDo struct{ gen.DO } - -type IWorkerDo interface { - gen.SubQuery - Debug() IWorkerDo - WithContext(ctx context.Context) IWorkerDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IWorkerDo - WriteDB() IWorkerDo - As(alias string) gen.Dao - Session(config *gorm.Session) IWorkerDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IWorkerDo - Not(conds ...gen.Condition) IWorkerDo - Or(conds ...gen.Condition) IWorkerDo - Select(conds ...field.Expr) IWorkerDo - Where(conds ...gen.Condition) IWorkerDo - Order(conds ...field.Expr) IWorkerDo - Distinct(cols ...field.Expr) IWorkerDo - Omit(cols ...field.Expr) IWorkerDo - Join(table schema.Tabler, on ...field.Expr) IWorkerDo - LeftJoin(table schema.Tabler, on ...field.Expr) IWorkerDo - RightJoin(table schema.Tabler, on ...field.Expr) IWorkerDo - Group(cols ...field.Expr) IWorkerDo - Having(conds ...gen.Condition) IWorkerDo - Limit(limit int) IWorkerDo - Offset(offset int) IWorkerDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IWorkerDo - Unscoped() IWorkerDo - Create(values ...*models.Worker) error - CreateInBatches(values []*models.Worker, batchSize int) error - Save(values ...*models.Worker) error - First() (*models.Worker, error) - Take() (*models.Worker, error) - Last() (*models.Worker, error) - Find() ([]*models.Worker, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Worker, err error) - FindInBatches(result *[]*models.Worker, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.Worker) (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) IWorkerDo - Assign(attrs ...field.AssignExpr) IWorkerDo - Joins(fields ...field.RelationField) IWorkerDo - Preload(fields ...field.RelationField) IWorkerDo - FirstOrInit() (*models.Worker, error) - FirstOrCreate() (*models.Worker, error) - FindByPage(offset int, limit int) (result []*models.Worker, 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) IWorkerDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (w workerDo) Debug() IWorkerDo { - return w.withDO(w.DO.Debug()) -} - -func (w workerDo) WithContext(ctx context.Context) IWorkerDo { - return w.withDO(w.DO.WithContext(ctx)) -} - -func (w workerDo) ReadDB() IWorkerDo { - return w.Clauses(dbresolver.Read) -} - -func (w workerDo) WriteDB() IWorkerDo { - return w.Clauses(dbresolver.Write) -} - -func (w workerDo) Session(config *gorm.Session) IWorkerDo { - return w.withDO(w.DO.Session(config)) -} - -func (w workerDo) Clauses(conds ...clause.Expression) IWorkerDo { - return w.withDO(w.DO.Clauses(conds...)) -} - -func (w workerDo) Returning(value interface{}, columns ...string) IWorkerDo { - return w.withDO(w.DO.Returning(value, columns...)) -} - -func (w workerDo) Not(conds ...gen.Condition) IWorkerDo { - return w.withDO(w.DO.Not(conds...)) -} - -func (w workerDo) Or(conds ...gen.Condition) IWorkerDo { - return w.withDO(w.DO.Or(conds...)) -} - -func (w workerDo) Select(conds ...field.Expr) IWorkerDo { - return w.withDO(w.DO.Select(conds...)) -} - -func (w workerDo) Where(conds ...gen.Condition) IWorkerDo { - return w.withDO(w.DO.Where(conds...)) -} - -func (w workerDo) Order(conds ...field.Expr) IWorkerDo { - return w.withDO(w.DO.Order(conds...)) -} - -func (w workerDo) Distinct(cols ...field.Expr) IWorkerDo { - return w.withDO(w.DO.Distinct(cols...)) -} - -func (w workerDo) Omit(cols ...field.Expr) IWorkerDo { - return w.withDO(w.DO.Omit(cols...)) -} - -func (w workerDo) Join(table schema.Tabler, on ...field.Expr) IWorkerDo { - return w.withDO(w.DO.Join(table, on...)) -} - -func (w workerDo) LeftJoin(table schema.Tabler, on ...field.Expr) IWorkerDo { - return w.withDO(w.DO.LeftJoin(table, on...)) -} - -func (w workerDo) RightJoin(table schema.Tabler, on ...field.Expr) IWorkerDo { - return w.withDO(w.DO.RightJoin(table, on...)) -} - -func (w workerDo) Group(cols ...field.Expr) IWorkerDo { - return w.withDO(w.DO.Group(cols...)) -} - -func (w workerDo) Having(conds ...gen.Condition) IWorkerDo { - return w.withDO(w.DO.Having(conds...)) -} - -func (w workerDo) Limit(limit int) IWorkerDo { - return w.withDO(w.DO.Limit(limit)) -} - -func (w workerDo) Offset(offset int) IWorkerDo { - return w.withDO(w.DO.Offset(offset)) -} - -func (w workerDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IWorkerDo { - return w.withDO(w.DO.Scopes(funcs...)) -} - -func (w workerDo) Unscoped() IWorkerDo { - return w.withDO(w.DO.Unscoped()) -} - -func (w workerDo) Create(values ...*models.Worker) error { - if len(values) == 0 { - return nil - } - return w.DO.Create(values) -} - -func (w workerDo) CreateInBatches(values []*models.Worker, batchSize int) error { - return w.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 (w workerDo) Save(values ...*models.Worker) error { - if len(values) == 0 { - return nil - } - return w.DO.Save(values) -} - -func (w workerDo) First() (*models.Worker, error) { - if result, err := w.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.Worker), nil - } -} - -func (w workerDo) Take() (*models.Worker, error) { - if result, err := w.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.Worker), nil - } -} - -func (w workerDo) Last() (*models.Worker, error) { - if result, err := w.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.Worker), nil - } -} - -func (w workerDo) Find() ([]*models.Worker, error) { - result, err := w.DO.Find() - return result.([]*models.Worker), err -} - -func (w workerDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Worker, err error) { - buf := make([]*models.Worker, 0, batchSize) - err = w.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 (w workerDo) FindInBatches(result *[]*models.Worker, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return w.DO.FindInBatches(result, batchSize, fc) -} - -func (w workerDo) Attrs(attrs ...field.AssignExpr) IWorkerDo { - return w.withDO(w.DO.Attrs(attrs...)) -} - -func (w workerDo) Assign(attrs ...field.AssignExpr) IWorkerDo { - return w.withDO(w.DO.Assign(attrs...)) -} - -func (w workerDo) Joins(fields ...field.RelationField) IWorkerDo { - for _, _f := range fields { - w = *w.withDO(w.DO.Joins(_f)) - } - return &w -} - -func (w workerDo) Preload(fields ...field.RelationField) IWorkerDo { - for _, _f := range fields { - w = *w.withDO(w.DO.Preload(_f)) - } - return &w -} - -func (w workerDo) FirstOrInit() (*models.Worker, error) { - if result, err := w.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.Worker), nil - } -} - -func (w workerDo) FirstOrCreate() (*models.Worker, error) { - if result, err := w.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.Worker), nil - } -} - -func (w workerDo) FindByPage(offset int, limit int) (result []*models.Worker, count int64, err error) { - result, err = w.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 = w.Offset(-1).Limit(-1).Count() - return -} - -func (w workerDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = w.Count() - if err != nil { - return - } - - err = w.Offset(offset).Limit(limit).Scan(result) - return -} - -func (w workerDo) Scan(result interface{}) (err error) { - return w.DO.Scan(result) -} - -func (w workerDo) Delete(models ...*models.Worker) (result gen.ResultInfo, err error) { - return w.DO.Delete(models) -} - -func (w *workerDo) withDO(do gen.Dao) *workerDo { - w.DO = *do.(*gen.DO) - return w -} diff --git a/internal/services/monitor.go b/internal/services/monitor.go index b6607b2..459e2a7 100644 --- a/internal/services/monitor.go +++ b/internal/services/monitor.go @@ -25,14 +25,19 @@ func UpdateMonitor(ctx context.Context, q *query.Query, monitor *models.Monitor) _, err := q.Monitor.WithContext(ctx).Where( q.Monitor.Slug.Eq(monitor.Slug), ).Updates(monitor) + return err } +func UpdateMonitorWorkerGroups(ctx context.Context, q *query.Query, monitor *models.Monitor, workerGroups []*models.WorkerGroup) error { + return q.Monitor.WorkerGroups.Model(monitor).Replace(workerGroups...) +} + func GetMonitor(ctx context.Context, q *query.Query, slug string) (*models.Monitor, error) { return q.Monitor.WithContext(ctx).Where( q.Monitor.Slug.Eq(slug), - q.Monitor.DeletedAt.IsNull(), ).Preload( + q.Monitor.WorkerGroups, q.Monitor.History, ).First() } @@ -40,12 +45,16 @@ func GetMonitor(ctx context.Context, q *query.Query, slug string) (*models.Monit func GetMonitors(ctx context.Context, q *query.Query) ([]*models.Monitor, error) { return q.Monitor.WithContext(ctx).Preload( q.Monitor.History, - ).Where( - q.Monitor.DeletedAt.IsNull(), + ).Preload( + q.Monitor.WorkerGroups, ).Find() } -func CreateOrUpdateMonitorSchedule(ctx context.Context, t client.Client, monitor *models.Monitor) error { +func CreateOrUpdateMonitorSchedule( + ctx context.Context, + t client.Client, + monitor *models.Monitor, +) error { log.Println("Creating or Updating Monitor Schedule") args := make([]interface{}, 0) @@ -53,27 +62,23 @@ func CreateOrUpdateMonitorSchedule(ctx context.Context, t client.Client, monitor for _, group := range monitor.WorkerGroups { options := client.ScheduleOptions{ - ID: getScheduleId(monitor, group), - //SearchAttributes: map[string]interface{}{ - // "worker-group": group, - // "monitor-slug": monitor.Slug, - //}, + ID: getScheduleId(monitor, group.Slug), Spec: client.ScheduleSpec{ CronExpressions: []string{monitor.Schedule}, Jitter: time.Second * 10, }, Action: &client.ScheduleWorkflowAction{ - ID: getScheduleId(monitor, group), + ID: getScheduleId(monitor, group.Slug), Workflow: workflows.NewWorkflows(nil).MonitorWorkflowDefinition, Args: args, - TaskQueue: group, + TaskQueue: group.Slug, RetryPolicy: &temporal.RetryPolicy{ MaximumAttempts: 3, }, }, } - schedule := t.ScheduleClient().GetHandle(ctx, getScheduleId(monitor, group)) + schedule := t.ScheduleClient().GetHandle(ctx, getScheduleId(monitor, group.Slug)) // If exists, we update _, err := schedule.Describe(ctx) diff --git a/internal/services/worker.go b/internal/services/worker.go deleted file mode 100644 index a6d25a0..0000000 --- a/internal/services/worker.go +++ /dev/null @@ -1,20 +0,0 @@ -package services - -import ( - "context" - "log" - - "code.tjo.space/mentos1386/zdravko/internal/models" - "code.tjo.space/mentos1386/zdravko/internal/models/query" -) - -func CreateWorker(ctx context.Context, q *query.Query, worker *models.Worker) error { - return q.Worker.WithContext(ctx).Create(worker) -} - -func GetWorker(ctx context.Context, q *query.Query, slug string) (*models.Worker, error) { - log.Println("GetWorker") - return q.Worker.WithContext(ctx).Where( - q.Worker.Slug.Eq(slug), - ).First() -} diff --git a/internal/services/worker_group.go b/internal/services/worker_group.go new file mode 100644 index 0000000..586370d --- /dev/null +++ b/internal/services/worker_group.go @@ -0,0 +1,44 @@ +package services + +import ( + "context" + + "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/internal/models/query" + "gorm.io/gorm/clause" +) + +func GetOrCreateWorkerGroup(ctx context.Context, q *query.Query, workerGroup models.WorkerGroup) (*models.WorkerGroup, error) { + tx := q.Begin() + + if err := tx.WorkerGroup.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&workerGroup); err != nil { + _ = tx.Rollback() + return nil, err + } + + wg, err := tx.WorkerGroup.WithContext(ctx).Where( + q.WorkerGroup.Slug.Eq(workerGroup.Slug), + ).First() + if err != nil { + _ = tx.Rollback() + return nil, err + } + + return wg, tx.Commit() +} + +func GetWorkerGroups(ctx context.Context, q *query.Query) ([]*models.WorkerGroup, error) { + return q.WorkerGroup.WithContext(ctx).Preload(q.WorkerGroup.Monitors).Find() +} + +func GetWorkerGroupsBySlug(ctx context.Context, q *query.Query, slugs []string) ([]*models.WorkerGroup, error) { + return q.WorkerGroup.WithContext(ctx).Where( + q.WorkerGroup.Slug.In(slugs...), + ).Find() +} + +func GetWorkerGroup(ctx context.Context, q *query.Query, slug string) (*models.WorkerGroup, error) { + return q.WorkerGroup.WithContext(ctx).Where( + q.WorkerGroup.Slug.Eq(slug), + ).First() +} diff --git a/internal/temporal/temporal.go b/internal/temporal/temporal.go index 5ab0e11..2562136 100644 --- a/internal/temporal/temporal.go +++ b/internal/temporal/temporal.go @@ -39,7 +39,7 @@ func ConnectServerToTemporal(cfg *config.ServerConfig) (client.Client, error) { }) } -func ConnectWorkerToTemporal(token string, temporalHost string, identity string) (client.Client, error) { +func ConnectWorkerToTemporal(token string, temporalHost string) (client.Client, error) { provider := &AuthHeadersProvider{token} // Try to connect to the Temporal Server @@ -48,7 +48,6 @@ func ConnectWorkerToTemporal(token string, temporalHost string, identity string) HostPort: temporalHost, HeadersProvider: provider, Namespace: "default", - Identity: identity, }) if err != nil { return nil, errors.Wrap(err, "failed to connect to Temporal Server: "+temporalHost) diff --git a/justfile b/justfile index 652e780..fa4aa9c 100644 --- a/justfile +++ b/justfile @@ -16,7 +16,9 @@ _default: # Run full development environment run: - devbox services up + watchexec -r -e tmpl,css just _tailwindcss-build | sed -e 's/^/tailwind: /;' & + just run-temporal | sed -e 's/^/temporal: /;' & + watchexec -r -e go,tmpl,css just run-server # Start worker run-worker: diff --git a/pkg/server/server.go b/pkg/server/server.go index 82eb56f..0a423d4 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -33,7 +33,7 @@ func (s *Server) Name() string { func (s *Server) Start() error { s.echo.Renderer = templates.NewTemplates() - s.echo.Use(middleware.Logger()) + //s.echo.Use(middleware.Logger()) s.echo.Use(middleware.Recover()) db, query, err := internal.ConnectToDatabase(s.cfg.DatabasePath) @@ -83,10 +83,10 @@ func (s *Server) Start() error { settings.POST("/monitors/create", h.SettingsMonitorsCreatePOST) settings.GET("/monitors/:slug", h.SettingsMonitorsDescribeGET) settings.POST("/monitors/:slug", h.SettingsMonitorsDescribePOST) - settings.GET("/workers", h.SettingsWorkersGET) - settings.GET("/workers/create", h.SettingsWorkersCreateGET) - settings.POST("/workers/create", h.SettingsWorkersCreatePOST) - settings.GET("/workers/:slug", h.SettingsWorkersDescribeGET) + settings.GET("/worker-groups", h.SettingsWorkerGroupsGET) + settings.GET("/worker-groups/create", h.SettingsWorkerGroupsCreateGET) + settings.POST("/worker-groups/create", h.SettingsWorkerGroupsCreatePOST) + settings.GET("/worker-groups/:slug", h.SettingsWorkerGroupsDescribeGET) settings.Match([]string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}, "/temporal*", h.Temporal) // OAuth2 diff --git a/pkg/worker/worker.go b/pkg/worker/worker.go index 4e31b96..61f53d9 100644 --- a/pkg/worker/worker.go +++ b/pkg/worker/worker.go @@ -19,7 +19,6 @@ import ( type ConnectionConfig struct { Endpoint string `json:"endpoint"` - Slug string `json:"slug"` Group string `json:"group"` } @@ -36,7 +35,7 @@ func getConnectionConfig(token string, apiUrl string) (*ConnectionConfig, error) } if res.StatusCode == http.StatusUnauthorized { - panic("WORKER_TOKEN is invalid. Either it expired or the worker was removed!") + panic("WORKER_GROUP_TOKEN is invalid. Either it expired or the worker was removed!") } if res.StatusCode != http.StatusOK { @@ -79,10 +78,9 @@ func (w *Worker) Start() error { return err } - log.Println("Worker slug:", config.Slug) - log.Println("Worker group:", config.Group) + log.Println("Worker Group:", config.Group) - temporalClient, err := temporal.ConnectWorkerToTemporal(w.cfg.Token, config.Endpoint, config.Slug) + temporalClient, err := temporal.ConnectWorkerToTemporal(w.cfg.Token, config.Endpoint) if err != nil { return err } diff --git a/process-compose.yml b/process-compose.yml deleted file mode 100644 index 9f135f1..0000000 --- a/process-compose.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: "0.5" - -processes: - server: - command: watchexec -r -e go,tmpl,css just run-server - availability: - restart: "always" - temporal: - command: just run-temporal - availability: - restart: "always" - tailwind: - command: watchexec -r -e go,tmpl,css just _tailwindcss-build - availability: - restart: "always" diff --git a/tools/generate/main.go b/tools/generate/main.go index f42be45..1b4af2e 100644 --- a/tools/generate/main.go +++ b/tools/generate/main.go @@ -29,11 +29,9 @@ func main() { // Generate default DAO interface for those specified structs g.ApplyBasic( - models.Worker{}, models.Monitor{}, + models.WorkerGroup{}, models.MonitorHistory{}, - models.Cronjob{}, - models.CronjobHistory{}, models.OAuth2State{}, ) diff --git a/web/static/css/main.css b/web/static/css/main.css index 8d8d95c..463c3c5 100644 --- a/web/static/css/main.css +++ b/web/static/css/main.css @@ -82,12 +82,14 @@ code { .settings section { @apply relative overflow-x-auto shadow-md sm:rounded-lg text-gray-500 bg-white; } + .settings section h2 { @apply flex flex-col text-lg font-semibold text-gray-900; } .settings section h2 span { @apply text-sm font-medium text-gray-500; } + .settings section form { @apply grid gap-4 grid-cols-1 sm:grid-cols-[2fr_1fr]; } @@ -104,3 +106,16 @@ code { @apply text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center; @apply sm:col-span-2; } + +.settings section table thead { + @apply text-xs text-gray-700 uppercase bg-gray-50; +} +.settings section table thead th { + @apply px-6 py-3 text-center; +} +.settings section table tbody th { + @apply px-6 py-4 font-medium text-gray-900 whitespace-nowrap text-center; +} +.settings section table tbody tr { + @apply px-6 py-4 text-center; +} diff --git a/web/static/css/tailwind.css b/web/static/css/tailwind.css index 7363074..3d85bd6 100644 --- a/web/static/css/tailwind.css +++ b/web/static/css/tailwind.css @@ -1509,14 +1509,42 @@ code { } } -.odd\:bg-white:nth-child(odd) { - --tw-bg-opacity: 1; - background-color: rgb(255 255 255 / var(--tw-bg-opacity)); -} - -.even\:bg-gray-50:nth-child(even) { +.settings section table thead { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity)); + font-size: 0.75rem; + line-height: 1rem; + text-transform: uppercase; + --tw-text-opacity: 1; + color: rgb(55 65 81 / var(--tw-text-opacity)); +} + +.settings section table thead th { + padding-left: 1.5rem; + padding-right: 1.5rem; + padding-top: 0.75rem; + padding-bottom: 0.75rem; + text-align: center; +} + +.settings section table tbody th { + white-space: nowrap; + padding-left: 1.5rem; + padding-right: 1.5rem; + padding-top: 1rem; + padding-bottom: 1rem; + text-align: center; + font-weight: 500; + --tw-text-opacity: 1; + color: rgb(17 24 39 / var(--tw-text-opacity)); +} + +.settings section table tbody tr { + padding-left: 1.5rem; + padding-right: 1.5rem; + padding-top: 1rem; + padding-bottom: 1rem; + text-align: center; } .hover\:bg-blue-800:hover { diff --git a/web/templates/pages/incidents.tmpl b/web/templates/pages/incidents.tmpl index e5ee74b..343655a 100644 --- a/web/templates/pages/incidents.tmpl +++ b/web/templates/pages/incidents.tmpl @@ -6,7 +6,7 @@ There are no Incidents, yet.

- Incidents will allow you to inform your users or co-workers about outages and issues. + Incidents will allow you to inform your users or co-worker groups about outages and issues.

diff --git a/web/templates/pages/settings_monitors.tmpl b/web/templates/pages/settings_monitors.tmpl index c5b9369..1a4b8c6 100644 --- a/web/templates/pages/settings_monitors.tmpl +++ b/web/templates/pages/settings_monitors.tmpl @@ -1,6 +1,6 @@ {{define "settings"}} -{{ $description := "Monitors represent periodicly the k6 script, to see if the monitored service is healthy." }} +{{ $description := "Monitors are constantly checking weather a service is online and working correctly." }} {{ if eq .MonitorsLength 0 }}
@@ -34,37 +34,37 @@ - + Name - + Worker Groups - + Status - + Schedule - + Action {{range .Monitors}} - - + + {{.Name}} - + {{range .WorkerGroups}} - {{ . }} + {{ .Name }} {{end}} - + ACTIVE @@ -72,10 +72,10 @@ PAUSED - + {{.Schedule}} - + Details diff --git a/web/templates/pages/settings_monitors_describe.tmpl b/web/templates/pages/settings_monitors_describe.tmpl index 50d62a0..8c7549f 100644 --- a/web/templates/pages/settings_monitors_describe.tmpl +++ b/web/templates/pages/settings_monitors_describe.tmpl @@ -5,7 +5,7 @@ Configuration - +

Worker groups are used to distribute the monitor to specific workers.

diff --git a/web/templates/pages/settings_overview.tmpl b/web/templates/pages/settings_overview.tmpl index 10e6318..333e635 100644 --- a/web/templates/pages/settings_overview.tmpl +++ b/web/templates/pages/settings_overview.tmpl @@ -9,23 +9,17 @@
-
-
-

Total Workers

-

42

-
+
+

Total Workers

+

42

-
-
-

Total Monitors

-

42

-
+
+

Total Monitors

+

42

-
-
-

Total Notifications

-

42

-
+
+

Total Notifications

+

42

{{end}} diff --git a/web/templates/pages/settings_workers.tmpl b/web/templates/pages/settings_worker_groups.tmpl similarity index 53% rename from web/templates/pages/settings_workers.tmpl rename to web/templates/pages/settings_worker_groups.tmpl index 4d0abdb..f2ae54e 100644 --- a/web/templates/pages/settings_workers.tmpl +++ b/web/templates/pages/settings_worker_groups.tmpl @@ -1,18 +1,18 @@ {{define "settings"}} -{{ $description := "Workers are executing monitors. You can deploy multiple of thems to multiple regions for wider coverage." }} +{{ $description := "Worker Groups are used to match multiple workers together. They can be used to difirentiate between regions, environments, networks etc." }} -{{ if eq .WorkersLength 0 }} +{{ if eq .WorkerGroupsLength 0 }}

- There are no workers yet. + There are no worker groups yet.

{{ $description }}

@@ -21,12 +21,12 @@
- - - - - {{range .Workers}} + {{range .WorkerGroups}} - - + - - - + diff --git a/web/templates/pages/settings_worker_groups_create.tmpl b/web/templates/pages/settings_worker_groups_create.tmpl new file mode 100644 index 0000000..118bcaf --- /dev/null +++ b/web/templates/pages/settings_worker_groups_create.tmpl @@ -0,0 +1,10 @@ +{{define "settings"}} +
+
+ + +

Worker group name can be anything.

+ + +
+{{end}} diff --git a/web/templates/pages/settings_workers_describe.tmpl b/web/templates/pages/settings_worker_groups_describe.tmpl similarity index 71% rename from web/templates/pages/settings_workers_describe.tmpl rename to web/templates/pages/settings_worker_groups_describe.tmpl index 8d3f860..a9dfe65 100644 --- a/web/templates/pages/settings_workers_describe.tmpl +++ b/web/templates/pages/settings_worker_groups_describe.tmpl @@ -1,23 +1,8 @@ {{define "settings"}} -
-
-

- Configuration -

- - -

- Group is used to distinguish between different workers. - For example, you can have a group for different regions, - different datacenters or different environments. -

- - -

Token - Use it as WORKER_TOKEN configuration option. + Use it as WORKER_GROUP_TOKEN configuration option.

{{ .Worker.Token }}
diff --git a/web/templates/pages/settings_workers_create.tmpl b/web/templates/pages/settings_workers_create.tmpl deleted file mode 100644 index e66d011..0000000 --- a/web/templates/pages/settings_workers_create.tmpl +++ /dev/null @@ -1,17 +0,0 @@ -{{define "settings"}} -
-
- - -

Worker name can be anything.

- - -

- Group is used to distinguish between different workers. - For example, you can have a group for different regions, - different datacenters or different environments. -

- - -
-{{end}} diff --git a/web/templates/tempaltes.go b/web/templates/tempaltes.go index d13a1e3..3c9b156 100644 --- a/web/templates/tempaltes.go +++ b/web/templates/tempaltes.go @@ -38,16 +38,16 @@ func loadSettings(files ...string) *template.Template { func NewTemplates() *Templates { return &Templates{ templates: map[string]*template.Template{ - "404.tmpl": load("pages/404.tmpl"), - "index.tmpl": load("pages/index.tmpl"), - "incidents.tmpl": load("pages/incidents.tmpl"), - "settings_overview.tmpl": loadSettings("pages/settings_overview.tmpl"), - "settings_workers.tmpl": loadSettings("pages/settings_workers.tmpl"), - "settings_workers_create.tmpl": loadSettings("pages/settings_workers_create.tmpl"), - "settings_workers_describe.tmpl": loadSettings("pages/settings_workers_describe.tmpl"), - "settings_monitors.tmpl": loadSettings("pages/settings_monitors.tmpl"), - "settings_monitors_create.tmpl": loadSettings("pages/settings_monitors_create.tmpl"), - "settings_monitors_describe.tmpl": loadSettings("pages/settings_monitors_describe.tmpl"), + "404.tmpl": load("pages/404.tmpl"), + "index.tmpl": load("pages/index.tmpl"), + "incidents.tmpl": load("pages/incidents.tmpl"), + "settings_overview.tmpl": loadSettings("pages/settings_overview.tmpl"), + "settings_worker_groups.tmpl": loadSettings("pages/settings_worker_groups.tmpl"), + "settings_worker_groups_create.tmpl": loadSettings("pages/settings_worker_groups_create.tmpl"), + "settings_worker_groups_describe.tmpl": loadSettings("pages/settings_worker_groups_describe.tmpl"), + "settings_monitors.tmpl": loadSettings("pages/settings_monitors.tmpl"), + "settings_monitors_create.tmpl": loadSettings("pages/settings_monitors_create.tmpl"), + "settings_monitors_describe.tmpl": loadSettings("pages/settings_monitors_describe.tmpl"), }, } }
- List of Workers + List of Worker Groups

{{ $description }}

- + Create New @@ -34,41 +34,39 @@
+ Name - Group + + Workers - Status + + Monitors + Action
+
{{.Name}} - - {{.Group}} - - + - ONLINE + 10 ONLINE - - OFFLINE + + NONE - Details + + {{ len .Monitors }} + + Details