Skip to content

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

feat(tenancy): database label API & backend (#157)

p0nya56a9e8bc593
diff --git a/api/database.go b/api/database.go
index ecf819253a..b4b4074f14 100644
--- a/api/database.go
+++ b/api/database.go
@@ -66,6 +66,9 @@ type Database struct {
Collation string `jsonapi:"attr,collation"`
SyncStatus SyncStatus `jsonapi:"attr,syncStatus"`
LastSuccessfulSyncTs int64 `jsonapi:"attr,lastSuccessfulSyncTs"`
+ // Labels is a json-encoded string from a list of DatabaseLabel,
+ // e.g. "[{"key":"bb.location","value":"earth"},{"key":"bb.tenant","value":"bytebase"}]".
+ Labels string `jsonapi:"attr,labels,omitempty"`
}
// DatabaseCreate is the API message for creating a database.
@@ -119,6 +122,10 @@ type DatabasePatch struct {
ProjectID *int `jsonapi:"attr,projectId"`
SourceBackupID *int
+ // Labels is a json-encoded string from a list of DatabaseLabel,
+ // e.g. "[{"key":"bb.location","value":"earth"},{"key":"bb.tenant","value":"bytebase"}]".
+ Labels *string `jsonapi:"attr,labels"`
+
// Domain specific fields
SyncStatus *SyncStatus
LastSuccessfulSyncTs *int64
diff --git a/api/label.go b/api/label.go
index 022df10995..8c33af2c60 100644
--- a/api/label.go
+++ b/api/label.go
@@ -24,8 +24,56 @@ type LabelKey struct {
type LabelKeyFind struct {
}
+// DatabaseLabel is the label associated with a database.
+type DatabaseLabel struct {
+ ID int `json:"-"`
+
+ // Standard fields
+ RowStatus RowStatus `json:"-"`
+ CreatorID int `json:"-"`
+ Creator *Principal `json:"-"`
+ CreatedTs int64 `json:"-"`
+ UpdaterID int `json:"-"`
+ Updater *Principal `json:"-"`
+ UpdatedTs int64 `json:"-"`
+
+ // Related fields
+ DatabaseID int `json:"-"`
+ Key string `json:"key"`
+
+ // Domain specific fields
+ Value string `json:"value"`
+}
+
+type DatabaseLabelFind struct {
+ // Standard fields
+ ID *int
+ RowStatus *RowStatus
+
+ // Related fields
+ DatabaseID *int
+}
+
+type DatabaseLabelUpsert struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterID int
+ RowStatus RowStatus
+
+ // Related fields
+ DatabaseID int
+ Key string
+
+ // Domain specific fields
+ Value string
+}
+
// LabelService is the service for labels.
type LabelService interface {
// FindLabelKeyList finds all available keys for labels.
FindLabelKeyList(ctx context.Context, find *LabelKeyFind) ([]*LabelKey, error)
+ // FindDatabaseLabels finds all database labels matching the conditions, ascending by key.
+ FindDatabaseLabels(ctx context.Context, find *DatabaseLabelFind) ([]*DatabaseLabel, error)
+ // SetDatabaseLabels sets a database's labels to new labels.
+ SetDatabaseLabels(ctx context.Context, labels []*DatabaseLabel, databaseID int, updaterID int) ([]*DatabaseLabel, error)
}
diff --git a/api/label_test.go b/api/label_test.go
new file mode 100644
index 0000000000..230b58c999
--- /dev/null
+++ b/api/label_test.go
@@ -0,0 +1,39 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "testing"
+
+ "github.com/google/jsonapi"
+)
+
+func TestUnmarshal(t *testing.T) {
+ b := []byte(`{
+ "data": {
+ "type": "databasePatch",
+ "attributes": {
+ "labels": "[{\"key\":\"bb.location\",\"value\":\"earth\"}]"
+ }
+ }
+ }`)
+ keys := []string{"bb.location", "bb.tenant"}
+ values := []string{"earth", "bytebase"}
+ databasePatch := &DatabasePatch{
+ ID: 1,
+ UpdaterID: 1,
+ }
+ if err := jsonapi.UnmarshalPayload(bytes.NewReader(b), databasePatch); err != nil {
+ t.Fatal(err)
+ }
+ var labels []*DatabaseLabel
+ if err := json.Unmarshal([]byte(*databasePatch.Labels), &labels); err != nil {
+ t.Fatal(err)
+ }
+ for i, label := range labels {
+ if keys[i] != label.Key || values[i] != label.Value {
+ t.Fatal("Key value pair does not match!")
+ }
+ }
+
+}
diff --git a/server/database.go b/server/database.go
index 6f3de79eb8..f230472099 100644
--- a/server/database.go
+++ b/server/database.go
@@ -145,6 +145,26 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch database request").SetInternal(err)
}
+ // Patch database labels
+ // We will completely replace the old labels with the new ones
+ if databasePatch.Labels != nil {
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch database ID: %v", id)).SetInternal(err)
+ }
+
+ // databasePatch.Labels is a JSON-encoded string
+ var labels []*api.DatabaseLabel
+ json.Unmarshal([]byte(*databasePatch.Labels), &labels)
+
+ _, err := s.LabelService.SetDatabaseLabels(ctx, labels, databasePatch.ID, databasePatch.UpdaterID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to set database labels, database ID: %v", id)).SetInternal(err)
+ }
+ }
+
// If we are transferring the database to a different project, then we create a project activity in both
// the old project and new project.
var existingDatabase *api.Database
@@ -680,6 +700,23 @@ func (s *Server) composeDatabaseRelationship(ctx context.Context, database *api.
}
}
+ rowStatus = api.Normal
+ labels, err := s.LabelService.FindDatabaseLabels(ctx, &api.DatabaseLabelFind{
+ DatabaseID: &database.ID,
+ RowStatus: &rowStatus,
+ })
+ if err != nil {
+ return err
+ }
+
+ if len(labels) > 0 {
+ labels, err := json.Marshal(labels)
+ if err != nil {
+ return err
+ }
+ database.Labels = string(labels)
+ }
+
return nil
}
diff --git a/store/label.go b/store/label.go
index 838bfd07b0..7597171995 100644
--- a/store/label.go
+++ b/store/label.go
@@ -2,6 +2,7 @@ package store
import (
"context"
+ "strings"
"github.com/bytebase/bytebase/api"
"go.uber.org/zap"
@@ -68,3 +69,186 @@ func (s *LabelService) FindLabelKeyList(ctx context.Context, find *api.LabelKeyF
return ret, nil
}
+
+func (s *LabelService) FindDatabaseLabels(ctx context.Context, find *api.DatabaseLabelFind) ([]*api.DatabaseLabel, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ databaseLabelList, err := s.findDatabaseLabels(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return databaseLabelList, nil
+}
+
+func (s *LabelService) findDatabaseLabels(ctx context.Context, tx *Tx, find *api.DatabaseLabelFind) ([]*api.DatabaseLabel, error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
+ if v := find.RowStatus; v != nil {
+ where, args = append(where, "row_status = ?"), append(args, *v)
+ }
+ if v := find.DatabaseID; v != nil {
+ where, args = append(where, "database_id = ?"), append(args, *v)
+ }
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ row_status,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ database_id,
+ key,
+ value
+ FROM db_label
+ WHERE `+strings.Join(where, " AND ")+` ORDER BY key`,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ var ret []*api.DatabaseLabel
+ for rows.Next() {
+ var databaseLabel api.DatabaseLabel
+ if err := rows.Scan(
+ &databaseLabel.ID,
+ &databaseLabel.RowStatus,
+ &databaseLabel.CreatorID,
+ &databaseLabel.CreatedTs,
+ &databaseLabel.UpdaterID,
+ &databaseLabel.UpdatedTs,
+ &databaseLabel.DatabaseID,
+ &databaseLabel.Key,
+ &databaseLabel.Value,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ ret = append(ret, &databaseLabel)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return ret, nil
+}
+
+func (s *LabelService) upsertDatabaseLabel(ctx context.Context, tx *Tx, upsert *api.DatabaseLabelUpsert) (*api.DatabaseLabel, error) {
+ // Upsert row into db_label
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO db_label (
+ row_status,
+ creator_id,
+ updater_id,
+ database_id,
+ key,
+ value
+ )
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(database_id, key) DO UPDATE SET
+ row_status = excluded.row_status,
+ creator_id = excluded.creator_id,
+ updater_id = excluded.updater_id,
+ value = excluded.value
+ RETURNING id, row_status, creator_id, created_ts, updater_id, updated_ts, database_id, key, value
+ `,
+ upsert.RowStatus,
+ upsert.UpdaterID,
+ upsert.UpdaterID,
+ upsert.DatabaseID,
+ upsert.Key,
+ upsert.Value,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var databaseLabel api.DatabaseLabel
+ if err := row.Scan(
+ &databaseLabel.ID,
+ &databaseLabel.RowStatus,
+ &databaseLabel.CreatorID,
+ &databaseLabel.CreatedTs,
+ &databaseLabel.UpdaterID,
+ &databaseLabel.UpdatedTs,
+ &databaseLabel.DatabaseID,
+ &databaseLabel.Key,
+ &databaseLabel.Value,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &databaseLabel, nil
+}
+
+func (s *LabelService) SetDatabaseLabels(ctx context.Context, labels []*api.DatabaseLabel, databaseID int, updaterID int) ([]*api.DatabaseLabel, error) {
+ oldLabels, err := s.FindDatabaseLabels(ctx, &api.DatabaseLabelFind{
+ DatabaseID: &databaseID,
+ })
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ var ret []*api.DatabaseLabel
+
+ for _, oldLabel := range oldLabels {
+ // Archive all old labels
+ label, err := s.upsertDatabaseLabel(ctx, tx, &api.DatabaseLabelUpsert{
+ UpdaterID: updaterID,
+ RowStatus: api.Archived,
+ DatabaseID: databaseID,
+ Key: oldLabel.Key,
+ Value: oldLabel.Value,
+ })
+ if err != nil {
+ return nil, err
+ }
+ ret = append(ret, label)
+ }
+
+ for _, label := range labels {
+ // Upsert all new labels
+ label, err := s.upsertDatabaseLabel(ctx, tx, &api.DatabaseLabelUpsert{
+ UpdaterID: updaterID,
+ RowStatus: api.Normal,
+ DatabaseID: databaseID,
+ Key: label.Key,
+ Value: label.Value,
+ })
+ if err != nil {
+ return nil, err
+ }
+ ret = append(ret, label)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return ret, nil
+
+}
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index ed13ecf249..d695542c50 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -1316,7 +1316,8 @@ CREATE TABLE db_label (
updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
database_id INTEGER NOT NULL REFERENCES db (id),
key TEXT NOT NULL REFERENCES label_key (key),
- value TEXT NOT NULL
+ value TEXT NOT NULL,
+ UNIQUE(database_id, key)
);
CREATE UNIQUE INDEX idx_db_label_database_id_key ON db_label(database_id, key);
diff --git a/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index b7b67b1a98..7ce99457df 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -65,6 +65,9 @@ DELETE FROM
DELETE FROM
backup_setting;
+DELETE FROM
+ db_label;
+
DELETE FROM
db;
@@ -89,8 +92,7 @@ DELETE FROM
DELETE FROM
label_key;
-DELETE FROM
- db_label;
+
DELETE FROM
deployment_config;
diff --git a/store/seed/test/10200__label.sql b/store/seed/test/10200__label.sql
index 2833377dd7..541736d6d6 100644
--- a/store/seed/test/10200__label.sql
+++ b/store/seed/test/10200__label.sql
@@ -29,3 +29,42 @@ VALUES
1,
'bb.tenant'
);
+
+
+INSERT INTO
+ db_label (
+ id,
+ creator_id,
+ updater_id,
+ database_id,
+ key,
+ value
+ )
+VALUES
+ (
+ 20001,
+ 1,
+ 1,
+ 7002,
+ "bb.location",
+ "earth"
+ );
+
+INSERT INTO
+ db_label (
+ id,
+ creator_id,
+ updater_id,
+ database_id,
+ key,
+ value
+ )
+VALUES
+ (
+ 20002,
+ 1,
+ 1,
+ 7002,
+ "bb.tenant",
+ "bytebase"
+ );