diff --git a/database/database.go b/database/database.go new file mode 100644 index 0000000..da84362 --- /dev/null +++ b/database/database.go @@ -0,0 +1,33 @@ +package database + +import ( + "embed" + "log/slog" + + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" + migrate "github.com/rubenv/sql-migrate" +) + +//go:embed sqlite/migrations/* +var sqliteMigrations embed.FS + +func ConnectToDatabase(logger *slog.Logger, path string) (*sqlx.DB, error) { + db, err := sqlx.Connect("sqlite3", path) + if err != nil { + return nil, err + } + logger.Info("Connected to database") + + migrations := migrate.EmbedFileSystemMigrationSource{ + FileSystem: sqliteMigrations, + Root: "sqlite/migrations", + } + n, err := migrate.Exec(db.DB, "sqlite3", migrations, migrate.Up) + if err != nil { + return nil, err + } + logger.Info("Applied migrations", "number", n) + + return db, nil +} diff --git a/database/models/models.go b/database/models/models.go new file mode 100644 index 0000000..2316b80 --- /dev/null +++ b/database/models/models.go @@ -0,0 +1,60 @@ +package models + +import ( + "time" +) + +type OAuth2State struct { + State string `db:"state"` + ExpiresAt time.Time `db:"expires_at"` +} + +const ( + MonitorSuccess string = "SUCCESS" + MonitorFailure string = "FAILURE" + MonitorError string = "ERROR" + MonitorUnknown string = "UNKNOWN" +) + +type Monitor struct { + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` + DeletedAt *time.Time `db:"deleted_at"` + + Slug string `db:"slug"` + Name string `db:"name"` + + Schedule string `db:"schedule"` + Script string `db:"script"` +} + +type MonitorWithWorkerGroups struct { + Monitor + + // List of worker group names + WorkerGroups []string +} + +type MonitorHistory struct { + CreatedAt time.Time `db:"created_at"` + + MonitorSlug string `db:"monitor_slug"` + Status string `db:"status"` + Note string `db:"note"` +} + +type WorkerGroup struct { + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` + DeletedAt *time.Time `db:"deleted_at"` + + Slug string `db:"slug"` + Name string `db:"name"` +} + +type WorkerGroupWithMonitors struct { + WorkerGroup + + // List of worker group names + Monitors []string +} diff --git a/database/sqlite/migrations/2024-02-27-initial.sql b/database/sqlite/migrations/2024-02-27-initial.sql new file mode 100644 index 0000000..0efcf46 --- /dev/null +++ b/database/sqlite/migrations/2024-02-27-initial.sql @@ -0,0 +1,58 @@ +-- +migrate Up +CREATE TABLE o_auth2_states ( + state TEXT, + expiry DATETIME, + PRIMARY KEY (state) +); + +CREATE TABLE monitors ( + slug TEXT, + name TEXT, + schedule TEXT, + script TEXT, + + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + deleted_at DATETIME, + + PRIMARY KEY (slug), + CONSTRAINT unique_monitors_name UNIQUE (name) +); + +CREATE TABLE worker_groups ( + slug TEXT, + name TEXT, + + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + deleted_at DATETIME, + + PRIMARY KEY (slug), + CONSTRAINT unique_worker_groups_name UNIQUE (name) +); + +CREATE TABLE monitor_worker_groups ( + worker_group_slug TEXT, + monitor_slug TEXT, + PRIMARY KEY (worker_group_slug,monitor_slug), + CONSTRAINT fk_monitor_worker_groups_worker_group FOREIGN KEY (worker_group_slug) REFERENCES worker_groups(slug), + CONSTRAINT fk_monitor_worker_groups_monitor FOREIGN KEY (monitor_slug) REFERENCES monitors(slug) +); + +CREATE TABLE "monitor_histories" ( + monitor_slug TEXT, + status TEXT, + note TEXT, + + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + + PRIMARY KEY (monitor_slug, created_at), + CONSTRAINT fk_monitors_history FOREIGN KEY (monitor_slug) REFERENCES monitors(slug) +); + +-- +migrate Down +DROP TABLE o_auth2_states; +DROP TABLE monitor_worker_groups; +DROP TABLE worker_groups; +DROP TABLE monitor_histories; +DROP TABLE monitors; diff --git a/deploy/fly.toml b/deploy/fly.toml index ca2bd9a..0788dae 100644 --- a/deploy/fly.toml +++ b/deploy/fly.toml @@ -17,8 +17,8 @@ primary_region = 'waw' ROOT_URL = 'https://zdravko.mnts.dev' TEMPORAL_SERVER_HOST = 'server.process.zdravko.internal:7233' - TEMPORAL_DATABASE_PATH = '/data/temporal-2.db' - DATABASE_PATH = '/data/zdravko-2.db' + TEMPORAL_DATABASE_PATH = '/data/temporal-4.db' + DATABASE_PATH = '/data/zdravko-4.db' [processes] server = '--temporal --server' diff --git a/devbox.json b/devbox.json index c244b2f..3dca6b6 100644 --- a/devbox.json +++ b/devbox.json @@ -6,6 +6,8 @@ "tailwindcss@latest", "flyctl@latest", "just@latest", - "nodePackages.npm@latest" + "nodePackages.npm@latest", + "sqlite@latest", + "sqlite-web@latest" ] } diff --git a/devbox.lock b/devbox.lock index 18e3d16..bd02d77 100644 --- a/devbox.lock +++ b/devbox.lock @@ -75,6 +75,46 @@ } } }, + "sqlite-web@latest": { + "last_modified": "2024-02-10T18:15:24Z", + "resolved": "github:NixOS/nixpkgs/10b813040df67c4039086db0f6eaf65c536886c6#sqlite-web", + "source": "devbox-search", + "version": "0.6.2", + "systems": { + "aarch64-darwin": { + "store_path": "/nix/store/klkx4fv3al5dgg59w3xv0brnn28gmpkh-sqlite-web-0.6.2" + }, + "aarch64-linux": { + "store_path": "/nix/store/liqjqlnwc111g2j1mxak0z6b0cbvn46i-sqlite-web-0.6.2" + }, + "x86_64-darwin": { + "store_path": "/nix/store/ip9c99c0r4avyxl68x1cxpn6649pff4j-sqlite-web-0.6.2" + }, + "x86_64-linux": { + "store_path": "/nix/store/lfwrqdx8jjpqhzxhcfjnm82ll4a2jzhv-sqlite-web-0.6.2" + } + } + }, + "sqlite@latest": { + "last_modified": "2024-02-20T22:56:03Z", + "resolved": "github:NixOS/nixpkgs/5eeded8e3518579daa13887297efa79f5be74b41#sqlite", + "source": "devbox-search", + "version": "3.45.1", + "systems": { + "aarch64-darwin": { + "store_path": "/nix/store/ay9wvqp3p548p08symcy3q7avm86ck00-sqlite-3.45.1-bin" + }, + "aarch64-linux": { + "store_path": "/nix/store/1j3xiiq0i2q69nmwi9ja99grnwlpqzgy-sqlite-3.45.1-bin" + }, + "x86_64-darwin": { + "store_path": "/nix/store/c9wndvymfnm4dcmi0bgy1lmljzx8dv4n-sqlite-3.45.1-bin" + }, + "x86_64-linux": { + "store_path": "/nix/store/b3pbwqqpfllg2lxwhhv4iyw3m9xxbgld-sqlite-3.45.1-bin" + } + } + }, "tailwindcss@latest": { "last_modified": "2024-01-27T14:55:31Z", "resolved": "github:NixOS/nixpkgs/160b762eda6d139ac10ae081f8f78d640dd523eb#tailwindcss", diff --git a/go.mod b/go.mod index 42b47f7..cdf5c79 100644 --- a/go.mod +++ b/go.mod @@ -7,20 +7,19 @@ require ( github.com/golang-jwt/jwt/v5 v5.2.0 github.com/gorilla/sessions v1.2.2 github.com/gosimple/slug v1.13.1 + github.com/jmoiron/sqlx v1.3.5 github.com/labstack/echo/v4 v4.11.4 - github.com/lib/pq v1.10.9 + github.com/mattn/go-sqlite3 v1.14.19 github.com/pkg/errors v0.9.1 + github.com/rubenv/sql-migrate v1.6.1 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.18.2 github.com/temporalio/ui-server/v2 v2.23.0 go.k6.io/k6 v0.49.0 go.temporal.io/sdk v1.26.0-rc.2 go.temporal.io/server v1.22.4 + golang.org/x/exp v0.0.0-20231127185646-65229373498e golang.org/x/oauth2 v0.17.0 - gorm.io/driver/sqlite v1.5.0 - gorm.io/gen v0.3.25 - gorm.io/gorm v1.25.7 - gorm.io/plugin/dbresolver v1.5.0 ) replace go.temporal.io/server => github.com/temporalio/temporal v1.23.0-rc2.0.20240207154935-68882596be5d @@ -61,6 +60,7 @@ require ( github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/go-gorp/gorp/v3 v3.1.0 // indirect github.com/go-logr/logr v1.3.0 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.1 // indirect @@ -97,20 +97,17 @@ require ( github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgx/v5 v5.4.3 // indirect github.com/jhump/protoreflect v1.15.4 // indirect - github.com/jinzhu/inflection v1.0.0 // indirect - github.com/jinzhu/now v1.1.5 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/jmoiron/sqlx v1.3.4 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/klauspost/compress v1.17.4 // indirect github.com/labstack/gommon v0.4.2 // indirect github.com/leodido/go-urn v1.4.0 // indirect + github.com/lib/pq v1.10.9 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-sqlite3 v1.14.16 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mccutchen/go-httpbin v1.1.2-0.20190116014521-c5cb2f4802fa // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -176,7 +173,6 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect golang.org/x/crypto v0.19.0 // indirect - golang.org/x/exp v0.0.0-20231127185646-65229373498e // indirect golang.org/x/mod v0.15.0 // indirect golang.org/x/net v0.21.0 // indirect golang.org/x/sync v0.6.0 // indirect @@ -198,9 +194,6 @@ require ( gopkg.in/square/go-jose.v2 v2.6.0 // indirect gopkg.in/validator.v2 v2.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - gorm.io/datatypes v1.2.0 // indirect - gorm.io/driver/mysql v1.5.4 // indirect - gorm.io/hints v1.1.2 // indirect lukechampine.com/uint128 v1.3.0 // indirect modernc.org/cc/v3 v3.41.0 // indirect modernc.org/ccgo/v3 v3.16.15 // indirect diff --git a/go.sum b/go.sum index 84f8929..001efd5 100644 --- a/go.sum +++ b/go.sum @@ -131,6 +131,8 @@ github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcP github.com/go-faker/faker/v4 v4.2.0 h1:dGebOupKwssrODV51E0zbMrv5e2gO9VWSLNC1WDCpWg= github.com/go-faker/faker/v4 v4.2.0/go.mod h1:F/bBy8GH9NxOxMInug5Gx4WYeG6fHJZ8Ol/dhcpRub4= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gorp/gorp/v3 v3.1.0 h1:ItKF/Vbuj31dmV4jxA1qblpSwkl9g1typ24xoe70IGs= +github.com/go-gorp/gorp/v3 v3.1.0/go.mod h1:dLEjIyyRNiXvNZ8PSmzpt1GsWAUK8kjVhEpjH8TixEw= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= @@ -153,9 +155,7 @@ github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaC github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-sourcemap/sourcemap v2.1.4-0.20211119122758-180fcef48034+incompatible h1:bopx7t9jyUNX1ebhr0G4gtQWmUOgwQRI0QsYhdYLgkU= github.com/go-sourcemap/sourcemap v2.1.4-0.20211119122758-180fcef48034+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= @@ -170,10 +170,6 @@ github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOW github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw= github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= -github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= -github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= -github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= -github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -272,17 +268,12 @@ github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJS github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jhump/protoreflect v1.15.4 h1:mrwJhfQGGljwvR/jPEocli8KA6G9afbQpH8NY2wORcI= github.com/jhump/protoreflect v1.15.4/go.mod h1:2B+zwrnMY3TTIqEK01OG/d3pyUycQBfDf+bx8fE2DNg= -github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= -github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= -github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= -github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= -github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/jmoiron/sqlx v1.3.4 h1:wv+0IJZfL5z0uZoUjlpKgHkgaFSYD+r9CfrXjEXsO7w= -github.com/jmoiron/sqlx v1.3.4/go.mod h1:2BljVx/86SuTyjE+aPYlHCTNvZrnJXghYGpNiXLBMCQ= +github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= +github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= @@ -330,16 +321,13 @@ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= -github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= -github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= -github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/mattn/go-sqlite3 v1.14.19 h1:fhGleo2h1p8tVChob4I9HpmVFIAkKGpiukdrgQbWfGI= +github.com/mattn/go-sqlite3 v1.14.19/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/mccutchen/go-httpbin v1.1.2-0.20190116014521-c5cb2f4802fa h1:lx8ZnNPwjkXSzOROz0cg69RlErRXs+L3eDkggASWKLo= github.com/mccutchen/go-httpbin v1.1.2-0.20190116014521-c5cb2f4802fa/go.mod h1:fhpOYavp5g2K74XDl/ao2y4KvhqVtKlkg1e+0UaQv7I= -github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE= -github.com/microsoft/go-mssqldb v0.17.0/go.mod h1:OkoNGhGEs8EZqchVTtochlXruEhEOaO4S0d2sB5aeGQ= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -381,6 +369,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY= +github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg= github.com/prashantv/protectmem v0.0.0-20171002184600-e20412882b3a h1:AA9vgIBDjMHPC2McaGPojgV2dcI78ZC0TLNhYCXEKH8= github.com/prashantv/protectmem v0.0.0-20171002184600-e20412882b3a/go.mod h1:lzZQ3Noex5pfAy7mkAeCjcBDteYU85uWWnJ/y6gKU8k= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= @@ -421,6 +411,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rubenv/sql-migrate v1.6.1 h1:bo6/sjsan9HaXAsNxYP/jCEDUGibHp8JmOBw7NTGRos= +github.com/rubenv/sql-migrate v1.6.1/go.mod h1:tPzespupJS0jacLfhbwto/UjSX+8h2FdWB7ar+QlHa0= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= @@ -786,30 +778,6 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gorm.io/datatypes v1.2.0 h1:5YT+eokWdIxhJgWHdrb2zYUimyk0+TaFth+7a0ybzco= -gorm.io/datatypes v1.2.0/go.mod h1:o1dh0ZvjIjhH/bngTpypG6lVRJ5chTBxE09FH/71k04= -gorm.io/driver/mysql v1.4.3/go.mod h1:sSIebwZAVPiT+27jK9HIwvsqOGKx3YMPmrA3mBJR10c= -gorm.io/driver/mysql v1.5.4 h1:igQmHfKcbaTVyAIHNhhB888vvxh8EdQ2uSUT0LPcBso= -gorm.io/driver/mysql v1.5.4/go.mod h1:9rYxJph/u9SWkWc9yY4XJ1F/+xO0S/ChOmbk3+Z5Tvs= -gorm.io/driver/postgres v1.5.0 h1:u2FXTy14l45qc3UeCJ7QaAXZmZfDDv0YrthvmRq1l0U= -gorm.io/driver/postgres v1.5.0/go.mod h1:FUZXzO+5Uqg5zzwzv4KK49R8lvGIyscBOqYrtI1Ce9A= -gorm.io/driver/sqlite v1.5.0 h1:zKYbzRCpBrT1bNijRnxLDJWPjVfImGEn0lSnUY5gZ+c= -gorm.io/driver/sqlite v1.5.0/go.mod h1:kDMDfntV9u/vuMmz8APHtHF0b4nyBB7sfCieC6G8k8I= -gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0= -gorm.io/driver/sqlserver v1.4.1/go.mod h1:DJ4P+MeZbc5rvY58PnmN1Lnyvb5gw5NPzGshHDnJLig= -gorm.io/gen v0.3.25 h1:uT/1YfvcnYUdike4XPYyi89FEnVHZF115GUXQm2Sfug= -gorm.io/gen v0.3.25/go.mod h1:p+t0iCKjaPz+pKRxcx63nXdRgnrah/QD2l92747ihyA= -gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= -gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= -gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= -gorm.io/gorm v1.25.2/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= -gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= -gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A= -gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= -gorm.io/hints v1.1.2 h1:b5j0kwk5p4+3BtDtYqqfY+ATSxjj+6ptPgVveuynn9o= -gorm.io/hints v1.1.2/go.mod h1:/ARdpUHAtyEMCh5NNi3tI7FsGh+Cj/MIUlvNxCNCFWg= -gorm.io/plugin/dbresolver v1.5.0 h1:XVHLxh775eP0CqVh3vcfJtYqja3uFl5Wr3cKlY8jgDY= -gorm.io/plugin/dbresolver v1.5.0/go.mod h1:l4Cn87EHLEYuqUncpEeTC2tTJQkjngPSD+lo8hIvcT0= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/internal/database.go b/internal/database.go deleted file mode 100644 index 0770265..0000000 --- a/internal/database.go +++ /dev/null @@ -1,33 +0,0 @@ -package internal - -import ( - "code.tjo.space/mentos1386/zdravko/internal/models" - "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{ - Logger: logger.Default.LogMode(logger.Info), - }) - if err != nil { - return nil, nil, err - } - - err = db.AutoMigrate( - models.Monitor{}, - models.WorkerGroup{}, - models.MonitorHistory{}, - models.OAuth2State{}, - ) - if err != nil { - return nil, nil, err - } - - q := query.Use(db) - - return db, q, nil -} diff --git a/internal/handlers/api.go b/internal/handlers/api.go index 6f3676b..a08c79f 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -2,14 +2,14 @@ package handlers import ( "context" + "database/sql" "errors" "net/http" - "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/database/models" "code.tjo.space/mentos1386/zdravko/internal/services" "code.tjo.space/mentos1386/zdravko/pkg/api" "github.com/labstack/echo/v4" - "gorm.io/gorm" ) type ApiV1WorkersConnectGETResponse struct { @@ -21,9 +21,9 @@ func (h *BaseHandler) ApiV1WorkersConnectGET(c echo.Context) error { ctx := context.Background() cc := c.(AuthenticatedContext) - workerGroup, err := services.GetWorkerGroup(ctx, h.query, cc.Principal.Worker.Group) + workerGroup, err := services.GetWorkerGroup(ctx, h.db, cc.Principal.Worker.Group) if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { + if errors.Is(err, sql.ErrNoRows) { return echo.NewHTTPError(http.StatusUnauthorized, "Token invalid") } return err @@ -51,16 +51,19 @@ func (h *BaseHandler) ApiV1MonitorsHistoryPOST(c echo.Context) error { return err } - monitor, err := services.GetMonitor(ctx, h.query, slug) + _, err = services.GetMonitor(ctx, h.db, slug) if err != nil { + if err == sql.ErrNoRows { + return echo.NewHTTPError(http.StatusNotFound, "Monitor not found") + } return err } - err = h.query.Monitor.History.Model(monitor).Append( - &models.MonitorHistory{ - Status: body.Status, - Note: body.Note, - }) + err = services.AddHistoryForMonitor(ctx, h.db, &models.MonitorHistory{ + MonitorSlug: slug, + Status: body.Status, + Note: body.Note, + }) if err != nil { return err } diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index dbb1758..ed83135 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -1,10 +1,12 @@ package handlers import ( + "log/slog" + "code.tjo.space/mentos1386/zdravko/internal/config" - "code.tjo.space/mentos1386/zdravko/internal/models/query" "code.tjo.space/mentos1386/zdravko/web/templates/components" "github.com/gorilla/sessions" + "github.com/jmoiron/sqlx" "go.temporal.io/sdk/client" ) @@ -24,16 +26,23 @@ func GetPageByTitle(pages []*components.Page, title string) *components.Page { } type BaseHandler struct { - query *query.Query + db *sqlx.DB config *config.ServerConfig + logger *slog.Logger temporal client.Client store *sessions.CookieStore } -func NewBaseHandler(q *query.Query, temporal client.Client, config *config.ServerConfig) *BaseHandler { +func NewBaseHandler(db *sqlx.DB, temporal client.Client, config *config.ServerConfig, logger *slog.Logger) *BaseHandler { store := sessions.NewCookieStore([]byte(config.SessionSecret)) - return &BaseHandler{q, config, temporal, store} + return &BaseHandler{ + db: db, + config: config, + logger: logger, + temporal: temporal, + store: store, + } } diff --git a/internal/handlers/index.go b/internal/handlers/index.go index c4d707a..048f5ed 100644 --- a/internal/handlers/index.go +++ b/internal/handlers/index.go @@ -5,7 +5,7 @@ import ( "net/http" "time" - "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/database/models" "code.tjo.space/mentos1386/zdravko/internal/services" "code.tjo.space/mentos1386/zdravko/web/templates/components" "github.com/labstack/echo/v4" @@ -13,10 +13,10 @@ import ( type IndexData struct { *components.Base - HealthChecks []*HealthCheck + HealthChecks []*HealthCheck MonitorsLength int - TimeRange string - Status string + TimeRange string + Status string } type HealthCheck struct { @@ -39,7 +39,7 @@ func getHour(date time.Time) string { return date.Format("2006-01-02T15:04") } -func getDailyHistory(history []models.MonitorHistory) *History { +func getDailyHistory(history []*models.MonitorHistory) *History { numDays := 90 historyDailyMap := map[string]string{} numOfSuccess := 0 @@ -88,7 +88,7 @@ func getDailyHistory(history []models.MonitorHistory) *History { } } -func getHourlyHistory(history []models.MonitorHistory) *History { +func getHourlyHistory(history []*models.MonitorHistory) *History { numHours := 48 historyHourlyMap := map[string]string{} numOfSuccess := 0 @@ -139,7 +139,7 @@ func getHourlyHistory(history []models.MonitorHistory) *History { func (h *BaseHandler) Index(c echo.Context) error { ctx := context.Background() - monitors, err := services.GetMonitors(ctx, h.query) + monitors, err := services.GetMonitors(ctx, h.db) if err != nil { return err } @@ -153,8 +153,13 @@ func (h *BaseHandler) Index(c echo.Context) error { monitorsWithHistory := make([]*HealthCheck, len(monitors)) for i, monitor := range monitors { - historyDaily := getDailyHistory(monitor.History) - historyHourly := getHourlyHistory(monitor.History) + history, err := services.GetMonitorHistoryForMonitor(ctx, h.db, monitor.Slug) + if err != nil { + return err + } + + historyDaily := getDailyHistory(history) + historyHourly := getHourlyHistory(history) status := historyDaily.History[89] if status != models.MonitorSuccess { @@ -174,9 +179,9 @@ func (h *BaseHandler) Index(c echo.Context) error { NavbarActive: GetPageByTitle(Pages, "Status"), Navbar: Pages, }, - HealthChecks: monitorsWithHistory, + HealthChecks: monitorsWithHistory, MonitorsLength: len(monitors), - TimeRange: timeRange, - Status: overallStatus, + TimeRange: timeRange, + Status: overallStatus, }) } diff --git a/internal/handlers/oauth2.go b/internal/handlers/oauth2.go index ce2f3f6..7218932 100644 --- a/internal/handlers/oauth2.go +++ b/internal/handlers/oauth2.go @@ -12,8 +12,9 @@ import ( "strconv" "time" + "code.tjo.space/mentos1386/zdravko/database/models" "code.tjo.space/mentos1386/zdravko/internal/config" - "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/internal/services" "github.com/labstack/echo/v4" "golang.org/x/oauth2" ) @@ -86,7 +87,7 @@ func (h *BaseHandler) OAuth2LoginGET(c echo.Context) error { conf := newOAuth2(h.config) state := newRandomState() - err := h.query.OAuth2State.WithContext(ctx).Create(&models.OAuth2State{State: state, Expiry: time.Now().Add(5 * time.Minute)}) + err := services.CreateOAuth2State(ctx, h.db, &models.OAuth2State{State: state, ExpiresAt: time.Now().Add(5 * time.Minute)}) if err != nil { return err } @@ -103,14 +104,11 @@ func (h *BaseHandler) OAuth2CallbackGET(c echo.Context) error { state := c.QueryParam("state") code := c.QueryParam("code") - result, err := h.query.OAuth2State.WithContext(ctx).Where( - h.query.OAuth2State.State.Eq(state), - h.query.OAuth2State.Expiry.Gt(time.Now()), - ).Delete() + deleted, err := services.DeleteOAuth2State(ctx, h.db, state) if err != nil { return err } - if result.RowsAffected != 1 { + if deleted == false { return errors.New("invalid state") } diff --git a/internal/handlers/settingsmonitors.go b/internal/handlers/settingsmonitors.go index 49a8414..f1910c6 100644 --- a/internal/handlers/settingsmonitors.go +++ b/internal/handlers/settingsmonitors.go @@ -2,11 +2,12 @@ package handlers import ( "context" + "database/sql" "fmt" "net/http" "strings" - "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/database/models" "code.tjo.space/mentos1386/zdravko/internal/services" "code.tjo.space/mentos1386/zdravko/web/templates/components" "github.com/go-playground/validator/v10" @@ -29,19 +30,20 @@ type UpdateMonitor struct { type SettingsMonitors struct { *Settings - Monitors []*models.Monitor + Monitors []*models.MonitorWithWorkerGroups MonitorsLength int } type SettingsMonitor struct { *Settings - Monitor *models.Monitor + Monitor *models.MonitorWithWorkerGroups + History []*models.MonitorHistory } func (h *BaseHandler) SettingsMonitorsGET(c echo.Context) error { cc := c.(AuthenticatedContext) - monitors, err := services.GetMonitors(context.Background(), h.query) + monitors, err := services.GetMonitorsWithWorkerGroups(context.Background(), h.db) if err != nil { return err } @@ -62,11 +64,21 @@ func (h *BaseHandler) SettingsMonitorsDescribeGET(c echo.Context) error { slug := c.Param("slug") - monitor, err := services.GetMonitor(context.Background(), h.query, slug) + monitor, err := services.GetMonitorWithWorkerGroups(context.Background(), h.db, slug) if err != nil { return err } + history, err := services.GetMonitorHistoryForMonitor(context.Background(), h.db, slug) + if err != nil { + return err + } + + maxElements := 10 + if len(history) < maxElements { + maxElements = len(history) + } + return c.Render(http.StatusOK, "settings_monitors_describe.tmpl", &SettingsMonitor{ Settings: NewSettings( cc.Principal.User, @@ -80,6 +92,7 @@ func (h *BaseHandler) SettingsMonitorsDescribeGET(c echo.Context) error { }, }), Monitor: monitor, + History: history[:maxElements], }) } @@ -97,7 +110,7 @@ func (h *BaseHandler) SettingsMonitorsDescribePOST(c echo.Context) error { return err } - monitor, err := services.GetMonitor(ctx, h.query, monitorSlug) + monitor, err := services.GetMonitor(ctx, h.db, monitorSlug) if err != nil { return err } @@ -106,7 +119,7 @@ func (h *BaseHandler) SettingsMonitorsDescribePOST(c echo.Context) error { err = services.UpdateMonitor( ctx, - h.query, + h.db, monitor, ) if err != nil { @@ -118,18 +131,27 @@ func (h *BaseHandler) SettingsMonitorsDescribePOST(c echo.Context) error { if group == "" { continue } - workerGroup, err := services.GetOrCreateWorkerGroup(ctx, h.query, models.WorkerGroup{Name: group, Slug: slug.Make(group)}) + workerGroup, err := services.GetWorkerGroup(ctx, h.db, slug.Make(group)) if err != nil { - return err + if err == sql.ErrNoRows { + workerGroup = &models.WorkerGroup{Name: group, Slug: slug.Make(group)} + err = services.CreateWorkerGroup(ctx, h.db, workerGroup) + if err != nil { + return err + } + } else { + return err + } } workerGroups = append(workerGroups, workerGroup) } - err = services.UpdateMonitorWorkerGroups(ctx, h.query, monitor, workerGroups) + + err = services.UpdateMonitorWorkerGroups(ctx, h.db, monitor, workerGroups) if err != nil { return err } - err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor) + err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor, workerGroups) if err != nil { return err } @@ -165,32 +187,51 @@ func (h *BaseHandler) SettingsMonitorsCreatePOST(c echo.Context) error { return err } - workerGroups := []models.WorkerGroup{} + workerGroups := []*models.WorkerGroup{} for _, group := range strings.Split(create.WorkerGroups, " ") { - workerGroups = append(workerGroups, models.WorkerGroup{Name: group, Slug: slug.Make(group)}) + if group == "" { + continue + } + workerGroup, err := services.GetWorkerGroup(ctx, h.db, slug.Make(group)) + if err != nil { + if err == sql.ErrNoRows { + workerGroup = &models.WorkerGroup{Name: group, Slug: slug.Make(group)} + err = services.CreateWorkerGroup(ctx, h.db, workerGroup) + if err != nil { + return err + } + } else { + return err + } + } + workerGroups = append(workerGroups, workerGroup) } monitor := &models.Monitor{ - Name: create.Name, - Slug: monitorSlug, - Schedule: create.Schedule, - Script: create.Script, - WorkerGroups: workerGroups, + Name: create.Name, + Slug: monitorSlug, + Schedule: create.Schedule, + Script: create.Script, } err = services.CreateMonitor( ctx, - h.query, + h.db, monitor, ) if err != nil { return err } - err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor) + err = services.UpdateMonitorWorkerGroups(ctx, h.db, monitor, workerGroups) if err != nil { return err } - return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/settings/monitors/%s", monitorSlug)) + err = services.CreateOrUpdateMonitorSchedule(ctx, h.temporal, monitor, workerGroups) + if err != nil { + return err + } + + return c.Redirect(http.StatusSeeOther, "/settings/monitors") } diff --git a/internal/handlers/settingsworkergroups.go b/internal/handlers/settingsworkergroups.go index 5c74b91..1b4419f 100644 --- a/internal/handlers/settingsworkergroups.go +++ b/internal/handlers/settingsworkergroups.go @@ -5,8 +5,8 @@ import ( "fmt" "net/http" + "code.tjo.space/mentos1386/zdravko/database/models" "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" @@ -21,7 +21,7 @@ type WorkerWithToken struct { type SettingsWorkerGroups struct { *Settings - WorkerGroups []*models.WorkerGroup + WorkerGroups []*models.WorkerGroupWithMonitors WorkerGroupsLength int } @@ -33,7 +33,7 @@ type SettingsWorker struct { func (h *BaseHandler) SettingsWorkerGroupsGET(c echo.Context) error { cc := c.(AuthenticatedContext) - workerGroups, err := services.GetWorkerGroups(context.Background(), h.query) + workerGroups, err := services.GetWorkerGroupsWithMonitors(context.Background(), h.db) if err != nil { return err } @@ -54,7 +54,7 @@ func (h *BaseHandler) SettingsWorkerGroupsDescribeGET(c echo.Context) error { slug := c.Param("slug") - worker, err := services.GetWorkerGroup(context.Background(), h.query, slug) + worker, err := services.GetWorkerGroup(context.Background(), h.db, slug) if err != nil { return err } @@ -101,20 +101,20 @@ func (h *BaseHandler) SettingsWorkerGroupsCreatePOST(c echo.Context) error { ctx := context.Background() slug := slug.Make(c.FormValue("name")) - worker := models.WorkerGroup{ + workerGroup := &models.WorkerGroup{ Name: c.FormValue("name"), Slug: slug, } - err := validator.New(validator.WithRequiredStructEnabled()).Struct(worker) + err := validator.New(validator.WithRequiredStructEnabled()).Struct(workerGroup) if err != nil { return err } - _, err = services.GetOrCreateWorkerGroup( + err = services.CreateWorkerGroup( ctx, - h.query, - worker, + h.db, + workerGroup, ) if err != nil { return err diff --git a/internal/jwt/jwt.go b/internal/jwt/jwt.go index 77a5252..3601bc2 100644 --- a/internal/jwt/jwt.go +++ b/internal/jwt/jwt.go @@ -6,7 +6,7 @@ import ( "encoding/hex" "time" - "code.tjo.space/mentos1386/zdravko/internal/models" + "code.tjo.space/mentos1386/zdravko/database/models" "github.com/golang-jwt/jwt/v5" "github.com/pkg/errors" ) diff --git a/internal/models/models.go b/internal/models/models.go deleted file mode 100644 index c4b57a2..0000000 --- a/internal/models/models.go +++ /dev/null @@ -1,47 +0,0 @@ -package models - -import ( - "time" - - "gorm.io/gorm" -) - -type OAuth2State struct { - State string `gorm:"primary_key"` - Expiry time.Time -} - -const ( - MonitorSuccess string = "SUCCESS" - MonitorFailure string = "FAILURE" - MonitorError string = "ERROR" - MonitorUnknown string = "UNKNOWN" -) - -type Monitor struct { - gorm.Model - Slug string `gorm:"unique"` - Name string `gorm:"unique"` - - Schedule string - WorkerGroups []WorkerGroup `gorm:"many2many:monitor_worker_groups;"` - - Script string `validate:"required"` - - History []MonitorHistory `gorm:"foreignKey:Monitor"` -} - -type MonitorHistory struct { - gorm.Model - Monitor uint - Status string - Note string -} - -type WorkerGroup struct { - gorm.Model - Name string `gorm:"unique"` - Slug string `gorm:"unique"` - - Monitors []Monitor `gorm:"many2many:monitor_worker_groups;"` -} diff --git a/internal/models/query/gen.go b/internal/models/query/gen.go deleted file mode 100644 index ce04cee..0000000 --- a/internal/models/query/gen.go +++ /dev/null @@ -1,127 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - "database/sql" - - "gorm.io/gorm" - - "gorm.io/gen" - - "gorm.io/plugin/dbresolver" -) - -var ( - Q = new(Query) - Monitor *monitor - MonitorHistory *monitorHistory - OAuth2State *oAuth2State - WorkerGroup *workerGroup -) - -func SetDefault(db *gorm.DB, opts ...gen.DOOption) { - *Q = *Use(db, opts...) - Monitor = &Q.Monitor - MonitorHistory = &Q.MonitorHistory - OAuth2State = &Q.OAuth2State - WorkerGroup = &Q.WorkerGroup -} - -func Use(db *gorm.DB, opts ...gen.DOOption) *Query { - return &Query{ - db: db, - Monitor: newMonitor(db, opts...), - MonitorHistory: newMonitorHistory(db, opts...), - OAuth2State: newOAuth2State(db, opts...), - WorkerGroup: newWorkerGroup(db, opts...), - } -} - -type Query struct { - db *gorm.DB - - Monitor monitor - MonitorHistory monitorHistory - OAuth2State oAuth2State - WorkerGroup workerGroup -} - -func (q *Query) Available() bool { return q.db != nil } - -func (q *Query) clone(db *gorm.DB) *Query { - return &Query{ - db: db, - Monitor: q.Monitor.clone(db), - MonitorHistory: q.MonitorHistory.clone(db), - OAuth2State: q.OAuth2State.clone(db), - WorkerGroup: q.WorkerGroup.clone(db), - } -} - -func (q *Query) ReadDB() *Query { - return q.ReplaceDB(q.db.Clauses(dbresolver.Read)) -} - -func (q *Query) WriteDB() *Query { - return q.ReplaceDB(q.db.Clauses(dbresolver.Write)) -} - -func (q *Query) ReplaceDB(db *gorm.DB) *Query { - return &Query{ - db: db, - Monitor: q.Monitor.replaceDB(db), - MonitorHistory: q.MonitorHistory.replaceDB(db), - OAuth2State: q.OAuth2State.replaceDB(db), - WorkerGroup: q.WorkerGroup.replaceDB(db), - } -} - -type queryCtx struct { - Monitor IMonitorDo - MonitorHistory IMonitorHistoryDo - OAuth2State IOAuth2StateDo - WorkerGroup IWorkerGroupDo -} - -func (q *Query) WithContext(ctx context.Context) *queryCtx { - return &queryCtx{ - Monitor: q.Monitor.WithContext(ctx), - MonitorHistory: q.MonitorHistory.WithContext(ctx), - OAuth2State: q.OAuth2State.WithContext(ctx), - WorkerGroup: q.WorkerGroup.WithContext(ctx), - } -} - -func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error { - return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...) -} - -func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx { - tx := q.db.Begin(opts...) - return &QueryTx{Query: q.clone(tx), Error: tx.Error} -} - -type QueryTx struct { - *Query - Error error -} - -func (q *QueryTx) Commit() error { - return q.db.Commit().Error -} - -func (q *QueryTx) Rollback() error { - return q.db.Rollback().Error -} - -func (q *QueryTx) SavePoint(name string) error { - return q.db.SavePoint(name).Error -} - -func (q *QueryTx) RollbackTo(name string) error { - return q.db.RollbackTo(name).Error -} diff --git a/internal/models/query/monitor_histories.gen.go b/internal/models/query/monitor_histories.gen.go deleted file mode 100644 index c3f2b3e..0000000 --- a/internal/models/query/monitor_histories.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 newMonitorHistory(db *gorm.DB, opts ...gen.DOOption) monitorHistory { - _monitorHistory := monitorHistory{} - - _monitorHistory.monitorHistoryDo.UseDB(db, opts...) - _monitorHistory.monitorHistoryDo.UseModel(&models.MonitorHistory{}) - - tableName := _monitorHistory.monitorHistoryDo.TableName() - _monitorHistory.ALL = field.NewAsterisk(tableName) - _monitorHistory.ID = field.NewUint(tableName, "id") - _monitorHistory.CreatedAt = field.NewTime(tableName, "created_at") - _monitorHistory.UpdatedAt = field.NewTime(tableName, "updated_at") - _monitorHistory.DeletedAt = field.NewField(tableName, "deleted_at") - _monitorHistory.Monitor = field.NewUint(tableName, "monitor") - _monitorHistory.Status = field.NewString(tableName, "status") - _monitorHistory.Note = field.NewString(tableName, "note") - - _monitorHistory.fillFieldMap() - - return _monitorHistory -} - -type monitorHistory struct { - monitorHistoryDo monitorHistoryDo - - ALL field.Asterisk - ID field.Uint - CreatedAt field.Time - UpdatedAt field.Time - DeletedAt field.Field - Monitor field.Uint - Status field.String - Note field.String - - fieldMap map[string]field.Expr -} - -func (m monitorHistory) Table(newTableName string) *monitorHistory { - m.monitorHistoryDo.UseTable(newTableName) - return m.updateTableName(newTableName) -} - -func (m monitorHistory) As(alias string) *monitorHistory { - m.monitorHistoryDo.DO = *(m.monitorHistoryDo.As(alias).(*gen.DO)) - return m.updateTableName(alias) -} - -func (m *monitorHistory) updateTableName(table string) *monitorHistory { - m.ALL = field.NewAsterisk(table) - m.ID = field.NewUint(table, "id") - m.CreatedAt = field.NewTime(table, "created_at") - m.UpdatedAt = field.NewTime(table, "updated_at") - m.DeletedAt = field.NewField(table, "deleted_at") - m.Monitor = field.NewUint(table, "monitor") - m.Status = field.NewString(table, "status") - m.Note = field.NewString(table, "note") - - m.fillFieldMap() - - return m -} - -func (m *monitorHistory) WithContext(ctx context.Context) IMonitorHistoryDo { - return m.monitorHistoryDo.WithContext(ctx) -} - -func (m monitorHistory) TableName() string { return m.monitorHistoryDo.TableName() } - -func (m monitorHistory) Alias() string { return m.monitorHistoryDo.Alias() } - -func (m monitorHistory) Columns(cols ...field.Expr) gen.Columns { - return m.monitorHistoryDo.Columns(cols...) -} - -func (m *monitorHistory) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := m.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (m *monitorHistory) fillFieldMap() { - m.fieldMap = make(map[string]field.Expr, 7) - m.fieldMap["id"] = m.ID - m.fieldMap["created_at"] = m.CreatedAt - m.fieldMap["updated_at"] = m.UpdatedAt - m.fieldMap["deleted_at"] = m.DeletedAt - m.fieldMap["monitor"] = m.Monitor - m.fieldMap["status"] = m.Status - m.fieldMap["note"] = m.Note -} - -func (m monitorHistory) clone(db *gorm.DB) monitorHistory { - m.monitorHistoryDo.ReplaceConnPool(db.Statement.ConnPool) - return m -} - -func (m monitorHistory) replaceDB(db *gorm.DB) monitorHistory { - m.monitorHistoryDo.ReplaceDB(db) - return m -} - -type monitorHistoryDo struct{ gen.DO } - -type IMonitorHistoryDo interface { - gen.SubQuery - Debug() IMonitorHistoryDo - WithContext(ctx context.Context) IMonitorHistoryDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IMonitorHistoryDo - WriteDB() IMonitorHistoryDo - As(alias string) gen.Dao - Session(config *gorm.Session) IMonitorHistoryDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IMonitorHistoryDo - Not(conds ...gen.Condition) IMonitorHistoryDo - Or(conds ...gen.Condition) IMonitorHistoryDo - Select(conds ...field.Expr) IMonitorHistoryDo - Where(conds ...gen.Condition) IMonitorHistoryDo - Order(conds ...field.Expr) IMonitorHistoryDo - Distinct(cols ...field.Expr) IMonitorHistoryDo - Omit(cols ...field.Expr) IMonitorHistoryDo - Join(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo - LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo - RightJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo - Group(cols ...field.Expr) IMonitorHistoryDo - Having(conds ...gen.Condition) IMonitorHistoryDo - Limit(limit int) IMonitorHistoryDo - Offset(offset int) IMonitorHistoryDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorHistoryDo - Unscoped() IMonitorHistoryDo - Create(values ...*models.MonitorHistory) error - CreateInBatches(values []*models.MonitorHistory, batchSize int) error - Save(values ...*models.MonitorHistory) error - First() (*models.MonitorHistory, error) - Take() (*models.MonitorHistory, error) - Last() (*models.MonitorHistory, error) - Find() ([]*models.MonitorHistory, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.MonitorHistory, err error) - FindInBatches(result *[]*models.MonitorHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.MonitorHistory) (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) IMonitorHistoryDo - Assign(attrs ...field.AssignExpr) IMonitorHistoryDo - Joins(fields ...field.RelationField) IMonitorHistoryDo - Preload(fields ...field.RelationField) IMonitorHistoryDo - FirstOrInit() (*models.MonitorHistory, error) - FirstOrCreate() (*models.MonitorHistory, error) - FindByPage(offset int, limit int) (result []*models.MonitorHistory, 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) IMonitorHistoryDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (m monitorHistoryDo) Debug() IMonitorHistoryDo { - return m.withDO(m.DO.Debug()) -} - -func (m monitorHistoryDo) WithContext(ctx context.Context) IMonitorHistoryDo { - return m.withDO(m.DO.WithContext(ctx)) -} - -func (m monitorHistoryDo) ReadDB() IMonitorHistoryDo { - return m.Clauses(dbresolver.Read) -} - -func (m monitorHistoryDo) WriteDB() IMonitorHistoryDo { - return m.Clauses(dbresolver.Write) -} - -func (m monitorHistoryDo) Session(config *gorm.Session) IMonitorHistoryDo { - return m.withDO(m.DO.Session(config)) -} - -func (m monitorHistoryDo) Clauses(conds ...clause.Expression) IMonitorHistoryDo { - return m.withDO(m.DO.Clauses(conds...)) -} - -func (m monitorHistoryDo) Returning(value interface{}, columns ...string) IMonitorHistoryDo { - return m.withDO(m.DO.Returning(value, columns...)) -} - -func (m monitorHistoryDo) Not(conds ...gen.Condition) IMonitorHistoryDo { - return m.withDO(m.DO.Not(conds...)) -} - -func (m monitorHistoryDo) Or(conds ...gen.Condition) IMonitorHistoryDo { - return m.withDO(m.DO.Or(conds...)) -} - -func (m monitorHistoryDo) Select(conds ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.Select(conds...)) -} - -func (m monitorHistoryDo) Where(conds ...gen.Condition) IMonitorHistoryDo { - return m.withDO(m.DO.Where(conds...)) -} - -func (m monitorHistoryDo) Order(conds ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.Order(conds...)) -} - -func (m monitorHistoryDo) Distinct(cols ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.Distinct(cols...)) -} - -func (m monitorHistoryDo) Omit(cols ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.Omit(cols...)) -} - -func (m monitorHistoryDo) Join(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.Join(table, on...)) -} - -func (m monitorHistoryDo) LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.LeftJoin(table, on...)) -} - -func (m monitorHistoryDo) RightJoin(table schema.Tabler, on ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.RightJoin(table, on...)) -} - -func (m monitorHistoryDo) Group(cols ...field.Expr) IMonitorHistoryDo { - return m.withDO(m.DO.Group(cols...)) -} - -func (m monitorHistoryDo) Having(conds ...gen.Condition) IMonitorHistoryDo { - return m.withDO(m.DO.Having(conds...)) -} - -func (m monitorHistoryDo) Limit(limit int) IMonitorHistoryDo { - return m.withDO(m.DO.Limit(limit)) -} - -func (m monitorHistoryDo) Offset(offset int) IMonitorHistoryDo { - return m.withDO(m.DO.Offset(offset)) -} - -func (m monitorHistoryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorHistoryDo { - return m.withDO(m.DO.Scopes(funcs...)) -} - -func (m monitorHistoryDo) Unscoped() IMonitorHistoryDo { - return m.withDO(m.DO.Unscoped()) -} - -func (m monitorHistoryDo) Create(values ...*models.MonitorHistory) error { - if len(values) == 0 { - return nil - } - return m.DO.Create(values) -} - -func (m monitorHistoryDo) CreateInBatches(values []*models.MonitorHistory, batchSize int) error { - return m.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (m monitorHistoryDo) Save(values ...*models.MonitorHistory) error { - if len(values) == 0 { - return nil - } - return m.DO.Save(values) -} - -func (m monitorHistoryDo) First() (*models.MonitorHistory, error) { - if result, err := m.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.MonitorHistory), nil - } -} - -func (m monitorHistoryDo) Take() (*models.MonitorHistory, error) { - if result, err := m.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.MonitorHistory), nil - } -} - -func (m monitorHistoryDo) Last() (*models.MonitorHistory, error) { - if result, err := m.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.MonitorHistory), nil - } -} - -func (m monitorHistoryDo) Find() ([]*models.MonitorHistory, error) { - result, err := m.DO.Find() - return result.([]*models.MonitorHistory), err -} - -func (m monitorHistoryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.MonitorHistory, err error) { - buf := make([]*models.MonitorHistory, 0, batchSize) - err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (m monitorHistoryDo) FindInBatches(result *[]*models.MonitorHistory, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return m.DO.FindInBatches(result, batchSize, fc) -} - -func (m monitorHistoryDo) Attrs(attrs ...field.AssignExpr) IMonitorHistoryDo { - return m.withDO(m.DO.Attrs(attrs...)) -} - -func (m monitorHistoryDo) Assign(attrs ...field.AssignExpr) IMonitorHistoryDo { - return m.withDO(m.DO.Assign(attrs...)) -} - -func (m monitorHistoryDo) Joins(fields ...field.RelationField) IMonitorHistoryDo { - for _, _f := range fields { - m = *m.withDO(m.DO.Joins(_f)) - } - return &m -} - -func (m monitorHistoryDo) Preload(fields ...field.RelationField) IMonitorHistoryDo { - for _, _f := range fields { - m = *m.withDO(m.DO.Preload(_f)) - } - return &m -} - -func (m monitorHistoryDo) FirstOrInit() (*models.MonitorHistory, error) { - if result, err := m.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.MonitorHistory), nil - } -} - -func (m monitorHistoryDo) FirstOrCreate() (*models.MonitorHistory, error) { - if result, err := m.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.MonitorHistory), nil - } -} - -func (m monitorHistoryDo) FindByPage(offset int, limit int) (result []*models.MonitorHistory, count int64, err error) { - result, err = m.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = m.Offset(-1).Limit(-1).Count() - return -} - -func (m monitorHistoryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = m.Count() - if err != nil { - return - } - - err = m.Offset(offset).Limit(limit).Scan(result) - return -} - -func (m monitorHistoryDo) Scan(result interface{}) (err error) { - return m.DO.Scan(result) -} - -func (m monitorHistoryDo) Delete(models ...*models.MonitorHistory) (result gen.ResultInfo, err error) { - return m.DO.Delete(models) -} - -func (m *monitorHistoryDo) withDO(do gen.Dao) *monitorHistoryDo { - m.DO = *do.(*gen.DO) - return m -} diff --git a/internal/models/query/monitors.gen.go b/internal/models/query/monitors.gen.go deleted file mode 100644 index 294a520..0000000 --- a/internal/models/query/monitors.gen.go +++ /dev/null @@ -1,604 +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 newMonitor(db *gorm.DB, opts ...gen.DOOption) monitor { - _monitor := monitor{} - - _monitor.monitorDo.UseDB(db, opts...) - _monitor.monitorDo.UseModel(&models.Monitor{}) - - tableName := _monitor.monitorDo.TableName() - _monitor.ALL = field.NewAsterisk(tableName) - _monitor.ID = field.NewUint(tableName, "id") - _monitor.CreatedAt = field.NewTime(tableName, "created_at") - _monitor.UpdatedAt = field.NewTime(tableName, "updated_at") - _monitor.DeletedAt = field.NewField(tableName, "deleted_at") - _monitor.Slug = field.NewString(tableName, "slug") - _monitor.Name = field.NewString(tableName, "name") - _monitor.Schedule = field.NewString(tableName, "schedule") - _monitor.Script = field.NewString(tableName, "script") - _monitor.History = monitorHasManyHistory{ - db: db.Session(&gorm.Session{}), - - 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 -} - -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 - Script field.String - History monitorHasManyHistory - - WorkerGroups monitorManyToManyWorkerGroups - - fieldMap map[string]field.Expr -} - -func (m monitor) Table(newTableName string) *monitor { - m.monitorDo.UseTable(newTableName) - return m.updateTableName(newTableName) -} - -func (m monitor) As(alias string) *monitor { - m.monitorDo.DO = *(m.monitorDo.As(alias).(*gen.DO)) - return m.updateTableName(alias) -} - -func (m *monitor) updateTableName(table string) *monitor { - m.ALL = field.NewAsterisk(table) - m.ID = field.NewUint(table, "id") - m.CreatedAt = field.NewTime(table, "created_at") - m.UpdatedAt = field.NewTime(table, "updated_at") - m.DeletedAt = field.NewField(table, "deleted_at") - m.Slug = field.NewString(table, "slug") - m.Name = field.NewString(table, "name") - m.Schedule = field.NewString(table, "schedule") - m.Script = field.NewString(table, "script") - - m.fillFieldMap() - - return m -} - -func (m *monitor) WithContext(ctx context.Context) IMonitorDo { return m.monitorDo.WithContext(ctx) } - -func (m monitor) TableName() string { return m.monitorDo.TableName() } - -func (m monitor) Alias() string { return m.monitorDo.Alias() } - -func (m monitor) Columns(cols ...field.Expr) gen.Columns { return m.monitorDo.Columns(cols...) } - -func (m *monitor) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := m.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (m *monitor) fillFieldMap() { - m.fieldMap = make(map[string]field.Expr, 10) - m.fieldMap["id"] = m.ID - m.fieldMap["created_at"] = m.CreatedAt - m.fieldMap["updated_at"] = m.UpdatedAt - m.fieldMap["deleted_at"] = m.DeletedAt - m.fieldMap["slug"] = m.Slug - m.fieldMap["name"] = m.Name - m.fieldMap["schedule"] = m.Schedule - m.fieldMap["script"] = m.Script - -} - -func (m monitor) clone(db *gorm.DB) monitor { - m.monitorDo.ReplaceConnPool(db.Statement.ConnPool) - return m -} - -func (m monitor) replaceDB(db *gorm.DB) monitor { - m.monitorDo.ReplaceDB(db) - return m -} - -type monitorHasManyHistory struct { - db *gorm.DB - - field.RelationField -} - -func (a monitorHasManyHistory) Where(conds ...field.Expr) *monitorHasManyHistory { - 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 monitorHasManyHistory) WithContext(ctx context.Context) *monitorHasManyHistory { - a.db = a.db.WithContext(ctx) - return &a -} - -func (a monitorHasManyHistory) Session(session *gorm.Session) *monitorHasManyHistory { - a.db = a.db.Session(session) - return &a -} - -func (a monitorHasManyHistory) Model(m *models.Monitor) *monitorHasManyHistoryTx { - return &monitorHasManyHistoryTx{a.db.Model(m).Association(a.Name())} -} - -type monitorHasManyHistoryTx struct{ tx *gorm.Association } - -func (a monitorHasManyHistoryTx) Find() (result []*models.MonitorHistory, err error) { - return result, a.tx.Find(&result) -} - -func (a monitorHasManyHistoryTx) Append(values ...*models.MonitorHistory) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Append(targetValues...) -} - -func (a monitorHasManyHistoryTx) Replace(values ...*models.MonitorHistory) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Replace(targetValues...) -} - -func (a monitorHasManyHistoryTx) Delete(values ...*models.MonitorHistory) (err error) { - targetValues := make([]interface{}, len(values)) - for i, v := range values { - targetValues[i] = v - } - return a.tx.Delete(targetValues...) -} - -func (a monitorHasManyHistoryTx) Clear() error { - return a.tx.Clear() -} - -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 { - gen.SubQuery - Debug() IMonitorDo - WithContext(ctx context.Context) IMonitorDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IMonitorDo - WriteDB() IMonitorDo - As(alias string) gen.Dao - Session(config *gorm.Session) IMonitorDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IMonitorDo - Not(conds ...gen.Condition) IMonitorDo - Or(conds ...gen.Condition) IMonitorDo - Select(conds ...field.Expr) IMonitorDo - Where(conds ...gen.Condition) IMonitorDo - Order(conds ...field.Expr) IMonitorDo - Distinct(cols ...field.Expr) IMonitorDo - Omit(cols ...field.Expr) IMonitorDo - Join(table schema.Tabler, on ...field.Expr) IMonitorDo - LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorDo - RightJoin(table schema.Tabler, on ...field.Expr) IMonitorDo - Group(cols ...field.Expr) IMonitorDo - Having(conds ...gen.Condition) IMonitorDo - Limit(limit int) IMonitorDo - Offset(offset int) IMonitorDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorDo - Unscoped() IMonitorDo - Create(values ...*models.Monitor) error - CreateInBatches(values []*models.Monitor, batchSize int) error - Save(values ...*models.Monitor) error - First() (*models.Monitor, error) - Take() (*models.Monitor, error) - Last() (*models.Monitor, error) - Find() ([]*models.Monitor, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Monitor, err error) - FindInBatches(result *[]*models.Monitor, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.Monitor) (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) IMonitorDo - Assign(attrs ...field.AssignExpr) IMonitorDo - Joins(fields ...field.RelationField) IMonitorDo - Preload(fields ...field.RelationField) IMonitorDo - FirstOrInit() (*models.Monitor, error) - FirstOrCreate() (*models.Monitor, error) - FindByPage(offset int, limit int) (result []*models.Monitor, 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) IMonitorDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (m monitorDo) Debug() IMonitorDo { - return m.withDO(m.DO.Debug()) -} - -func (m monitorDo) WithContext(ctx context.Context) IMonitorDo { - return m.withDO(m.DO.WithContext(ctx)) -} - -func (m monitorDo) ReadDB() IMonitorDo { - return m.Clauses(dbresolver.Read) -} - -func (m monitorDo) WriteDB() IMonitorDo { - return m.Clauses(dbresolver.Write) -} - -func (m monitorDo) Session(config *gorm.Session) IMonitorDo { - return m.withDO(m.DO.Session(config)) -} - -func (m monitorDo) Clauses(conds ...clause.Expression) IMonitorDo { - return m.withDO(m.DO.Clauses(conds...)) -} - -func (m monitorDo) Returning(value interface{}, columns ...string) IMonitorDo { - return m.withDO(m.DO.Returning(value, columns...)) -} - -func (m monitorDo) Not(conds ...gen.Condition) IMonitorDo { - return m.withDO(m.DO.Not(conds...)) -} - -func (m monitorDo) Or(conds ...gen.Condition) IMonitorDo { - return m.withDO(m.DO.Or(conds...)) -} - -func (m monitorDo) Select(conds ...field.Expr) IMonitorDo { - return m.withDO(m.DO.Select(conds...)) -} - -func (m monitorDo) Where(conds ...gen.Condition) IMonitorDo { - return m.withDO(m.DO.Where(conds...)) -} - -func (m monitorDo) Order(conds ...field.Expr) IMonitorDo { - return m.withDO(m.DO.Order(conds...)) -} - -func (m monitorDo) Distinct(cols ...field.Expr) IMonitorDo { - return m.withDO(m.DO.Distinct(cols...)) -} - -func (m monitorDo) Omit(cols ...field.Expr) IMonitorDo { - return m.withDO(m.DO.Omit(cols...)) -} - -func (m monitorDo) Join(table schema.Tabler, on ...field.Expr) IMonitorDo { - return m.withDO(m.DO.Join(table, on...)) -} - -func (m monitorDo) LeftJoin(table schema.Tabler, on ...field.Expr) IMonitorDo { - return m.withDO(m.DO.LeftJoin(table, on...)) -} - -func (m monitorDo) RightJoin(table schema.Tabler, on ...field.Expr) IMonitorDo { - return m.withDO(m.DO.RightJoin(table, on...)) -} - -func (m monitorDo) Group(cols ...field.Expr) IMonitorDo { - return m.withDO(m.DO.Group(cols...)) -} - -func (m monitorDo) Having(conds ...gen.Condition) IMonitorDo { - return m.withDO(m.DO.Having(conds...)) -} - -func (m monitorDo) Limit(limit int) IMonitorDo { - return m.withDO(m.DO.Limit(limit)) -} - -func (m monitorDo) Offset(offset int) IMonitorDo { - return m.withDO(m.DO.Offset(offset)) -} - -func (m monitorDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IMonitorDo { - return m.withDO(m.DO.Scopes(funcs...)) -} - -func (m monitorDo) Unscoped() IMonitorDo { - return m.withDO(m.DO.Unscoped()) -} - -func (m monitorDo) Create(values ...*models.Monitor) error { - if len(values) == 0 { - return nil - } - return m.DO.Create(values) -} - -func (m monitorDo) CreateInBatches(values []*models.Monitor, batchSize int) error { - return m.DO.CreateInBatches(values, batchSize) -} - -// Save : !!! underlying implementation is different with GORM -// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) -func (m monitorDo) Save(values ...*models.Monitor) error { - if len(values) == 0 { - return nil - } - return m.DO.Save(values) -} - -func (m monitorDo) First() (*models.Monitor, error) { - if result, err := m.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.Monitor), nil - } -} - -func (m monitorDo) Take() (*models.Monitor, error) { - if result, err := m.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.Monitor), nil - } -} - -func (m monitorDo) Last() (*models.Monitor, error) { - if result, err := m.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.Monitor), nil - } -} - -func (m monitorDo) Find() ([]*models.Monitor, error) { - result, err := m.DO.Find() - return result.([]*models.Monitor), err -} - -func (m monitorDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Monitor, err error) { - buf := make([]*models.Monitor, 0, batchSize) - err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { - defer func() { results = append(results, buf...) }() - return fc(tx, batch) - }) - return results, err -} - -func (m monitorDo) FindInBatches(result *[]*models.Monitor, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return m.DO.FindInBatches(result, batchSize, fc) -} - -func (m monitorDo) Attrs(attrs ...field.AssignExpr) IMonitorDo { - return m.withDO(m.DO.Attrs(attrs...)) -} - -func (m monitorDo) Assign(attrs ...field.AssignExpr) IMonitorDo { - return m.withDO(m.DO.Assign(attrs...)) -} - -func (m monitorDo) Joins(fields ...field.RelationField) IMonitorDo { - for _, _f := range fields { - m = *m.withDO(m.DO.Joins(_f)) - } - return &m -} - -func (m monitorDo) Preload(fields ...field.RelationField) IMonitorDo { - for _, _f := range fields { - m = *m.withDO(m.DO.Preload(_f)) - } - return &m -} - -func (m monitorDo) FirstOrInit() (*models.Monitor, error) { - if result, err := m.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.Monitor), nil - } -} - -func (m monitorDo) FirstOrCreate() (*models.Monitor, error) { - if result, err := m.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.Monitor), nil - } -} - -func (m monitorDo) FindByPage(offset int, limit int) (result []*models.Monitor, count int64, err error) { - result, err = m.Offset(offset).Limit(limit).Find() - if err != nil { - return - } - - if size := len(result); 0 < limit && 0 < size && size < limit { - count = int64(size + offset) - return - } - - count, err = m.Offset(-1).Limit(-1).Count() - return -} - -func (m monitorDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = m.Count() - if err != nil { - return - } - - err = m.Offset(offset).Limit(limit).Scan(result) - return -} - -func (m monitorDo) Scan(result interface{}) (err error) { - return m.DO.Scan(result) -} - -func (m monitorDo) Delete(models ...*models.Monitor) (result gen.ResultInfo, err error) { - return m.DO.Delete(models) -} - -func (m *monitorDo) withDO(do gen.Dao) *monitorDo { - m.DO = *do.(*gen.DO) - return m -} diff --git a/internal/models/query/o_auth2_states.gen.go b/internal/models/query/o_auth2_states.gen.go deleted file mode 100644 index 56aa48a..0000000 --- a/internal/models/query/o_auth2_states.gen.go +++ /dev/null @@ -1,394 +0,0 @@ -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. -// Code generated by gorm.io/gen. DO NOT EDIT. - -package query - -import ( - "context" - - "gorm.io/gorm" - "gorm.io/gorm/clause" - "gorm.io/gorm/schema" - - "gorm.io/gen" - "gorm.io/gen/field" - - "gorm.io/plugin/dbresolver" - - "code.tjo.space/mentos1386/zdravko/internal/models" -) - -func newOAuth2State(db *gorm.DB, opts ...gen.DOOption) oAuth2State { - _oAuth2State := oAuth2State{} - - _oAuth2State.oAuth2StateDo.UseDB(db, opts...) - _oAuth2State.oAuth2StateDo.UseModel(&models.OAuth2State{}) - - tableName := _oAuth2State.oAuth2StateDo.TableName() - _oAuth2State.ALL = field.NewAsterisk(tableName) - _oAuth2State.State = field.NewString(tableName, "state") - _oAuth2State.Expiry = field.NewTime(tableName, "expiry") - - _oAuth2State.fillFieldMap() - - return _oAuth2State -} - -type oAuth2State struct { - oAuth2StateDo oAuth2StateDo - - ALL field.Asterisk - State field.String - Expiry field.Time - - fieldMap map[string]field.Expr -} - -func (o oAuth2State) Table(newTableName string) *oAuth2State { - o.oAuth2StateDo.UseTable(newTableName) - return o.updateTableName(newTableName) -} - -func (o oAuth2State) As(alias string) *oAuth2State { - o.oAuth2StateDo.DO = *(o.oAuth2StateDo.As(alias).(*gen.DO)) - return o.updateTableName(alias) -} - -func (o *oAuth2State) updateTableName(table string) *oAuth2State { - o.ALL = field.NewAsterisk(table) - o.State = field.NewString(table, "state") - o.Expiry = field.NewTime(table, "expiry") - - o.fillFieldMap() - - return o -} - -func (o *oAuth2State) WithContext(ctx context.Context) IOAuth2StateDo { - return o.oAuth2StateDo.WithContext(ctx) -} - -func (o oAuth2State) TableName() string { return o.oAuth2StateDo.TableName() } - -func (o oAuth2State) Alias() string { return o.oAuth2StateDo.Alias() } - -func (o oAuth2State) Columns(cols ...field.Expr) gen.Columns { return o.oAuth2StateDo.Columns(cols...) } - -func (o *oAuth2State) GetFieldByName(fieldName string) (field.OrderExpr, bool) { - _f, ok := o.fieldMap[fieldName] - if !ok || _f == nil { - return nil, false - } - _oe, ok := _f.(field.OrderExpr) - return _oe, ok -} - -func (o *oAuth2State) fillFieldMap() { - o.fieldMap = make(map[string]field.Expr, 2) - o.fieldMap["state"] = o.State - o.fieldMap["expiry"] = o.Expiry -} - -func (o oAuth2State) clone(db *gorm.DB) oAuth2State { - o.oAuth2StateDo.ReplaceConnPool(db.Statement.ConnPool) - return o -} - -func (o oAuth2State) replaceDB(db *gorm.DB) oAuth2State { - o.oAuth2StateDo.ReplaceDB(db) - return o -} - -type oAuth2StateDo struct{ gen.DO } - -type IOAuth2StateDo interface { - gen.SubQuery - Debug() IOAuth2StateDo - WithContext(ctx context.Context) IOAuth2StateDo - WithResult(fc func(tx gen.Dao)) gen.ResultInfo - ReplaceDB(db *gorm.DB) - ReadDB() IOAuth2StateDo - WriteDB() IOAuth2StateDo - As(alias string) gen.Dao - Session(config *gorm.Session) IOAuth2StateDo - Columns(cols ...field.Expr) gen.Columns - Clauses(conds ...clause.Expression) IOAuth2StateDo - Not(conds ...gen.Condition) IOAuth2StateDo - Or(conds ...gen.Condition) IOAuth2StateDo - Select(conds ...field.Expr) IOAuth2StateDo - Where(conds ...gen.Condition) IOAuth2StateDo - Order(conds ...field.Expr) IOAuth2StateDo - Distinct(cols ...field.Expr) IOAuth2StateDo - Omit(cols ...field.Expr) IOAuth2StateDo - Join(table schema.Tabler, on ...field.Expr) IOAuth2StateDo - LeftJoin(table schema.Tabler, on ...field.Expr) IOAuth2StateDo - RightJoin(table schema.Tabler, on ...field.Expr) IOAuth2StateDo - Group(cols ...field.Expr) IOAuth2StateDo - Having(conds ...gen.Condition) IOAuth2StateDo - Limit(limit int) IOAuth2StateDo - Offset(offset int) IOAuth2StateDo - Count() (count int64, err error) - Scopes(funcs ...func(gen.Dao) gen.Dao) IOAuth2StateDo - Unscoped() IOAuth2StateDo - Create(values ...*models.OAuth2State) error - CreateInBatches(values []*models.OAuth2State, batchSize int) error - Save(values ...*models.OAuth2State) error - First() (*models.OAuth2State, error) - Take() (*models.OAuth2State, error) - Last() (*models.OAuth2State, error) - Find() ([]*models.OAuth2State, error) - FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.OAuth2State, err error) - FindInBatches(result *[]*models.OAuth2State, batchSize int, fc func(tx gen.Dao, batch int) error) error - Pluck(column field.Expr, dest interface{}) error - Delete(...*models.OAuth2State) (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) IOAuth2StateDo - Assign(attrs ...field.AssignExpr) IOAuth2StateDo - Joins(fields ...field.RelationField) IOAuth2StateDo - Preload(fields ...field.RelationField) IOAuth2StateDo - FirstOrInit() (*models.OAuth2State, error) - FirstOrCreate() (*models.OAuth2State, error) - FindByPage(offset int, limit int) (result []*models.OAuth2State, 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) IOAuth2StateDo - UnderlyingDB() *gorm.DB - schema.Tabler -} - -func (o oAuth2StateDo) Debug() IOAuth2StateDo { - return o.withDO(o.DO.Debug()) -} - -func (o oAuth2StateDo) WithContext(ctx context.Context) IOAuth2StateDo { - return o.withDO(o.DO.WithContext(ctx)) -} - -func (o oAuth2StateDo) ReadDB() IOAuth2StateDo { - return o.Clauses(dbresolver.Read) -} - -func (o oAuth2StateDo) WriteDB() IOAuth2StateDo { - return o.Clauses(dbresolver.Write) -} - -func (o oAuth2StateDo) Session(config *gorm.Session) IOAuth2StateDo { - return o.withDO(o.DO.Session(config)) -} - -func (o oAuth2StateDo) Clauses(conds ...clause.Expression) IOAuth2StateDo { - return o.withDO(o.DO.Clauses(conds...)) -} - -func (o oAuth2StateDo) Returning(value interface{}, columns ...string) IOAuth2StateDo { - return o.withDO(o.DO.Returning(value, columns...)) -} - -func (o oAuth2StateDo) Not(conds ...gen.Condition) IOAuth2StateDo { - return o.withDO(o.DO.Not(conds...)) -} - -func (o oAuth2StateDo) Or(conds ...gen.Condition) IOAuth2StateDo { - return o.withDO(o.DO.Or(conds...)) -} - -func (o oAuth2StateDo) Select(conds ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.Select(conds...)) -} - -func (o oAuth2StateDo) Where(conds ...gen.Condition) IOAuth2StateDo { - return o.withDO(o.DO.Where(conds...)) -} - -func (o oAuth2StateDo) Order(conds ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.Order(conds...)) -} - -func (o oAuth2StateDo) Distinct(cols ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.Distinct(cols...)) -} - -func (o oAuth2StateDo) Omit(cols ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.Omit(cols...)) -} - -func (o oAuth2StateDo) Join(table schema.Tabler, on ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.Join(table, on...)) -} - -func (o oAuth2StateDo) LeftJoin(table schema.Tabler, on ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.LeftJoin(table, on...)) -} - -func (o oAuth2StateDo) RightJoin(table schema.Tabler, on ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.RightJoin(table, on...)) -} - -func (o oAuth2StateDo) Group(cols ...field.Expr) IOAuth2StateDo { - return o.withDO(o.DO.Group(cols...)) -} - -func (o oAuth2StateDo) Having(conds ...gen.Condition) IOAuth2StateDo { - return o.withDO(o.DO.Having(conds...)) -} - -func (o oAuth2StateDo) Limit(limit int) IOAuth2StateDo { - return o.withDO(o.DO.Limit(limit)) -} - -func (o oAuth2StateDo) Offset(offset int) IOAuth2StateDo { - return o.withDO(o.DO.Offset(offset)) -} - -func (o oAuth2StateDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IOAuth2StateDo { - return o.withDO(o.DO.Scopes(funcs...)) -} - -func (o oAuth2StateDo) Unscoped() IOAuth2StateDo { - return o.withDO(o.DO.Unscoped()) -} - -func (o oAuth2StateDo) Create(values ...*models.OAuth2State) error { - if len(values) == 0 { - return nil - } - return o.DO.Create(values) -} - -func (o oAuth2StateDo) CreateInBatches(values []*models.OAuth2State, batchSize int) error { - return o.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 (o oAuth2StateDo) Save(values ...*models.OAuth2State) error { - if len(values) == 0 { - return nil - } - return o.DO.Save(values) -} - -func (o oAuth2StateDo) First() (*models.OAuth2State, error) { - if result, err := o.DO.First(); err != nil { - return nil, err - } else { - return result.(*models.OAuth2State), nil - } -} - -func (o oAuth2StateDo) Take() (*models.OAuth2State, error) { - if result, err := o.DO.Take(); err != nil { - return nil, err - } else { - return result.(*models.OAuth2State), nil - } -} - -func (o oAuth2StateDo) Last() (*models.OAuth2State, error) { - if result, err := o.DO.Last(); err != nil { - return nil, err - } else { - return result.(*models.OAuth2State), nil - } -} - -func (o oAuth2StateDo) Find() ([]*models.OAuth2State, error) { - result, err := o.DO.Find() - return result.([]*models.OAuth2State), err -} - -func (o oAuth2StateDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.OAuth2State, err error) { - buf := make([]*models.OAuth2State, 0, batchSize) - err = o.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 (o oAuth2StateDo) FindInBatches(result *[]*models.OAuth2State, batchSize int, fc func(tx gen.Dao, batch int) error) error { - return o.DO.FindInBatches(result, batchSize, fc) -} - -func (o oAuth2StateDo) Attrs(attrs ...field.AssignExpr) IOAuth2StateDo { - return o.withDO(o.DO.Attrs(attrs...)) -} - -func (o oAuth2StateDo) Assign(attrs ...field.AssignExpr) IOAuth2StateDo { - return o.withDO(o.DO.Assign(attrs...)) -} - -func (o oAuth2StateDo) Joins(fields ...field.RelationField) IOAuth2StateDo { - for _, _f := range fields { - o = *o.withDO(o.DO.Joins(_f)) - } - return &o -} - -func (o oAuth2StateDo) Preload(fields ...field.RelationField) IOAuth2StateDo { - for _, _f := range fields { - o = *o.withDO(o.DO.Preload(_f)) - } - return &o -} - -func (o oAuth2StateDo) FirstOrInit() (*models.OAuth2State, error) { - if result, err := o.DO.FirstOrInit(); err != nil { - return nil, err - } else { - return result.(*models.OAuth2State), nil - } -} - -func (o oAuth2StateDo) FirstOrCreate() (*models.OAuth2State, error) { - if result, err := o.DO.FirstOrCreate(); err != nil { - return nil, err - } else { - return result.(*models.OAuth2State), nil - } -} - -func (o oAuth2StateDo) FindByPage(offset int, limit int) (result []*models.OAuth2State, count int64, err error) { - result, err = o.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 = o.Offset(-1).Limit(-1).Count() - return -} - -func (o oAuth2StateDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { - count, err = o.Count() - if err != nil { - return - } - - err = o.Offset(offset).Limit(limit).Scan(result) - return -} - -func (o oAuth2StateDo) Scan(result interface{}) (err error) { - return o.DO.Scan(result) -} - -func (o oAuth2StateDo) Delete(models ...*models.OAuth2State) (result gen.ResultInfo, err error) { - return o.DO.Delete(models) -} - -func (o *oAuth2StateDo) withDO(do gen.Dao) *oAuth2StateDo { - o.DO = *do.(*gen.DO) - return o -} diff --git a/internal/models/query/worker_groups.gen.go b/internal/models/query/worker_groups.gen.go deleted file mode 100644 index d14f9dc..0000000 --- a/internal/models/query/worker_groups.gen.go +++ /dev/null @@ -1,516 +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 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/services/monitor.go b/internal/services/monitor.go index 459e2a7..8e3534e 100644 --- a/internal/services/monitor.go +++ b/internal/services/monitor.go @@ -5,62 +5,193 @@ import ( "log" "time" - "code.tjo.space/mentos1386/zdravko/internal/models" - "code.tjo.space/mentos1386/zdravko/internal/models/query" + "code.tjo.space/mentos1386/zdravko/database/models" "code.tjo.space/mentos1386/zdravko/internal/workflows" + "github.com/jmoiron/sqlx" "go.temporal.io/sdk/client" "go.temporal.io/sdk/temporal" - "gorm.io/gorm" + "golang.org/x/exp/maps" ) func getScheduleId(monitor *models.Monitor, group string) string { return "monitor-" + monitor.Slug + "-" + group } -func CreateMonitor(ctx context.Context, query *query.Query, monitor *models.Monitor) error { - return query.Monitor.WithContext(ctx).Create(monitor) -} - -func UpdateMonitor(ctx context.Context, q *query.Query, monitor *models.Monitor) error { - _, err := q.Monitor.WithContext(ctx).Where( - q.Monitor.Slug.Eq(monitor.Slug), - ).Updates(monitor) - +func CreateMonitor(ctx context.Context, db *sqlx.DB, monitor *models.Monitor) error { + _, err := db.NamedExecContext(ctx, + "INSERT INTO monitors (slug, name, script, schedule) VALUES (:slug, :name, :script, :schedule)", + 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 UpdateMonitor(ctx context.Context, db *sqlx.DB, monitor *models.Monitor) error { + _, err := db.NamedExecContext(ctx, + "UPDATE monitors SET name=:name, script=:script, schedule=:schedule WHERE slug=:slug", + monitor, + ) + return err } -func GetMonitor(ctx context.Context, q *query.Query, slug string) (*models.Monitor, error) { - return q.Monitor.WithContext(ctx).Where( - q.Monitor.Slug.Eq(slug), - ).Preload( - q.Monitor.WorkerGroups, - q.Monitor.History, - ).First() +func UpdateMonitorWorkerGroups(ctx context.Context, db *sqlx.DB, monitor *models.Monitor, workerGroups []*models.WorkerGroup) error { + tx, err := db.BeginTxx(ctx, nil) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, + "DELETE FROM monitor_worker_groups WHERE monitor_slug=$1", + monitor.Slug, + ) + if err != nil { + tx.Rollback() + return err + } + for _, group := range workerGroups { + _, err = tx.ExecContext(ctx, + "INSERT INTO monitor_worker_groups (monitor_slug, worker_group_slug) VALUES ($1, $2)", + monitor.Slug, + group.Slug, + ) + if err != nil { + tx.Rollback() + return err + } + } + return tx.Commit() } -func GetMonitors(ctx context.Context, q *query.Query) ([]*models.Monitor, error) { - return q.Monitor.WithContext(ctx).Preload( - q.Monitor.History, - ).Preload( - q.Monitor.WorkerGroups, - ).Find() +func GetMonitor(ctx context.Context, db *sqlx.DB, slug string) (*models.Monitor, error) { + monitor := &models.Monitor{} + err := db.GetContext(ctx, monitor, + "SELECT * FROM monitors WHERE slug=$1 AND deleted_at IS NULL", + slug, + ) + return monitor, err +} + +func GetMonitorWithWorkerGroups(ctx context.Context, db *sqlx.DB, slug string) (*models.MonitorWithWorkerGroups, error) { + rows, err := db.QueryContext(ctx, + ` +SELECT + monitors.slug, + monitors.name, + monitors.script, + monitors.schedule, + monitors.created_at, + monitors.updated_at, + monitors.deleted_at, + worker_groups.name as worker_group_name +FROM monitors +LEFT OUTER JOIN monitor_worker_groups ON monitors.slug = monitor_worker_groups.monitor_slug +LEFT OUTER JOIN worker_groups ON monitor_worker_groups.worker_group_slug = worker_groups.slug +WHERE monitors.slug=$1 AND monitors.deleted_at IS NULL +`, + slug, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + monitor := &models.MonitorWithWorkerGroups{} + + for rows.Next() { + var workerGroupName *string + err = rows.Scan( + &monitor.Slug, + &monitor.Name, + &monitor.Script, + &monitor.Schedule, + &monitor.CreatedAt, + &monitor.UpdatedAt, + &monitor.DeletedAt, + &workerGroupName, + ) + if err != nil { + return nil, err + } + if workerGroupName != nil { + monitor.WorkerGroups = append(monitor.WorkerGroups, *workerGroupName) + } + } + + return monitor, err +} + +func GetMonitors(ctx context.Context, db *sqlx.DB) ([]*models.Monitor, error) { + monitors := []*models.Monitor{} + err := db.SelectContext(ctx, &monitors, + "SELECT * FROM monitors WHERE deleted_at IS NULL", + ) + return monitors, err +} + +func GetMonitorsWithWorkerGroups(ctx context.Context, db *sqlx.DB) ([]*models.MonitorWithWorkerGroups, error) { + rows, err := db.QueryContext(ctx, + ` +SELECT + monitors.slug, + monitors.name, + monitors.script, + monitors.schedule, + monitors.created_at, + monitors.updated_at, + monitors.deleted_at, + worker_groups.name as worker_group_name +FROM monitors +LEFT OUTER JOIN monitor_worker_groups ON monitors.slug = monitor_worker_groups.monitor_slug +LEFT OUTER JOIN worker_groups ON monitor_worker_groups.worker_group_slug = worker_groups.slug +WHERE monitors.deleted_at IS NULL +`) + if err != nil { + return nil, err + } + defer rows.Close() + + monitors := map[string]*models.MonitorWithWorkerGroups{} + + for rows.Next() { + monitor := &models.MonitorWithWorkerGroups{} + + var workerGroupName *string + err = rows.Scan( + &monitor.Slug, + &monitor.Name, + &monitor.Script, + &monitor.Schedule, + &monitor.CreatedAt, + &monitor.UpdatedAt, + &monitor.DeletedAt, + &workerGroupName, + ) + if err != nil { + return nil, err + } + if workerGroupName != nil { + workerGroups := []string{} + if monitors[monitor.Slug] != nil { + workerGroups = monitors[monitor.Slug].WorkerGroups + } + monitor.WorkerGroups = append(workerGroups, *workerGroupName) + } + monitors[monitor.Slug] = monitor + } + + return maps.Values(monitors), err } func CreateOrUpdateMonitorSchedule( ctx context.Context, t client.Client, monitor *models.Monitor, + workerGroups []*models.WorkerGroup, ) error { log.Println("Creating or Updating Monitor Schedule") args := make([]interface{}, 0) args = append(args, workflows.MonitorWorkflowParam{Script: monitor.Script, Slug: monitor.Slug}) - for _, group := range monitor.WorkerGroups { + for _, group := range workerGroups { options := client.ScheduleOptions{ ID: getScheduleId(monitor, group.Slug), Spec: client.ScheduleSpec{ @@ -113,7 +244,3 @@ func CreateOrUpdateMonitorSchedule( return nil } - -func CreateMonitorHistory(ctx context.Context, db *gorm.DB, monitorHistory *models.MonitorHistory) error { - return db.WithContext(ctx).Create(monitorHistory).Error -} diff --git a/internal/services/monitor_history.go b/internal/services/monitor_history.go new file mode 100644 index 0000000..57410c8 --- /dev/null +++ b/internal/services/monitor_history.go @@ -0,0 +1,25 @@ +package services + +import ( + "context" + + "code.tjo.space/mentos1386/zdravko/database/models" + "github.com/jmoiron/sqlx" +) + +func GetMonitorHistoryForMonitor(ctx context.Context, db *sqlx.DB, monitorSlug string) ([]*models.MonitorHistory, error) { + var monitorHistory []*models.MonitorHistory + err := db.SelectContext(ctx, &monitorHistory, + "SELECT * FROM monitor_histories WHERE monitor_slug = $1 ORDER BY created_at DESC", + monitorSlug, + ) + return monitorHistory, err +} + +func AddHistoryForMonitor(ctx context.Context, db *sqlx.DB, history *models.MonitorHistory) error { + _, err := db.NamedExecContext(ctx, + "INSERT INTO monitor_histories (monitor_slug, status, note) VALUES (:monitor_slug, :status, :note)", + history, + ) + return err +} diff --git a/internal/services/oauth2_state.go b/internal/services/oauth2_state.go new file mode 100644 index 0000000..1572f5c --- /dev/null +++ b/internal/services/oauth2_state.go @@ -0,0 +1,30 @@ +package services + +import ( + "context" + + "code.tjo.space/mentos1386/zdravko/database/models" + "github.com/jmoiron/sqlx" +) + +func CreateOAuth2State(ctx context.Context, db *sqlx.DB, oauth2State *models.OAuth2State) error { + _, err := db.NamedExecContext(ctx, + "INSERT INTO oauth2_states (state, expires_at) VALUES (:state, :expires_at)", + oauth2State, + ) + return err +} + +func DeleteOAuth2State(ctx context.Context, db *sqlx.DB, state string) (deleted bool, err error) { + res, err := db.ExecContext(ctx, "DELETE FROM oauth2_states WHERE state = $1 AND expires_at > NOW()", state) + if err != nil { + return false, err + } + + affected, err := res.RowsAffected() + if err != nil { + return false, err + } + + return affected > 0, err +} diff --git a/internal/services/worker_group.go b/internal/services/worker_group.go index 586370d..da16b27 100644 --- a/internal/services/worker_group.go +++ b/internal/services/worker_group.go @@ -3,42 +3,138 @@ package services import ( "context" - "code.tjo.space/mentos1386/zdravko/internal/models" - "code.tjo.space/mentos1386/zdravko/internal/models/query" - "gorm.io/gorm/clause" + "code.tjo.space/mentos1386/zdravko/database/models" + "github.com/jmoiron/sqlx" + "golang.org/x/exp/maps" ) -func GetOrCreateWorkerGroup(ctx context.Context, q *query.Query, workerGroup models.WorkerGroup) (*models.WorkerGroup, error) { - tx := q.Begin() +func CreateWorkerGroup(ctx context.Context, db *sqlx.DB, workerGroup *models.WorkerGroup) error { + _, err := db.NamedExecContext(ctx, + "INSERT INTO worker_groups (slug, name) VALUES (:slug, :name)", + workerGroup, + ) + return err +} - if err := tx.WorkerGroup.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&workerGroup); err != nil { - _ = tx.Rollback() - return nil, err - } +func GetWorkerGroups(ctx context.Context, db *sqlx.DB) ([]*models.WorkerGroup, error) { + var workerGroups []*models.WorkerGroup + err := db.SelectContext(ctx, &workerGroups, + "SELECT * FROM worker_groups WHERE deleted_at IS NULL", + ) + return workerGroups, err +} - wg, err := tx.WorkerGroup.WithContext(ctx).Where( - q.WorkerGroup.Slug.Eq(workerGroup.Slug), - ).First() +func GetWorkerGroupsWithMonitors(ctx context.Context, db *sqlx.DB) ([]*models.WorkerGroupWithMonitors, error) { + rows, err := db.QueryContext(ctx, + ` +SELECT + worker_groups.slug, + worker_groups.name, + worker_groups.created_at, + worker_groups.updated_at, + worker_groups.deleted_at, + monitors.name as monitor_name +FROM worker_groups +LEFT OUTER JOIN monitor_worker_groups ON worker_groups.slug = monitor_worker_groups.worker_group_slug +LEFT OUTER JOIN monitors ON monitor_worker_groups.monitor_slug = monitors.slug +WHERE worker_groups.deleted_at IS NULL AND monitors.deleted_at IS NULL +`) if err != nil { - _ = tx.Rollback() return nil, err } + defer rows.Close() - return wg, tx.Commit() + workerGroups := map[string]*models.WorkerGroupWithMonitors{} + + for rows.Next() { + workerGroup := &models.WorkerGroupWithMonitors{} + + var monitorName *string + err = rows.Scan( + &workerGroup.Slug, + &workerGroup.Name, + &workerGroup.CreatedAt, + &workerGroup.UpdatedAt, + &workerGroup.DeletedAt, + &monitorName, + ) + if err != nil { + return nil, err + } + + if monitorName != nil { + monitors := []string{} + if workerGroups[workerGroup.Slug] != nil { + monitors = workerGroups[workerGroup.Slug].Monitors + } + workerGroup.Monitors = append(monitors, *monitorName) + } + + workerGroups[workerGroup.Slug] = workerGroup + } + + return maps.Values(workerGroups), err } -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, db *sqlx.DB, slugs []string) ([]*models.WorkerGroup, error) { + var workerGroups []*models.WorkerGroup + err := db.SelectContext(ctx, &workerGroups, + "SELECT * FROM worker_groups WHERE slug = ANY($1) AND deleted_at IS NULL", + slugs, + ) + return workerGroups, err } -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, db *sqlx.DB, slug string) (*models.WorkerGroup, error) { + var workerGroup models.WorkerGroup + err := db.GetContext(ctx, &workerGroup, + "SELECT * FROM worker_groups WHERE slug = $1 AND deleted_at IS NULL", + slug, + ) + return &workerGroup, err } -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() +func GetWorkerGroupWithMonitors(ctx context.Context, db *sqlx.DB, slug string) (*models.WorkerGroupWithMonitors, error) { + rows, err := db.QueryContext(ctx, + ` +SELECT + worker_groups.slug, + worker_groups.name, + worker_groups.created_at, + worker_groups.updated_at, + worker_groups.deleted_at, + monitors.name as monitor_name +FROM worker_groups +LEFT OUTER JOIN monitor_worker_groups ON worker_groups.slug = monitor_worker_groups.worker_group_slug +LEFT OUTER JOIN monitors ON monitor_worker_groups.monitor_slug = monitors.slug +WHERE worker_groups.slug=$1 AND worker_groups.deleted_at IS NULL AND monitors.deleted_at IS NULL +`, + slug, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + workerGroup := &models.WorkerGroupWithMonitors{} + + for rows.Next() { + var monitorName *string + err = rows.Scan( + &workerGroup.Slug, + &workerGroup.Name, + &workerGroup.CreatedAt, + &workerGroup.UpdatedAt, + &workerGroup.DeletedAt, + &monitorName, + ) + if err != nil { + return nil, err + } + if monitorName != nil { + workerGroup.Monitors = append(workerGroup.Monitors, *monitorName) + } + } + + return workerGroup, err } diff --git a/internal/temporal/temporal.go b/internal/temporal/temporal.go index 2562136..d6ac701 100644 --- a/internal/temporal/temporal.go +++ b/internal/temporal/temporal.go @@ -2,6 +2,7 @@ package temporal import ( "context" + "log/slog" "time" "code.tjo.space/mentos1386/zdravko/internal/config" @@ -21,7 +22,7 @@ func (p *AuthHeadersProvider) GetHeaders(ctx context.Context) (map[string]string }, nil } -func ConnectServerToTemporal(cfg *config.ServerConfig) (client.Client, error) { +func ConnectServerToTemporal(logger *slog.Logger, cfg *config.ServerConfig) (client.Client, error) { // For server we generate new token with admin permissions token, err := jwt.NewTokenForServer(cfg.Jwt.PrivateKey, cfg.Jwt.PublicKey) if err != nil { @@ -31,12 +32,18 @@ func ConnectServerToTemporal(cfg *config.ServerConfig) (client.Client, error) { provider := &AuthHeadersProvider{token} // Try to connect to the Temporal Server - return retry.Retry(10, 2*time.Second, func() (client.Client, error) { + c, err := retry.Retry(10, 2*time.Second, func() (client.Client, error) { return client.Dial(client.Options{ HostPort: cfg.Temporal.ServerHost, HeadersProvider: provider, }) }) + if err != nil { + logger.Error("Failed to connect to Temporal Server after retries") + return nil, errors.Wrap(err, "failed to connect to Temporal Server after retries") + } + + return c, nil } func ConnectWorkerToTemporal(token string, temporalHost string) (client.Client, error) { diff --git a/internal/workflows/monitor.go b/internal/workflows/monitor.go index ed02879..e22b24a 100644 --- a/internal/workflows/monitor.go +++ b/internal/workflows/monitor.go @@ -3,8 +3,8 @@ package workflows import ( "time" + "code.tjo.space/mentos1386/zdravko/database/models" "code.tjo.space/mentos1386/zdravko/internal/activities" - "code.tjo.space/mentos1386/zdravko/internal/models" "go.temporal.io/sdk/workflow" ) diff --git a/justfile b/justfile index fa4aa9c..8074568 100644 --- a/justfile +++ b/justfile @@ -17,7 +17,9 @@ _default: # Run full development environment run: watchexec -r -e tmpl,css just _tailwindcss-build | sed -e 's/^/tailwind: /;' & + sleep 1 just run-temporal | sed -e 's/^/temporal: /;' & + sleep 1 watchexec -r -e go,tmpl,css just run-server # Start worker @@ -81,13 +83,12 @@ run-docker: -e WORKER_TOKEN \ {{DOCKER_IMAGE}} --server --temporal --worker -# Start devbox shell -shell: - devbox shell +# Start Sqlite web client +sqlite-web: + sqlite_web zdravko.db # Generate and download all external dependencies. generate: - rm -rf internal/models/query/* go generate ./... _tailwindcss-build: @@ -114,6 +115,3 @@ _monaco-download: _feather-icons-download: mkdir -p {{STATIC_DIR}}/icons curl -sLo {{STATIC_DIR}}/icons/feather-sprite.svg https://unpkg.com/feather-icons/dist/feather-sprite.svg - -_generate-gorm: - go run tools/generate/main.go diff --git a/pkg/server/server.go b/pkg/server/server.go index 0a423d4..4268ba5 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -2,10 +2,10 @@ package server import ( "context" - "log" + "log/slog" "net/http" - "code.tjo.space/mentos1386/zdravko/internal" + "code.tjo.space/mentos1386/zdravko/database" "code.tjo.space/mentos1386/zdravko/internal/config" "code.tjo.space/mentos1386/zdravko/internal/handlers" "code.tjo.space/mentos1386/zdravko/internal/temporal" @@ -16,14 +16,16 @@ import ( ) type Server struct { - echo *echo.Echo - cfg *config.ServerConfig + echo *echo.Echo + cfg *config.ServerConfig + logger *slog.Logger } func NewServer(cfg *config.ServerConfig) (*Server, error) { return &Server{ - cfg: cfg, - echo: echo.New(), + cfg: cfg, + echo: echo.New(), + logger: slog.Default().WithGroup("server"), }, nil } @@ -36,31 +38,24 @@ func (s *Server) Start() error { //s.echo.Use(middleware.Logger()) s.echo.Use(middleware.Recover()) - db, query, err := internal.ConnectToDatabase(s.cfg.DatabasePath) + db, err := database.ConnectToDatabase(s.logger, s.cfg.DatabasePath) if err != nil { return err } - log.Println("Connected to database") - temporalClient, err := temporal.ConnectServerToTemporal(s.cfg) + temporalClient, err := temporal.ConnectServerToTemporal(s.logger, s.cfg) if err != nil { return err } - log.Println("Connected to Temporal") - h := handlers.NewBaseHandler(query, temporalClient, s.cfg) + h := handlers.NewBaseHandler(db, temporalClient, s.cfg, s.logger) // Health s.echo.GET("/health", func(c echo.Context) error { - d, err := db.DB() + err = db.Ping() if err != nil { return err } - err = d.Ping() - if err != nil { - return err - } - return c.JSON(http.StatusOK, map[string]string{"status": "ok"}) }) diff --git a/tools/generate/main.go b/tools/generate/main.go deleted file mode 100644 index 1b4af2e..0000000 --- a/tools/generate/main.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "code.tjo.space/mentos1386/zdravko/internal/config" - "code.tjo.space/mentos1386/zdravko/internal/models" - "gorm.io/driver/sqlite" - "gorm.io/gen" - "gorm.io/gorm" -) - -func main() { - config := config.NewServerConfig() - - // Initialize the generator with configuration - g := gen.NewGenerator(gen.Config{ - OutPath: "internal/models/query", - Mode: gen.WithDefaultQuery | gen.WithQueryInterface, - FieldNullable: true, - }) - - db, err := gorm.Open(sqlite.Open(config.DatabasePath), &gorm.Config{}) - if err != nil { - panic(err) - } - - // Use the above `*gorm.DB` instance to initialize the generator, - // which is required to generate structs from db when using `GenerateModel/GenerateModelAs` - g.UseDB(db) - - // Generate default DAO interface for those specified structs - g.ApplyBasic( - models.Monitor{}, - models.WorkerGroup{}, - models.MonitorHistory{}, - models.OAuth2State{}, - ) - - // Execute the generator - g.Execute() -} diff --git a/web/templates/pages/settings_monitors.tmpl b/web/templates/pages/settings_monitors.tmpl index 1a4b8c6..1e10c2e 100644 --- a/web/templates/pages/settings_monitors.tmpl +++ b/web/templates/pages/settings_monitors.tmpl @@ -60,7 +60,7 @@ {{range .WorkerGroups}} - {{ .Name }} + {{ . }} {{end}} diff --git a/web/templates/pages/settings_monitors_describe.tmpl b/web/templates/pages/settings_monitors_describe.tmpl index 8c7549f..301d61c 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.

@@ -31,7 +31,7 @@ History

- Last executions of monitor script. + Last 10 executions of monitor script.

@@ -43,7 +43,7 @@ - {{range .Monitor.History}} + {{range .History}}