Skip to content

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

feat: redis (#5007)

p0ny1efcfc52147d
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index eb52830fe0..51c488061b 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -347,6 +347,10 @@ type MigrationHistoryFind struct {
Version *string
// If specified, then it will only fetch "Limit" most recent migration histories
Limit *int
+
+ // Fields below should be set if fetching from metaDB instance_change_history table.
+ DatabaseID *int
+ InstanceID int
}
// ConnectionConfig is the configuration for connections.
diff --git a/backend/plugin/db/redis/migrate.go b/backend/plugin/db/redis/migrate.go
new file mode 100644
index 0000000000..18160cef41
--- /dev/null
+++ b/backend/plugin/db/redis/migrate.go
@@ -0,0 +1,42 @@
+package redis
+
+import (
+ "context"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/util"
+)
+
+// Migration related.
+
+// NeedsSetupMigration checks whether we need to setup migration (e.g. creating/upgrading the migration related tables).
+// No need because redis uses bytebase metaDB InstanceChangeHistory.
+func (*Driver) NeedsSetupMigration(context.Context) (bool, error) {
+ return false, nil
+}
+
+// SetupMigrationIfNeeded create or upgrade migration related tables.
+// No need for redis because it uses bytebase metaDB InstanceChangeHistory.
+func (*Driver) SetupMigrationIfNeeded(context.Context) error {
+ return nil
+}
+
+// ExecuteMigration executes a migration.
+// ExecuteMigration will execute the database migration.
+// Returns the created migration history id and the updated schema on success.
+func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {
+ if m.CreateDatabase {
+ return "", "", errors.New("redis: creating databases is not supported")
+ }
+ if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {
+ return "", "", util.FormatError(err)
+ }
+ return "", "", nil
+}
+
+// FindMigrationHistoryList finds the migration history list and return most recent item first.
+func (*Driver) FindMigrationHistoryList(context.Context, *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
+ return nil, errors.New("redis: not supported")
+}
diff --git a/backend/plugin/db/redis/redis.go b/backend/plugin/db/redis/redis.go
new file mode 100644
index 0000000000..ec9071ea1e
--- /dev/null
+++ b/backend/plugin/db/redis/redis.go
@@ -0,0 +1,175 @@
+// Package redis implements redis driver
+package redis
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+
+ "github.com/pkg/errors"
+ "github.com/redis/go-redis/v9"
+
+ "github.com/bytebase/bytebase/backend/plugin/db"
+)
+
+var (
+ _ db.Driver = (*Driver)(nil)
+)
+
+func init() {
+ db.Register(db.Redis, newDriver)
+}
+
+// Driver is the redis driver.
+type Driver struct {
+ rdb redis.UniversalClient
+}
+
+func newDriver(_ db.DriverConfig) db.Driver {
+ return &Driver{}
+}
+
+// Open opens the redis driver.
+func (d *Driver) Open(ctx context.Context, _ db.Type, config db.ConnectionConfig, _ db.ConnectionContext) (db.Driver, error) {
+ port := config.Port
+ if port == "" {
+ port = "6379"
+ }
+ addr := fmt.Sprintf("%s:%s", config.Host, port)
+ tlsConfig, err := config.TLSConfig.GetSslConfig()
+ if err != nil {
+ return nil, errors.Wrap(err, "redis: failed to get tls config")
+ }
+
+ // connect to 0 by default
+ db := 0
+ if config.Database != "" {
+ database, err := strconv.Atoi(config.Database)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to convert database %s to int", config.Database)
+ }
+ db = database
+ }
+
+ rdb := redis.NewUniversalClient(&redis.UniversalOptions{
+ Addrs: []string{addr},
+ Username: config.Username,
+ Password: config.Password,
+ TLSConfig: tlsConfig,
+ ReadOnly: config.ReadOnly,
+ DB: db,
+ })
+ if err := rdb.Ping(ctx).Err(); err != nil {
+ return nil, err
+ }
+
+ d.rdb = rdb
+ return d, nil
+}
+
+// Close closes the redis driver.
+func (d *Driver) Close(context.Context) error {
+ return d.rdb.Close()
+}
+
+// Ping pings the redis server.
+func (d *Driver) Ping(ctx context.Context) error {
+ return d.rdb.Ping(ctx).Err()
+}
+
+// GetType returns redis.
+func (*Driver) GetType() db.Type {
+ return db.Redis
+}
+
+// GetDBConnection is not supported for redis.
+func (*Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {
+ return nil, errors.New("redis: not supported")
+}
+
+// Execute will execute the statement. For CREATE DATABASE statement, some types of databases such as Postgres
+// will not use transactions to execute the statement but will still use transactions to execute the rest of statements.
+func (d *Driver) Execute(ctx context.Context, statement string, createDatabase bool) (int64, error) {
+ if createDatabase {
+ return 0, errors.New("redis: cannot create database")
+ }
+
+ lines := strings.Split(statement, "\n")
+ for i := range lines {
+ lines[i] = strings.Trim(lines[i], " \n\t\r")
+ }
+
+ if _, err := d.rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
+ for _, line := range lines {
+ if line == "" {
+ continue
+ }
+ var input []interface{}
+ for _, s := range strings.Split(line, " ") {
+ input = append(input, s)
+ }
+ _ = p.Do(ctx, input...)
+ }
+ return nil
+ }); err != nil && err != redis.Nil {
+ return 0, err
+ }
+
+ return 0, nil
+}
+
+// QueryConn executes the statement, returns the results.
+func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, _ *db.QueryContext) ([]interface{}, error) {
+ lines := strings.Split(statement, "\n")
+ for i := range lines {
+ lines[i] = strings.Trim(lines[i], " \n\t\r")
+ }
+
+ var data []interface{}
+ var cmds []*redis.Cmd
+
+ if _, err := d.rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
+ for _, line := range lines {
+ if line == "" {
+ continue
+ }
+ var input []interface{}
+ for _, s := range strings.Split(line, " ") {
+ input = append(input, s)
+ }
+ cmd := p.Do(ctx, input...)
+ cmds = append(cmds, cmd)
+ }
+ return nil
+ }); err != nil && err != redis.Nil {
+ return nil, err
+ }
+
+ for _, cmd := range cmds {
+ if cmd.Err() == redis.Nil {
+ data = append(data, []interface{}{"redis: nil"})
+ } else {
+ data = append(data, []interface{}{cmd.Val()})
+ }
+ }
+
+ return []interface{}{[]string{"result"}, []string{"TEXT"}, data}, nil
+}
+
+// Dump and restore
+// Dump the database, if dbName is empty, then dump all databases.
+// Redis is schemaless, we don't support dump Redis data currently.
+func (*Driver) Dump(_ context.Context, _ string, _ io.Writer, schemaOnly bool) (string, error) {
+ if !schemaOnly {
+ return "", errors.New("redis: not supported")
+ }
+ return "", nil
+}
+
+// Restore the database from src, which is a full backup.
+func (*Driver) Restore(context.Context, io.Reader) error {
+ return errors.New("redis: not supported")
+}
diff --git a/backend/plugin/db/redis/role.go b/backend/plugin/db/redis/role.go
new file mode 100644
index 0000000000..2136b00ea3
--- /dev/null
+++ b/backend/plugin/db/redis/role.go
@@ -0,0 +1,36 @@
+package redis
+
+import (
+ "context"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/db"
+)
+
+// Role
+
+// CreateRole creates the role.
+func (*Driver) CreateRole(context.Context, *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {
+ return nil, errors.New("redis: not supported")
+}
+
+// UpdateRole updates the role.
+func (*Driver) UpdateRole(context.Context, string, *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {
+ return nil, errors.New("redis: not supported")
+}
+
+// FindRole finds the role by name.
+func (*Driver) FindRole(context.Context, string) (*db.DatabaseRoleMessage, error) {
+ return nil, errors.New("redis: not supported")
+}
+
+// ListRole lists the role.
+func (*Driver) ListRole(context.Context) ([]*db.DatabaseRoleMessage, error) {
+ return nil, errors.New("redis: not supported")
+}
+
+// DeleteRole deletes the role by name.
+func (*Driver) DeleteRole(context.Context, string) error {
+ return errors.New("redis: not supported")
+}
diff --git a/backend/plugin/db/redis/sync.go b/backend/plugin/db/redis/sync.go
new file mode 100644
index 0000000000..4c90c273b5
--- /dev/null
+++ b/backend/plugin/db/redis/sync.go
@@ -0,0 +1,108 @@
+package redis
+
+import (
+ "context"
+ "strconv"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+// Sync schema
+
+// SyncInstance syncs the instance metadata.
+func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error) {
+ var instance db.InstanceMetadata
+
+ version, err := d.getVersion(ctx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get server version")
+ }
+ instance.Version = version
+
+ clusterEnabled, err := d.getClusterEnabled(ctx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to check if cluster is enabled")
+ }
+
+ databaseCount, err := d.getDatabaseCount(ctx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get databases")
+ }
+
+ // Redis cluster can only use database zero.
+ if clusterEnabled {
+ databaseCount = 1
+ }
+
+ var databases []*storepb.DatabaseMetadata
+ for i := 0; i < databaseCount; i++ {
+ databases = append(databases, &storepb.DatabaseMetadata{
+ Name: strconv.Itoa(i),
+ })
+ }
+ instance.Databases = databases
+
+ return &instance, nil
+}
+
+// SyncDBSchema syncs a single database schema.
+func (*Driver) SyncDBSchema(_ context.Context, database string) (*storepb.DatabaseMetadata, error) {
+ return &storepb.DatabaseMetadata{Name: database}, nil
+}
+
+func (d *Driver) getVersion(ctx context.Context) (string, error) {
+ val, err := d.rdb.Info(ctx, "server").Result()
+ if err != nil {
+ return "", err
+ }
+ var version string
+ for _, line := range strings.Split(val, "\n") {
+ if strings.HasPrefix(line, "redis_version:") {
+ version = strings.TrimPrefix(line, "redis_version:")
+ version = strings.Trim(version, " \n\t")
+ break
+ }
+ }
+ if version == "" {
+ return "", errors.New("failed to get redis_version")
+ }
+ return version, nil
+}
+
+func (d *Driver) getClusterEnabled(ctx context.Context) (bool, error) {
+ val, err := d.rdb.Info(ctx, "cluster").Result()
+ if err != nil {
+ return false, err
+ }
+ var enabled string
+ for _, line := range strings.Split(val, "\n") {
+ if strings.HasPrefix(line, "cluster_enabled:") {
+ enabled = strings.TrimPrefix(line, "cluter_enabled:")
+ enabled = strings.Trim(enabled, " \n\t")
+ break
+ }
+ }
+ if enabled == "" {
+ return false, errors.New("failed to get cluster_enabled")
+ }
+ return enabled == "1", nil
+}
+
+func (d *Driver) getDatabaseCount(ctx context.Context) (int, error) {
+ val, err := d.rdb.ConfigGet(ctx, "databases").Result()
+ if err != nil {
+ return 0, err
+ }
+ if _, ok := val["databases"]; !ok {
+ return 0, errors.New("The returned values of 'CONFIG GET databases' dont't have the 'databases' KEY")
+ }
+ count, err := strconv.Atoi(val["databases"])
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to convert to int from %v", val["databases"])
+ }
+ return count, nil
+}
diff --git a/backend/runner/anomaly/scanner.go b/backend/runner/anomaly/scanner.go
index de41562941..c8f615c22e 100644
--- a/backend/runner/anomaly/scanner.go
+++ b/backend/runner/anomaly/scanner.go
@@ -271,6 +271,10 @@ func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.Inst
// Check schema drift
if s.licenseService.IsFeatureEnabled(api.FeatureSchemaDrift) {
+ // Redis is schemaless.
+ if instance.Engine == db.Redis {
+ return
+ }
setup, err := driver.NeedsSetupMigration(ctx)
if err != nil {
log.Debug("Failed to check anomaly",
diff --git a/backend/runner/backuprun/runner.go b/backend/runner/backuprun/runner.go
index e6f95e5d2d..af1ac0da14 100644
--- a/backend/runner/backuprun/runner.go
+++ b/backend/runner/backuprun/runner.go
@@ -423,7 +423,7 @@ func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.Databas
}
defer driver.Close(ctx)
- migrationHistoryVersion, err := utils.GetLatestSchemaVersion(ctx, driver, database.DatabaseName)
+ migrationHistoryVersion, err := utils.GetLatestSchemaVersion(ctx, r.store, driver, instance.UID, database.UID, database.DatabaseName)
if err != nil {
return nil, errors.Wrapf(err, "failed to get migration history for database %q", database.DatabaseName)
}
diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.go
index 9ed75da4db..29ffe006c0 100644
--- a/backend/runner/schemasync/syncer.go
+++ b/backend/runner/schemasync/syncer.go
@@ -274,7 +274,7 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databas
if force {
// When there are too many databases, this might have performance issue and will
// cause frontend timeout since we set a 30s limit (INSTANCE_OPERATION_TIMEOUT).
- schemaVersion, err := utils.GetLatestSchemaVersion(ctx, driver, databaseMetadata.Name)
+ schemaVersion, err := utils.GetLatestSchemaVersion(ctx, s.store, driver, instance.UID, database.UID, databaseMetadata.Name)
if err != nil {
return err
}
diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.go
index 690c54526d..de055ae106 100644
--- a/backend/runner/taskrun/database_create_executor.go
+++ b/backend/runner/taskrun/database_create_executor.go
@@ -285,7 +285,7 @@ func (*DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Conte
return "", "", err
}
defer driver.Close(ctx)
- schemaVersion, err := utils.GetLatestSchemaVersion(ctx, driver, similarDB.DatabaseName)
+ schemaVersion, err := utils.GetLatestSchemaVersion(ctx, stores, driver, instance.UID, similarDB.UID, similarDB.DatabaseName)
if err != nil {
return "", "", errors.Wrapf(err, "failed to get migration history for database %q", similarDB.DatabaseName)
}
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index 3f976b81fe..1cd809cff0 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -187,9 +187,16 @@ func executeMigration(ctx context.Context, stores *store.Store, dbFactory *dbfac
task = updatedTask
}
- migrationID, schema, err = driver.ExecuteMigration(ctx, mi, statement)
- if err != nil {
- return "", "", err
+ if instance.Engine == db.Redis {
+ migrationID, schema, err = utils.ExecuteMigration(ctx, stores, driver, mi, statement)
+ if err != nil {
+ return "", "", err
+ }
+ } else {
+ migrationID, schema, err = driver.ExecuteMigration(ctx, mi, statement)
+ if err != nil {
+ return "", "", err
+ }
}
if task.Type == api.TaskDatabaseDataUpdate && instance.Engine == db.MySQL {
diff --git a/backend/server/instance.go b/backend/server/instance.go
index b6fc76e26e..86501f0b50 100644
--- a/backend/server/instance.go
+++ b/backend/server/instance.go
@@ -360,7 +360,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
g.GET("/instance/:instanceID/migration/history/:historyID", func(c echo.Context) error {
ctx := c.Request().Context()
- id, err := strconv.Atoi(c.Param("instanceID"))
+ instanceID, err := strconv.Atoi(c.Param("instanceID"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Instance ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
@@ -368,28 +368,40 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
historyID := c.Param("historyID")
isSDL := c.QueryParam("sdl") == "true"
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &id})
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &instanceID})
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", instanceID)).SetInternal(err)
}
if instance == nil {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", instanceID))
}
- find := &db.MigrationHistoryFind{ID: &historyID}
- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history ID %d for instance %q", id, instance.Title)).SetInternal(err)
- }
- defer driver.Close(ctx)
- list, err := driver.FindMigrationHistoryList(ctx, find)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
- }
- if len(list) == 0 {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))
+ var entry *db.MigrationHistory
+ find := &db.MigrationHistoryFind{ID: &historyID, InstanceID: instanceID}
+ if instance.Engine == db.Redis {
+ list, err := s.store.FindInstanceChangeHistoryList(ctx, find)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
+ }
+ if len(list) == 0 {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))
+ }
+ entry = list[0]
+ } else {
+ driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history ID %v for instance %q", historyID, instance.Title)).SetInternal(err)
+ }
+ defer driver.Close(ctx)
+ list, err := driver.FindMigrationHistoryList(ctx, find)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
+ }
+ if len(list) == 0 {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))
+ }
+ entry = list[0]
}
- entry := list[0]
if isSDL {
var engineType parser.EngineType
@@ -452,35 +464,70 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
}
- find := &db.MigrationHistoryFind{}
- databaseStr := c.QueryParams().Get("database")
- if databaseStr != "" {
- find.Database = &databaseStr
- }
- versionStr := c.QueryParams().Get("version")
- if versionStr != "" {
- find.Version = &versionStr
+ var migrationHistoryList []*db.MigrationHistory
+ find := &db.MigrationHistoryFind{
+ InstanceID: instance.UID,
}
- if limitStr := c.QueryParam("limit"); limitStr != "" {
- limit, err := strconv.Atoi(limitStr)
+ if instance.Engine == db.Redis {
+ if databaseStr := c.QueryParams().Get("database"); databaseStr != "" {
+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
+ InstanceID: &instance.ResourceID,
+ DatabaseName: &databaseStr,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)
+ }
+ if database == nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot find database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)
+ }
+ find.Database = &databaseStr
+ find.DatabaseID = &database.UID
+ }
+ if versionStr := c.QueryParams().Get("version"); versionStr != "" {
+ find.Version = &versionStr
+ }
+ if limitStr := c.QueryParam("limit"); limitStr != "" {
+ limit, err := strconv.Atoi(limitStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)
+ }
+ find.Limit = &limit
+ }
+
+ list, err := s.store.FindInstanceChangeHistoryList(ctx, find)
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
+ }
+ migrationHistoryList = list
+ } else {
+ if databaseStr := c.QueryParams().Get("database"); databaseStr != "" {
+ find.Database = &databaseStr
+ }
+ if versionStr := c.QueryParams().Get("version"); versionStr != "" {
+ find.Version = &versionStr
+ }
+ if limitStr := c.QueryParam("limit"); limitStr != "" {
+ limit, err := strconv.Atoi(limitStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)
+ }
+ find.Limit = &limit
}
- find.Limit = &limit
- }
- historyList := []*api.MigrationHistory{}
- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history for instance %q", instance.Title)).SetInternal(err)
- }
- defer driver.Close(ctx)
- list, err := driver.FindMigrationHistoryList(ctx, find)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
+ driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history for instance %q", instance.Title)).SetInternal(err)
+ }
+ defer driver.Close(ctx)
+ list, err := driver.FindMigrationHistoryList(ctx, find)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
+ }
+ migrationHistoryList = list
}
- for _, entry := range list {
+ historyList := []*api.MigrationHistory{}
+ for _, entry := range migrationHistoryList {
historyList = append(historyList, &api.MigrationHistory{
ID: entry.ID,
Creator: entry.Creator,
diff --git a/backend/server/server.go b/backend/server/server.go
index 552c5cf649..ce16da6f84 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -86,6 +86,8 @@ import (
_ "github.com/bytebase/bytebase/backend/plugin/db/mongodb"
// Register spanner driver.
_ "github.com/bytebase/bytebase/backend/plugin/db/spanner"
+ // Register redis driver.
+ _ "github.com/bytebase/bytebase/backend/plugin/db/redis"
// Register pingcap parser driver.
_ "github.com/pingcap/tidb/types/parser_driver"
diff --git a/backend/server/sql.go b/backend/server/sql.go
index 82c671fb09..9946f124d2 100644
--- a/backend/server/sql.go
+++ b/backend/server/sql.go
@@ -410,7 +410,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
defer driver.Close(ctx)
// TODO(p0ny): refactor
- if instance.Engine == db.MongoDB || instance.Engine == db.Spanner {
+ if instance.Engine == db.MongoDB || instance.Engine == db.Spanner || instance.Engine == db.Redis {
data, err := driver.QueryConn(ctx, nil, exec.Statement, &db.QueryContext{
Limit: exec.Limit,
ReadOnly: true,
@@ -613,7 +613,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
defer driver.Close(ctx)
// TODO(p0ny): refactor
- if instance.Engine == db.MongoDB || instance.Engine == db.Spanner {
+ if instance.Engine == db.MongoDB || instance.Engine == db.Spanner || instance.Engine == db.Redis {
data, err := driver.QueryConn(ctx, nil, exec.Statement, &db.QueryContext{
Limit: exec.Limit,
ReadOnly: false,
diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.go
index 5c7405cb63..8b4ce33848 100644
--- a/backend/store/instance_change_history.go
+++ b/backend/store/instance_change_history.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
+ "strconv"
"strings"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -130,10 +131,78 @@ func (*Store) createInstanceChangeHistoryImpl(ctx context.Context, tx *Tx, creat
UpdaterID: creatorID,
UpdatedTs: createdTs,
}
-
return changeHistory, nil
}
+func convertInstanceChangeHistoryToMigrationHistory(change *InstanceChangeHistoryMessage) (*db.MigrationHistory, error) {
+ var issueID string
+ if v := change.IssueID; v != nil {
+ issueID = strconv.Itoa(*v)
+ }
+
+ useSemanticVersion, version, semanticVersionSuffix, err := util.FromStoredVersion(change.Version)
+ if err != nil {
+ return nil, err
+ }
+
+ return &db.MigrationHistory{
+ ID: strconv.FormatInt(change.ID, 10),
+ Creator: "",
+ CreatedTs: change.CreatedTs,
+ Updater: "",
+ UpdatedTs: change.UpdatedTs,
+ ReleaseVersion: change.ReleaseVersion,
+ Namespace: "",
+ Sequence: int(change.Sequence),
+ Source: change.Source,
+ Type: change.Type,
+ Status: change.Status,
+ Version: version,
+ Description: change.Description,
+ Statement: change.Statement,
+ Schema: change.Schema,
+ SchemaPrev: change.SchemaPrev,
+ ExecutionDurationNs: change.ExecutionDurationNs,
+ IssueID: issueID,
+ Payload: change.Payload,
+ UseSemanticVersion: useSemanticVersion,
+ SemanticVersionSuffix: semanticVersionSuffix,
+ }, nil
+}
+
+// FindInstanceChangeHistoryList finds a list of instance change history and returns as a list of migration history.
+func (s *Store) FindInstanceChangeHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
+ findMessage := &FindInstanceChangeHistoryMessage{
+ InstanceID: find.InstanceID,
+ DatabaseID: find.DatabaseID,
+ Source: find.Source,
+ Version: find.Version,
+ Limit: find.Limit,
+ }
+ if v := find.ID; v != nil {
+ id, err := strconv.ParseInt(*v, 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ findMessage.ID = &id
+ }
+
+ list, err := s.ListInstanceChangeHistory(ctx, findMessage)
+ if err != nil {
+ return nil, err
+ }
+ var migrationHistoryList []*db.MigrationHistory
+ for _, change := range list {
+ migrationHistory, err := convertInstanceChangeHistoryToMigrationHistory(change)
+ if err != nil {
+ return nil, err
+ }
+ migrationHistoryList = append(migrationHistoryList, migrationHistory)
+ }
+
+ return migrationHistoryList, nil
+}
+
// ListInstanceChangeHistory finds the instance change history.
func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanceChangeHistoryMessage) ([]*InstanceChangeHistoryMessage, error) {
where, args := []string{"instance_id = $1"}, []interface{}{find.InstanceID}
@@ -232,9 +301,40 @@ func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanc
return list, nil
}
+// UpdateInstanceChangeHistoryAsDone updates a change history to done.
+func (s *Store) UpdateInstanceChangeHistoryAsDone(ctx context.Context, migrationDurationNs int64, updatedSchema string, insertedID string) error {
+ status := db.Done
+ id, err := strconv.ParseInt(insertedID, 10, 64)
+ if err != nil {
+ return err
+ }
+ update := &UpdateInstanceChangeHistoryMessage{
+ ID: id,
+ ExecutionDurationNs: &migrationDurationNs,
+ Status: &status,
+ Schema: &updatedSchema,
+ }
+ return s.updateInstanceChangeHistory(ctx, update)
+}
+
+// UpdateInstanceChangeHistoryAsFailed updates a change history to failed.
+func (s *Store) UpdateInstanceChangeHistoryAsFailed(ctx context.Context, migrationDurationNs int64, insertedID string) error {
+ status := db.Failed
+ id, err := strconv.ParseInt(insertedID, 10, 64)
+ if err != nil {
+ return err
+ }
+ update := &UpdateInstanceChangeHistoryMessage{
+ ID: id,
+ ExecutionDurationNs: &migrationDurationNs,
+ Status: &status,
+ }
+ return s.updateInstanceChangeHistory(ctx, update)
+}
+
// UpdateInstanceChangeHistory updates an instance change history.
// it deprecates the old UpdateHistoryAsDone and UpdateHistoryAsFailed.
-func (s *Store) UpdateInstanceChangeHistory(ctx context.Context, update *UpdateInstanceChangeHistoryMessage) error {
+func (s *Store) updateInstanceChangeHistory(ctx context.Context, update *UpdateInstanceChangeHistoryMessage) error {
set, args := []string{}, []interface{}{}
if v := update.Status; v != nil {
set, args = append(set, fmt.Sprintf("status = $%d", len(args)+1)), append(args, *v)
@@ -337,10 +437,10 @@ func (s *Store) GetLargestInstanceChangeHistoryVersionSinceBaseline(ctx context.
// CreatePendingInstanceChangeHistory creates an instance change history.
// it deprecates the old InsertPendingHistory.
-func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, sequence int64, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (int64, error) {
+func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, sequence int64, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
- return -1, err
+ return "", err
}
defer tx.Rollback()
@@ -362,12 +462,12 @@ func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, sequence
Payload: m.Payload,
}, m.CreatorID)
if err != nil {
- return -1, err
+ return "", err
}
if err := tx.Commit(); err != nil {
- return -1, err
+ return "", err
}
- return h.ID, nil
+ return strconv.FormatInt(h.ID, 10), nil
}
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index c78f5ef603..73f7fb35c0 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -2,31 +2,52 @@
package utils
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
+ "time"
"github.com/github/gh-ost/go/base"
ghostsql "github.com/github/gh-ost/go/sql"
"github.com/pkg/errors"
+ "go.uber.org/zap"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/store"
)
// GetLatestSchemaVersion gets the latest schema version for a database.
-func GetLatestSchemaVersion(ctx context.Context, driver db.Driver, databaseName string) (string, error) {
+func GetLatestSchemaVersion(ctx context.Context, store *store.Store, driver db.Driver, instanceID int, databaseID int, databaseName string) (string, error) {
// TODO(d): support semantic versioning.
limit := 1
- history, err := driver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{
- Database: &databaseName,
- Limit: &limit,
- })
+ find := &db.MigrationHistoryFind{
+ InstanceID: instanceID,
+ Database: &databaseName,
+ DatabaseID: &databaseID,
+ Limit: &limit,
+ }
+
+ if driver.GetType() == db.Redis {
+ history, err := store.FindInstanceChangeHistoryList(ctx, find)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)
+ }
+ var schemaVersion string
+ if len(history) == 1 {
+ schemaVersion = history[0].Version
+ }
+ return schemaVersion, nil
+ }
+
+ history, err := driver.FindMigrationHistoryList(ctx, find)
if err != nil {
return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)
}
@@ -467,3 +488,145 @@ func passCheck(taskCheckRunList []*store.TaskCheckRunMessage, checkType api.Task
return true, nil
}
+
+// ExecuteMigration executes migration.
+func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {
+ var prevSchemaBuf bytes.Buffer
+ // Don't record schema if the database hasn't existed yet or is schemaless (e.g. Mongo).
+ if !m.CreateDatabase {
+ // For baseline migration, we also record the live schema to detect the schema drift.
+ // See https://bytebase.com/blog/what-is-database-schema-drift
+ if _, err := driver.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {
+ return "", "", err
+ }
+ }
+
+ insertedID, err := beginMigration(ctx, store, m, prevSchemaBuf.String(), statement)
+ if err != nil {
+ if common.ErrorCode(err) == common.MigrationAlreadyApplied {
+ return insertedID, prevSchemaBuf.String(), nil
+ }
+ return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)
+ }
+
+ startedNs := time.Now().UnixNano()
+
+ defer func() {
+ if err := endMigration(ctx, store, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {
+ log.Error("Failed to update migration history record",
+ zap.Error(err),
+ zap.String("migration_id", migrationHistoryID),
+ )
+ }
+ }()
+
+ // Phase 3 - Executing migration
+ // Branch migration type always has empty sql.
+ // Baseline migration type could has non-empty sql but will not execute.
+ // https://github.com/bytebase/bytebase/issues/394
+ doMigrate := true
+ if statement == "" {
+ doMigrate = false
+ }
+ if m.Type == db.Baseline {
+ doMigrate = false
+ }
+ if doMigrate {
+ if _, _, err := driver.ExecuteMigration(ctx, m, statement); err != nil {
+ return "", "", err
+ }
+ }
+
+ // Phase 4 - Dump the schema after migration
+ var afterSchemaBuf bytes.Buffer
+ if _, err := driver.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {
+ // We will ignore the dump error if the database is dropped.
+ if strings.Contains(err.Error(), "not found") {
+ return insertedID, "", nil
+ }
+ return "", "", err
+ }
+
+ return insertedID, afterSchemaBuf.String(), nil
+}
+
+// beginMigration checks before executing migration and inserts a migration history record with pending status.
+func beginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo, prevSchema string, statement string) (string, error) {
+ // Convert version to stored version.
+ storedVersion, err := util.ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to convert to stored version")
+ }
+ // Phase 1 - Pre-check before executing migration
+ // Check if the same migration version has already been applied.
+ if list, err := store.FindInstanceChangeHistoryList(ctx, &db.MigrationHistoryFind{
+ InstanceID: m.InstanceID,
+ DatabaseID: m.DatabaseID,
+ Version: &m.Version,
+ }); err != nil {
+ return "", errors.Wrap(err, "failed to check duplicate version")
+ } else if len(list) > 0 {
+ migrationHistory := list[0]
+ switch migrationHistory.Status {
+ case db.Done:
+ if migrationHistory.IssueID != m.IssueID {
+ return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)
+ }
+ return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)
+ case db.Pending:
+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)
+ log.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ if m.Force {
+ return migrationHistory.ID, nil
+ }
+ return "", common.Wrap(err, common.MigrationPending)
+ case db.Failed:
+ err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version ", m.Database, m.Version)
+ log.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ if m.Force {
+ return migrationHistory.ID, nil
+ }
+ return "", common.Wrap(err, common.MigrationFailed)
+ }
+ }
+
+ largestSequence, err := store.GetLargestInstanceChangeHistorySequence(ctx, m.InstanceID, m.DatabaseID, false /* baseline */)
+ if err != nil {
+ return "", err
+ }
+
+ // Check if there is any higher version already been applied since the last baseline or branch.
+ if version, err := store.GetLargestInstanceChangeHistoryVersionSinceBaseline(ctx, m.InstanceID, m.DatabaseID); err != nil {
+ return "", err
+ } else if version != nil && len(*version) > 0 && *version >= m.Version {
+ return "", common.Errorf(common.MigrationOutOfOrder, "database %q has already applied version %s which >= %s", m.Database, *version, m.Version)
+ }
+
+ // Phase 2 - Record migration history as PENDING.
+ // MySQL runs DDL in its own transaction, so we can't commit migration history together with DDL in a single transaction.
+ // Thus we sort of doing a 2-phase commit, where we first write a PENDING migration record, and after migration completes, we then
+ // update the record to DONE together with the updated schema.
+ statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
+ insertedID, err := store.CreatePendingInstanceChangeHistory(ctx, largestSequence+1, prevSchema, m, storedVersion, statementRecord)
+ if err != nil {
+ return "", err
+ }
+
+ return insertedID, nil
+}
+
+func endMigration(ctx context.Context, store *store.Store, startedNs int64, insertedID string, updatedSchema string, _ string, isDone bool) error {
+ var err error
+ migrationDurationNs := time.Now().UnixNano() - startedNs
+
+ if isDone {
+ err = store.UpdateInstanceChangeHistoryAsDone(ctx, migrationDurationNs, updatedSchema, insertedID)
+ // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.
+ } else {
+ // Otherwise, update the migration history as 'FAILED', execution_duration.
+ err = store.UpdateInstanceChangeHistoryAsFailed(ctx, migrationDurationNs, insertedID)
+ }
+ return err
+}
diff --git a/frontend/src/assets/db-redis.png b/frontend/src/assets/db-redis.png
new file mode 100644
index 0000000000..66a7c7081d
Binary files /dev/null and b/frontend/src/assets/db-redis.png differ
diff --git a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue
index 90e8dc9928..fb642f7c7c 100644
--- a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue
@@ -191,6 +191,7 @@ import { Database, DatabaseId, Project, ProjectId, UNKNOWN_ID } from "@/types";
import {
allowGhostMigration,
allowUsingSchemaEditor,
+ instanceHasAlterSchema,
filterDatabaseByKeyword,
sortDatabaseList,
} from "@/utils";
@@ -294,7 +295,7 @@ const databaseList = computed(() => {
list = list.filter((db) => db.syncStatus === "OK");
if (isAlterSchema.value) {
// We disallow users to alter schema for MongoDB databases.
- list = list.filter((db) => db.instance.engine !== "MONGODB");
+ list = list.filter((db) => instanceHasAlterSchema(db.instance));
}
const keyword = state.searchText.trim();
diff --git a/frontend/src/components/CreateDataSourceExample.vue b/frontend/src/components/CreateDataSourceExample.vue
index ecb6436b6a..1562de1e23 100644
--- a/frontend/src/components/CreateDataSourceExample.vue
+++ b/frontend/src/components/CreateDataSourceExample.vue
@@ -173,6 +173,8 @@ const grantStatement = (
return 'use admin;\ndb.createUser({\n\tuser: "bytebase", \n\tpwd: "YOUR_DB_PWD", \n\troles: [\n\t\t{role: "readWriteAnyDatabase", db: "admin"},\n\t\t{role: "dbAdminAnyDatabase", db: "admin"},\n\t\t{role: "userAdminAnyDatabase", db: "admin"}\n\t]\n});';
case "SPANNER":
return "";
+ case "REDIS":
+ return "ACL SETUSER bytebase on >YOUR_DB_PWD +@all &*";
}
} else {
switch (engineType) {
@@ -189,6 +191,9 @@ const grantStatement = (
return 'use admin;\ndb.createUser({\n\tuser: "bytebase", \n\tpwd: "YOUR_DB_PWD", \n\troles: [\n\t\t{role: "readAnyDatabase", db: "admin"},\n\t\t{role: "dbAdminAnyDatabase", db: "admin"},\n\t\t{role: "userAdminAnyDatabase", db: "admin"}\n\t]\n});';
case "SPANNER":
return "";
+ case "REDIS":
+ // TODO(xz)
+ return "";
}
}
};
diff --git a/frontend/src/components/DatabaseMigrationHistoryPanel.vue b/frontend/src/components/DatabaseMigrationHistoryPanel.vue
index 9a335904e9..070a513cfb 100644
--- a/frontend/src/components/DatabaseMigrationHistoryPanel.vue
+++ b/frontend/src/components/DatabaseMigrationHistoryPanel.vue
@@ -5,7 +5,7 @@
>
<span>{{ $t("change-history.self") }}</span>
<BBTooltipButton
- v-if="!isTenantProject && allowEdit"
+ v-if="showEstablishBaselineButton"
type="primary"
:disabled="!allowMigrate"
tooltip-mode="DISABLED-ONLY"
@@ -85,7 +85,11 @@ import {
} from "../types";
import { useRouter } from "vue-router";
import { BBTableSectionDataSource } from "../bbkit/types";
-import { hasWorkspacePermission, instanceSlug } from "../utils";
+import {
+ hasWorkspacePermission,
+ instanceHasAlterSchema,
+ instanceSlug,
+} from "../utils";
import { useCurrentUser, useInstanceStore } from "@/store";
interface LocalState {
@@ -154,11 +158,17 @@ export default defineComponent({
currentUser.value.role
);
});
-
const isTenantProject = computed(() => {
return props.database.project.tenantMode === "TENANT";
});
+ const showEstablishBaselineButton = computed(() => {
+ if (!instanceHasAlterSchema(props.database.instance)) return false;
+ if (isTenantProject.value) return false;
+ if (!props.allowEdit) return false;
+ return true;
+ });
+
const allowMigrate = computed(() => {
if (!props.allowEdit) return false;
@@ -242,6 +252,7 @@ export default defineComponent({
state,
allowConfigInstance,
isTenantProject,
+ showEstablishBaselineButton,
allowMigrate,
attentionTitle,
migrationHistorySectionList,
diff --git a/frontend/src/components/DatabaseName.vue b/frontend/src/components/DatabaseName.vue
new file mode 100644
index 0000000000..123a4e95b8
--- /dev/null
+++ b/frontend/src/components/DatabaseName.vue
@@ -0,0 +1,29 @@
+<template>
+ <component :is="tag">
+ <span v-if="prefix" class="ml-1 text-gray-400">{{ prefix }}</span>
+ {{ database.name }}
+ </component>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import type { Database } from "@/types";
+
+const props = withDefaults(
+ defineProps<{
+ database: Database;
+ tag?: string;
+ }>(),
+ {
+ tag: "span",
+ }
+);
+
+const prefix = computed(() => {
+ const { database } = props;
+ if (database.instance.engine === "REDIS") {
+ return `${database.instance.name}`;
+ }
+ return "";
+});
+</script>
diff --git a/frontend/src/components/DatabaseOverviewPanel.vue b/frontend/src/components/DatabaseOverviewPanel.vue
index 9c0d7722c4..225b10d6bf 100644
--- a/frontend/src/components/DatabaseOverviewPanel.vue
+++ b/frontend/src/components/DatabaseOverviewPanel.vue
@@ -95,33 +95,35 @@
</BBSelect>
</div>
- <div class="text-lg leading-6 font-medium text-main mb-4">
- <span v-if="databaseEngine === 'MONGODB'">{{
- $t("db.collections")
- }}</span>
- <span v-else>{{ $t("db.tables") }}</span>
- </div>
+ <template v-if="databaseEngine !== 'REDIS'">
+ <div class="text-lg leading-6 font-medium text-main mb-4">
+ <span v-if="databaseEngine === 'MONGODB'">{{
+ $t("db.collections")
+ }}</span>
+ <span v-else>{{ $t("db.tables") }}</span>
+ </div>
- <TableTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :table-list="tableList"
- />
+ <TableTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :table-list="tableList"
+ />
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.views") }}
- </div>
- <ViewTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :view-list="viewList"
- />
-
- <template v-if="database.instance.engine == 'POSTGRES'">
<div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.extensions") }}
+ {{ $t("db.views") }}
</div>
- <DBExtensionTable :db-extension-list="dbExtensionList" />
+ <ViewTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :view-list="viewList"
+ />
+
+ <template v-if="database.instance.engine == 'POSTGRES'">
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.extensions") }}
+ </div>
+ <DBExtensionTable :db-extension-list="dbExtensionList" />
+ </template>
</template>
</div>
diff --git a/frontend/src/components/DatabaseTable.vue b/frontend/src/components/DatabaseTable.vue
index afefd8952a..97e0bf88b1 100644
--- a/frontend/src/components/DatabaseTable.vue
+++ b/frontend/src/components/DatabaseTable.vue
@@ -36,7 +36,7 @@
:tooltip="true"
@failed="handleGotoSQLEditorFailed"
/>
- <span>{{ database.name }}</span>
+ <DatabaseName :database="database" tag="span" />
<BBBadge
v-if="isPITRDatabase(database)"
text="PITR"
@@ -242,6 +242,7 @@ import { Database, Policy } from "../types";
import { BBGridColumn } from "../bbkit/types";
import InstanceEngineIcon from "./InstanceEngineIcon.vue";
import TenantIcon from "./TenantIcon.vue";
+import DatabaseName from "@/components/DatabaseName.vue";
import { SQLEditorButton } from "@/components/DatabaseDetail";
import { useCurrentUser, usePolicyStore } from "@/store";
import {
@@ -342,7 +343,7 @@ const sortedDatabaseList = computed(() => {
return 1;
}
// Fallback to `id` DESC
- return -(a.id - b.id);
+ return -(+a.id - +b.id);
});
}
diff --git a/frontend/src/components/InstanceEngineIcon.vue b/frontend/src/components/InstanceEngineIcon.vue
index fa46b9e477..e287b56eaa 100644
--- a/frontend/src/components/InstanceEngineIcon.vue
+++ b/frontend/src/components/InstanceEngineIcon.vue
@@ -39,6 +39,7 @@ export default defineComponent({
CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,
MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,
SPANNER: new URL("../assets/db-spanner.png", import.meta.url).href,
+ REDIS: new URL("../assets/db-redis.png", import.meta.url).href,
};
const SelectedEngineIconPath = computed(() => {
return EngineIconPath[props.instance.engine];
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index 336c7bd11e..d07b37dd06 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -3,7 +3,7 @@
<div class="divide-y divide-block-border w-[850px]">
<div
v-if="isCreating"
- class="w-full mt-4 mb-6 grid grid-cols-1 gap-4 sm:grid-cols-7"
+ class="w-full mt-4 mb-6 grid grid-cols-1 gap-4 sm:grid-cols-4"
>
<template v-for="engine in engineList" :key="engine">
<div
@@ -685,6 +685,8 @@ const getDefaultPort = (engine: EngineType) => {
return "4000";
} else if (engine == "MONGODB") {
return "27017";
+ } else if (engine === "REDIS") {
+ return "6379";
}
return "3306";
};
@@ -722,6 +724,7 @@ const engineList = computed(() => {
"CLICKHOUSE",
"MONGODB",
"SPANNER",
+ "REDIS",
];
return engines;
});
@@ -734,6 +737,7 @@ const EngineIconPath = {
CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,
MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,
SPANNER: new URL("../assets/db-spanner.png", import.meta.url).href,
+ REDIS: new URL("../assets/db-redis.png", import.meta.url).href,
};
const mongodbConnectionStringSchemaList = ["mongodb://", "mongodb+srv://"];
@@ -863,7 +867,8 @@ const showSSL = computed((): boolean => {
basicInformation.value.engine === "CLICKHOUSE" ||
basicInformation.value.engine === "MYSQL" ||
basicInformation.value.engine === "TIDB" ||
- basicInformation.value.engine === "POSTGRES"
+ basicInformation.value.engine === "POSTGRES" ||
+ basicInformation.value.engine === "REDIS"
);
});
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index 85940965c8..d5102d003b 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -17,7 +17,8 @@ export type EngineType =
| "SNOWFLAKE"
| "TIDB"
| "MONGODB"
- | "SPANNER";
+ | "SPANNER"
+ | "REDIS";
export function convertEngineType(type: EngineType): Engine {
switch (type) {
@@ -33,7 +34,10 @@ export function convertEngineType(type: EngineType): Engine {
return Engine.TIDB;
case "MONGODB":
return Engine.MONGODB;
- // TODO(xz): add Spanner here.
+ case "SPANNER":
+ return Engine.SPANNER;
+ case "REDIS":
+ return Engine.REDIS;
}
return Engine.ENGINE_UNSPECIFIED;
}
@@ -52,6 +56,8 @@ export function defaultCharset(type: EngineType): string {
return "";
case "SPANNER":
return "";
+ case "REDIS":
+ return "";
}
}
@@ -71,6 +77,8 @@ export function engineName(type: EngineType): string {
return "MongoDB";
case "SPANNER":
return "Spanner";
+ case "REDIS":
+ return "Redis";
}
}
@@ -91,6 +99,8 @@ export function defaultCollation(type: EngineType): string {
return "";
case "SPANNER":
return "";
+ case "REDIS":
+ return "";
}
}
diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor.ts
index 693af4de55..88ba12d25c 100644
--- a/frontend/src/types/sqlEditor.ts
+++ b/frontend/src/types/sqlEditor.ts
@@ -6,7 +6,7 @@ export type EditorModel = monaco.editor.ITextModel;
export type EditorPosition = monaco.Position;
export type CompletionItems = monaco.languages.CompletionItem[];
-export type Language = "sql" | "javascript";
+export type Language = "sql" | "javascript" | "redis";
export const EngineTypesUsingSQL = [
"MYSQL",
@@ -22,6 +22,9 @@ export const languageOfEngine = (engine?: EngineType | "unknown"): Language => {
if (engine === "MONGODB") {
return "javascript";
}
+ if (engine === "REDIS") {
+ return "redis";
+ }
return "sql";
};
diff --git a/frontend/src/utils/instance.ts b/frontend/src/utils/instance.ts
index c858c025a7..2c79c8a1e4 100644
--- a/frontend/src/utils/instance.ts
+++ b/frontend/src/utils/instance.ts
@@ -53,3 +53,25 @@ export const isValidSpannerHost = (host: string) => {
/^projects\/(?<PROJECT_ID>(?:[a-z]|[-.:]|[0-9])+)\/instances\/(?<INSTANCE_ID>(?:[a-z]|[-]|[0-9])+)$/;
return RE.test(host);
};
+
+export const instanceHasAlterSchema = (instance: Instance): boolean => {
+ const { engine } = instance;
+ if (engine === "MONGODB") return false;
+ if (engine === "REDIS") return false;
+ return true;
+};
+
+export const instanceHasBackupRestore = (instance: Instance): boolean => {
+ const { engine } = instance;
+ if (engine === "MONGODB") return false;
+ if (engine === "REDIS") return false;
+ if (engine === "SPANNER") return false;
+ return true;
+};
+
+export const instanceHasReadonlyMode = (instance: Instance): boolean => {
+ const { engine } = instance;
+ if (engine === "MONGODB") return false;
+ if (engine === "REDIS") return false;
+ return true;
+};
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index 0825ca0b65..77e84cf5c4 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -315,6 +315,8 @@ import {
isDatabaseAccessible,
allowUsingSchemaEditor,
isArchivedDatabase,
+ instanceHasBackupRestore,
+ instanceHasAlterSchema,
} from "@/utils";
import {
ProjectId,
@@ -395,7 +397,7 @@ const database = computed((): Database => {
});
const hasSchemaDiagramFeature = computed((): boolean => {
- return database.value.instance.engine !== "MONGODB";
+ return instanceHasAlterSchema(database.value.instance);
});
const accessControlPolicy = usePolicyByDatabaseAndType(
@@ -520,7 +522,7 @@ const allowAlterSchemaOrChangeData = computed(() => {
const allowAlterSchema = computed(() => {
return (
allowAlterSchemaOrChangeData.value &&
- database.value.instance.engine !== "MONGODB"
+ instanceHasAlterSchema(database.value.instance)
);
});
@@ -530,10 +532,7 @@ const allowEditDatabaseLabels = computed((): boolean => {
});
const tabItemList = computed((): BBTabFilterItem[] => {
- if (
- database.value.instance.engine === "SPANNER" ||
- database.value.instance.engine === "MONGODB"
- ) {
+ if (!instanceHasBackupRestore(database.value.instance)) {
return databaseTabItemList
.filter((item) => item.hash !== "backup-and-restore")
.map((item) => {
diff --git a/frontend/src/views/sql-editor/EditorCommon/DataTable.vue b/frontend/src/views/sql-editor/EditorCommon/DataTable.vue
index cfd09aef22..d787e355f5 100644
--- a/frontend/src/views/sql-editor/EditorCommon/DataTable.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/DataTable.vue
@@ -53,7 +53,10 @@
:key="cellIndex"
class="px-2 py-1 text-sm dark:text-gray-100 leading-5 whitespace-pre-wrap break-all border border-block-border group-last:border-b-0 group-even:bg-gray-50/50 dark:group-even:bg-gray-700/50"
>
- {{ cell.getValue() }}
+ <template v-if="cell.getValue()">{{
+ cell.getValue()
+ }}</template>
+ <br v-else class="min-h-[1rem] inline-flex" />
</td>
</tr>
</tbody>
diff --git a/frontend/src/views/sql-editor/SQLEditorPage.vue b/frontend/src/views/sql-editor/SQLEditorPage.vue
index 8ef33e53ad..f82c7407c5 100644
--- a/frontend/src/views/sql-editor/SQLEditorPage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorPage.vue
@@ -66,7 +66,7 @@
>
<template #instance>
<span class="inline-flex items-center mx-1">
- <InstanceEngineIcon :instance="instance" />
+ <InstanceEngineIcon :instance="instance" class="mr-1" />
<span>{{ instanceName(instance) }}</span>
</span>
</template>
@@ -127,7 +127,11 @@ import EditorPanel from "./EditorPanel/EditorPanel.vue";
import TerminalPanel from "./TerminalPanel/TerminalPanel.vue";
import TabList from "./TabList";
import TablePanel from "./TablePanel/TablePanel.vue";
-import { allowUsingSchemaEditor, isDatabaseAccessible } from "@/utils";
+import {
+ allowUsingSchemaEditor,
+ instanceHasReadonlyMode,
+ isDatabaseAccessible,
+} from "@/utils";
import AdminModeButton from "./EditorCommon/AdminModeButton.vue";
import SchemaEditorModal from "@/components/AlterSchemaPrepForm/SchemaEditorModal.vue";
import { useWindowSize } from "@vueuse/core";
@@ -178,10 +182,7 @@ const instance = useInstanceById(
const allowReadOnlyMode = computed(() => {
if (isDisconnected.value) return true;
- if (instance.value.engine === "MONGODB") {
- return false;
- }
- return true;
+ return instanceHasReadonlyMode(instance.value);
});
const alterSchemaState = reactive<AlterSchemaState>({
diff --git a/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue
index d21b925e03..5c951bca24 100644
--- a/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue
+++ b/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue
@@ -105,7 +105,10 @@ watch(
);
const firstLinePrompt = computed(() => {
- return selectedLanguage.value === "sql" ? "SQL>" : "MONGO>";
+ const lang = selectedLanguage.value;
+ if (lang === "javascript") return "MONGO>";
+ if (lang === "redis") return "REDIS>";
+ return "SQL>";
});
const getLineNumber = (lineNumber: number) => {
diff --git a/go.mod b/go.mod
index 06bf42c4ea..f59fd8f683 100644
--- a/go.mod
+++ b/go.mod
@@ -37,6 +37,7 @@ require (
github.com/pingcap/tidb/parser v0.0.0-20221101143359-5b0be9af540e
github.com/pkg/errors v0.9.1
github.com/qiangmzsx/string-adapter/v2 v2.1.0
+ github.com/redis/go-redis/v9 v9.0.2
github.com/segmentio/analytics-go v3.1.0+incompatible
github.com/shopspring/decimal v1.3.1
github.com/snowflakedb/gosnowflake v1.6.14
@@ -103,6 +104,7 @@ require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/envoyproxy/go-control-plane v0.10.3 // indirect
github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect
github.com/form3tech-oss/jwt-go v3.2.5+incompatible // indirect
diff --git a/go.sum b/go.sum
index ff072bf5dc..6c9b8ba007 100644
--- a/go.sum
+++ b/go.sum
@@ -164,6 +164,8 @@ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dR
github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
+github.com/bsm/ginkgo/v2 v2.5.0 h1:aOAnND1T40wEdAtkGSkvSICWeQ8L3UASX7YVCqQx+eQ=
+github.com/bsm/gomega v1.20.0 h1:JhAwLmtRzXFTx2AkALSLa8ijZafntmhSoU63Ok18Uq8=
github.com/bytebase/gh-ost v1.1.3-0.20220728080340-11d9c9027651 h1:NpoTuRY6Ckj37zTlEax/UTfvHCOdanI5/5dVCarOD18=
github.com/bytebase/gh-ost v1.1.3-0.20220728080340-11d9c9027651/go.mod h1:/HsnX0+34LXVz3MxtZoW15GiwEOXz/PrEhutjb3icfE=
github.com/bytebase/pg_query_go/v2 v2.0.0-20221123093650-17425d1d18b7 h1:RDN6UnjTq4HR4LKrN8Yav4XfwUoGRjTocvWmzGr6Usc=
@@ -246,6 +248,8 @@ github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE=
github.com/dgraph-io/ristretto v0.1.1-0.20220403145359-8e850b710d6d h1:Wrc3UKTS+cffkOx0xRGFC+ZesNuTfn0ThvEC72N0krk=
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
@@ -813,6 +817,8 @@ github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0ua
github.com/qiangmzsx/string-adapter/v2 v2.1.0 h1:q0y8TPa/sTwtriJPRe8gWL++PuZ+XbOUuvKU+hvtTYs=
github.com/qiangmzsx/string-adapter/v2 v2.1.0/go.mod h1:PElPB7b7HnGKTsuADAffFpOQXHqjEGJz1+U1a6yR5wA=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
+github.com/redis/go-redis/v9 v9.0.2 h1:BA426Zqe/7r56kCcvxYLWe1mkaz71LKF77GwgFzSxfE=
+github.com/redis/go-redis/v9 v9.0.2/go.mod h1:/xDTe9EF1LM61hek62Poq2nzQSGj0xSrEtEHbBQevps=
github.com/remyoudompheng/bigfft v0.0.0-20190728182440-6a916e37a237/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20220927061507-ef77025ab5aa h1:tEkEyxYeZ43TR55QU/hsIt9aRGBxbgGuz9CGykjvogY=
github.com/remyoudompheng/bigfft v0.0.0-20220927061507-ef77025ab5aa/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=