Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Add anomaly table and model object

天舟113310e7f7bf
diff --git a/api/anomaly.go b/api/anomaly.go
new file mode 100644
index 0000000000..1ff3555c85
--- /dev/null
+++ b/api/anomaly.go
@@ -0,0 +1,81 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+)
+
+// AnomalyType is the type of a task.
+type AnomalyType string
+
+const (
+ AnomalyBackupPolicyViolation AnomalyType = "bb.anomaly.backup.policy-violation"
+ AnomalyBackupMissing AnomalyType = "bb.anomaly.backup.missing"
+)
+
+type AnomalyBackupPolicyViolationPayload struct {
+ EnvironmentId int `json:"environmentId,omitempty"`
+ ExpectedBackupSchedule BackupPlanPolicySchedule `json:"expectedSchedule,omitempty"`
+ ActualBackupSchedule BackupPlanPolicySchedule `json:"actualSchedule,omitempty"`
+}
+
+type Anomaly struct {
+ ID int `jsonapi:"primary,anomaly"`
+
+ // Standard fields
+ CreatorId int
+ Creator *Principal `jsonapi:"attr,creator"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int
+ Updater *Principal `jsonapi:"attr,updater"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Related fields
+ InstanceId int `jsonapi:"attr,instanceId"`
+ DatabaseId int `jsonapi:"attr,databaseId"`
+
+ // Domain specific fields
+ Type AnomalyType `jsonapi:"attr,type"`
+ Payload string `jsonapi:"attr,payload"`
+}
+
+type AnomalyUpsert struct {
+ // Standard fields
+ CreatorId int
+
+ // Related fields
+ InstanceId int
+ DatabaseId int
+
+ // Domain specific fields
+ Type AnomalyType `jsonapi:"attr,type"`
+ Payload string `jsonapi:"attr,payload"`
+}
+
+type AnomalyFind struct {
+ // Standard fields
+ RowStatus *RowStatus
+
+ // Related fields
+ DatabaseId int
+}
+
+func (find *AnomalyFind) String() string {
+ str, err := json.Marshal(*find)
+ if err != nil {
+ return err.Error()
+ }
+ return string(str)
+}
+
+type AnomalyArchive struct {
+ DatabaseId int
+ Type AnomalyType
+}
+
+type AnomalyService interface {
+ // UpsertAnomaly would update the existing user if name matches.
+ UpsertAnomaly(ctx context.Context, upsert *AnomalyUpsert) (*Anomaly, error)
+ FindAnomalyList(ctx context.Context, find *AnomalyFind) ([]*Anomaly, error)
+ ArchiveAnomaly(ctx context.Context, archive *AnomalyArchive) error
+}
diff --git a/store/anomaly.go b/store/anomaly.go
new file mode 100644
index 0000000000..206d241ce8
--- /dev/null
+++ b/store/anomaly.go
@@ -0,0 +1,210 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.AnomalyService = (*AnomalyService)(nil)
+)
+
+// AnomalyService represents a service for managing anomaly.
+type AnomalyService struct {
+ l *zap.Logger
+ db *DB
+}
+
+// NewAnomalyService returns a new instance of AnomalyService.
+func NewAnomalyService(logger *zap.Logger, db *DB) *AnomalyService {
+ return &AnomalyService{l: logger, db: db}
+}
+
+// UpsertAnomaly would update the existing user if name matches.
+func (s *AnomalyService) UpsertAnomaly(ctx context.Context, upsert *api.AnomalyUpsert) (*api.Anomaly, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ anomaly, err := upsertAnomaly(ctx, tx, upsert)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return anomaly, nil
+}
+
+// FindAnomalyList retrieves a list of anomalys based on find.
+func (s *AnomalyService) FindAnomalyList(ctx context.Context, find *api.AnomalyFind) ([]*api.Anomaly, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := findAnomalyList(ctx, tx, find)
+ if err != nil {
+ return []*api.Anomaly{}, err
+ }
+
+ return list, nil
+}
+
+// ArchiveAnomaly archives an existing anomaly by ID.
+// Returns ENOTFOUND if anomaly does not exist.
+func (s *AnomalyService) ArchiveAnomaly(ctx context.Context, archive *api.AnomalyArchive) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return FormatError(err)
+ }
+ defer tx.Rollback()
+
+ err = archiveAnomaly(ctx, tx, archive)
+ if err != nil {
+ return FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return FormatError(err)
+ }
+
+ return nil
+}
+
+// upsertAnomaly upserts a new anomaly.
+func upsertAnomaly(ctx context.Context, tx *Tx, upsert *api.AnomalyUpsert) (*api.Anomaly, error) {
+ // Upsert row into database.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO anomaly (
+ creator_id,
+ updater_id,
+ instance_id,
+ database_id,
+ `+"`type`,"+`
+ payload
+ )
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT (database_id, `+"`type`"+`) DO UPDATE SET
+ updater_id = excluded.updater_id,
+ payload = excluded.payload
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, `+"`type`"+`, payload
+ `,
+ upsert.CreatorId,
+ upsert.CreatorId,
+ upsert.InstanceId,
+ upsert.DatabaseId,
+ upsert.Type,
+ upsert.Payload,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var anomaly api.Anomaly
+ if err := row.Scan(
+ &anomaly.ID,
+ &anomaly.CreatorId,
+ &anomaly.CreatedTs,
+ &anomaly.UpdaterId,
+ &anomaly.UpdatedTs,
+ &anomaly.InstanceId,
+ &anomaly.DatabaseId,
+ &anomaly.Type,
+ &anomaly.Payload,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return nil, err
+}
+
+func findAnomalyList(ctx context.Context, tx *Tx, find *api.AnomalyFind) (_ []*api.Anomaly, err error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ where, args = append(where, "database_id = ?"), append(args, find.DatabaseId)
+ if v := find.RowStatus; v != nil {
+ where, args = append(where, "row_status = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ instance_id,
+ database_id,
+ `+"`type`,"+`
+ payload
+ FROM anomaly
+ WHERE `+strings.Join(where, " AND ")+`
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ list := make([]*api.Anomaly, 0)
+ for rows.Next() {
+ var anomaly api.Anomaly
+ if err := rows.Scan(
+ &anomaly.ID,
+ &anomaly.CreatorId,
+ &anomaly.CreatedTs,
+ &anomaly.UpdaterId,
+ &anomaly.UpdatedTs,
+ &anomaly.InstanceId,
+ &anomaly.DatabaseId,
+ &anomaly.Type,
+ &anomaly.Payload,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &anomaly)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// archiveAnomaly archives an anomaly by ID.
+func archiveAnomaly(ctx context.Context, tx *Tx, archive *api.AnomalyArchive) error {
+ // Remove row from database.
+ result, err := tx.ExecContext(ctx,
+ `UPDATE anomaly SET row_status = ? WHERE database_id = ? AND type = ?`,
+ api.Archived,
+ archive.DatabaseId,
+ archive.Type,
+ )
+ if err != nil {
+ return FormatError(err)
+ }
+
+ rows, _ := result.RowsAffected()
+ if rows == 0 {
+ return &common.Error{Code: common.NotFound, Err: fmt.Errorf("anomaly not found database: %d type: %s", archive.DatabaseId, archive.Type)}
+ }
+
+ return nil
+}
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index e0319ec0cf..788059197e 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -1181,4 +1181,44 @@ SET
WHERE
rowid = old.rowid;
-END;
\ No newline at end of file
+END;
+
+-- Anomaly
+-- anomaly stores various anomalies found by the scanner.
+-- For now, anomaly is associated with a particular database. In the future, we may relax it a bit to have instance level anomalys.
+CREATE TABLE anomaly (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ row_status TEXT NOT NULL CHECK (
+ row_status IN ('NORMAL', 'ARCHIVED')
+ ) DEFAULT 'NORMAL',
+ creator_id INTEGER NOT NULL REFERENCES principal (id),
+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ updater_id INTEGER NOT NULL REFERENCES principal (id),
+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ instance_id INTEGER NOT NULL REFERENCES instance (id),
+ database_id INTEGER NOT NULL REFERENCES db (id),
+ `type` TEXT NOT NULL CHECK (`type` LIKE 'bb.anomaly.%'),
+ payload TEXT NOT NULL DEFAULT ''
+);
+
+CREATE INDEX idx_anomaly_database_id ON anomaly(database_id);
+
+CREATE UNIQUE INDEX idx_anomaly_database_id_type ON anomaly(database_id, type);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('anomaly', 100);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_anomaly_modification_time`
+AFTER
+UPDATE
+ ON `anomaly` FOR EACH ROW BEGIN
+UPDATE
+ `anomaly`
+SET
+ updated_ts = (strftime('%s', 'now'))
+WHERE
+ rowid = old.rowid;
+
+END;
diff --git a/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index bfbd81c5f7..8cd8a44c49 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -5,6 +5,9 @@ DELETE FROM
WHERE
name != 'bb.auth.secret';
+DELETE FROM
+ anomaly;
+
DELETE FROM
repository;