Skip to content

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

feat: support to use RisingWave as instance (#7427)

TennyZhuang9a85b2d06b6b
diff --git a/backend/api/v1/common.go b/backend/api/v1/common.go
index e378603cf1..ade77a0285 100644
--- a/backend/api/v1/common.go
+++ b/backend/api/v1/common.go
@@ -331,6 +331,8 @@ func convertToEngine(engine db.Type) v1pb.Engine {
return v1pb.Engine_MARIADB
case db.OceanBase:
return v1pb.Engine_OCEANBASE
+ case db.RisingWave:
+ return v1pb.Engine_RISINGWAVE
case db.DM:
return v1pb.Engine_DM
}
@@ -369,6 +371,8 @@ func convertEngine(engine v1pb.Engine) db.Type {
return db.OceanBase
case v1pb.Engine_DM:
return db.DM
+ case v1pb.Engine_RISINGWAVE:
+ return db.RisingWave
}
return db.UnknownType
}
diff --git a/backend/api/v1/instance_role_service.go b/backend/api/v1/instance_role_service.go
index 09e5c9fc5a..a551ad64e8 100644
--- a/backend/api/v1/instance_role_service.go
+++ b/backend/api/v1/instance_role_service.go
@@ -300,7 +300,7 @@ func validateRole(dbType db.Type, upsert *db.DatabaseRoleUpsertMessage) error {
return status.Errorf(codes.InvalidArgument, "Invalid role name, role name cannot be empty")
}
switch dbType {
- case db.Postgres:
+ case db.Postgres, db.RisingWave:
if v := upsert.ConnectionLimit; v != nil && *v < int32(-1) {
return status.Errorf(codes.InvalidArgument, "Invalid connection limit, it should greater than or equal to -1")
}
diff --git a/backend/api/v1/rollout_service_task.go b/backend/api/v1/rollout_service_task.go
index e2f629281d..14c55e0bdc 100644
--- a/backend/api/v1/rollout_service_task.go
+++ b/backend/api/v1/rollout_service_task.go
@@ -961,6 +961,13 @@ func checkCharacterSetCollationOwner(dbType db.Type, characterSet, collation, ow
if owner == "" {
return errors.Errorf("database owner is required for Redshift")
}
+ case db.RisingWave:
+ if characterSet != "" {
+ return errors.Errorf("RisingWave does not support character set, but got %s", characterSet)
+ }
+ if collation != "" {
+ return errors.Errorf("RisingWave does not support collation, but got %s", collation)
+ }
case db.SQLite, db.MongoDB, db.MSSQL:
// no-op.
default:
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index cde308c83d..a6008efa29 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -788,7 +788,7 @@ func (s *SQLService) preExport(ctx context.Context, request *v1pb.ExportRequest)
if err != nil {
return nil, nil, nil, nil, status.Errorf(codes.Internal, "Failed to get sensitive schema info: %s", request.Statement)
}
- case db.Postgres:
+ case db.Postgres, db.RisingWave:
sensitiveSchemaInfo, err = s.getSensitiveSchemaInfo(ctx, instance, []string{request.ConnectionDatabase}, request.ConnectionDatabase)
if err != nil {
return nil, nil, nil, nil, status.Errorf(codes.Internal, "Failed to get sensitive schema info: %s", request.Statement)
@@ -1093,7 +1093,7 @@ func (s *SQLService) preQuery(ctx context.Context, request *v1pb.QueryRequest) (
if err != nil {
return nil, nil, advisor.Success, nil, nil, nil, status.Errorf(codes.Internal, "Failed to get sensitive schema info for statement: %s, error: %v", request.Statement, err.Error())
}
- case db.Postgres, db.Redshift:
+ case db.Postgres, db.Redshift, db.RisingWave:
sensitiveSchemaInfo, err = s.getSensitiveSchemaInfo(ctx, instance, []string{request.ConnectionDatabase}, request.ConnectionDatabase)
if err != nil {
return nil, nil, advisor.Success, nil, nil, nil, status.Errorf(codes.Internal, "Failed to get sensitive schema info for statement: %s, error: %v", request.Statement, err.Error())
@@ -1303,7 +1303,7 @@ func (s *SQLService) getSensitiveSchemaInfo(ctx context.Context, instance *store
Name: table.Name,
ColumnList: []db.ColumnInfo{},
}
- if instance.Engine == db.Postgres || instance.Engine == db.Redshift {
+ if instance.Engine == db.Postgres || instance.Engine == db.Redshift || instance.Engine == db.RisingWave {
tableSchema.Name = fmt.Sprintf("%s.%s", schema.Name, table.Name)
}
for _, column := range table.Columns {
diff --git a/backend/component/dbfactory/dbfactory.go b/backend/component/dbfactory/dbfactory.go
index b78f6d095c..31594208bd 100644
--- a/backend/component/dbfactory/dbfactory.go
+++ b/backend/component/dbfactory/dbfactory.go
@@ -105,7 +105,7 @@ func (d *DBFactory) GetDataSourceDriver(ctx context.Context, engine db.Type, dat
case db.MySQL, db.TiDB, db.MariaDB, db.OceanBase:
// TODO(d): use maria mysqlbinlog for MariaDB.
dbBinDir = d.mysqlBinDir
- case db.Postgres:
+ case db.Postgres, db.RisingWave:
dbBinDir = d.pgBinDir
case db.MongoDB:
dbBinDir = d.mongoBinDir
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index c515817531..706bb13976 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -55,6 +55,8 @@ const (
MariaDB Type = "MARIADB"
// DM is the database type for DM.
DM Type = "DM"
+ // RisingWave is the database type for RisingWave.
+ RisingWave Type = "RISINGWAVE"
// UnknownType is the database type for UNKNOWN.
UnknownType Type = "UNKNOWN"
diff --git a/backend/plugin/db/risingwave/dump.go b/backend/plugin/db/risingwave/dump.go
new file mode 100644
index 0000000000..6978b55631
--- /dev/null
+++ b/backend/plugin/db/risingwave/dump.go
@@ -0,0 +1,18 @@
+package risingwave
+
+import (
+ "context"
+ "io"
+)
+
+// Dump dumps the database.
+// TODO: RisingWave doesn't support pg_dump yet.
+func (*Driver) Dump(_ context.Context, _ io.Writer, _ bool) (string, error) {
+ return "", nil
+}
+
+// Restore restores a database.
+// TODO: RisingWave doesn't support pg_dump yet.
+func (*Driver) Restore(_ context.Context, _ io.Reader) error {
+ return nil
+}
diff --git a/backend/plugin/db/risingwave/migrate.go b/backend/plugin/db/risingwave/migrate.go
new file mode 100644
index 0000000000..63bb31ad18
--- /dev/null
+++ b/backend/plugin/db/risingwave/migrate.go
@@ -0,0 +1,64 @@
+package risingwave
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/util"
+)
+
+// FindMigrationHistoryList finds the migration history.
+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
+ baseQuery := `
+ SELECT
+ id,
+ created_by,
+ created_ts,
+ updated_by,
+ updated_ts,
+ release_version,
+ namespace,
+ sequence,
+ source,
+ type,
+ status,
+ version,
+ description,
+ statement,
+ ` + `"schema",` + `
+ schema_prev,
+ execution_duration_ns,
+ issue_id,
+ payload
+ FROM migration_history `
+ paramNames, params := []string{}, []any{}
+ if v := find.ID; v != nil {
+ paramNames, params = append(paramNames, "id"), append(params, *v)
+ }
+ if v := find.Database; v != nil {
+ paramNames, params = append(paramNames, "namespace"), append(params, *v)
+ }
+ if v := find.Version; v != nil {
+ // TODO(d): support semantic versioning.
+ storedVersion, err := util.ToStoredVersion(false, *v, "")
+ if err != nil {
+ return nil, err
+ }
+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)
+ }
+ if v := find.Source; v != nil {
+ paramNames, params = append(paramNames, "source"), append(params, *v)
+ }
+ var query = baseQuery +
+ db.FormatParamNameInNumberedPosition(paramNames) +
+ `ORDER BY id DESC`
+ if v := find.Limit; v != nil {
+ query += fmt.Sprintf(" LIMIT %d", *v)
+ }
+ if v := find.Offset; v != nil {
+ query += fmt.Sprintf(" OFFSET %d", *v)
+ }
+
+ return util.FindMigrationHistoryList(ctx, query, params, driver.db)
+}
diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.go
new file mode 100644
index 0000000000..54b19826bc
--- /dev/null
+++ b/backend/plugin/db/risingwave/risingwave.go
@@ -0,0 +1,448 @@
+// Package risingwave is the plugin for RisingWave driver.
+package risingwave
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "net"
+ "regexp"
+ "strings"
+ "time"
+
+ // Import pg driver.
+ // init() in pgx/v4/stdlib will register it's pgx driver.
+ "github.com/jackc/pgx/v4"
+ "github.com/jackc/pgx/v4/stdlib"
+ "github.com/pkg/errors"
+ "go.uber.org/multierr"
+ "go.uber.org/zap"
+ "golang.org/x/crypto/ssh"
+ "google.golang.org/protobuf/types/known/durationpb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/util"
+ parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+)
+
+var (
+ // driverName is the driver name that our driver dependence register, now is "pgx".
+ driverName = "pgx"
+
+ _ db.Driver = (*Driver)(nil)
+)
+
+func init() {
+ db.Register(db.RisingWave, newDriver)
+}
+
+// Driver is the Postgres driver.
+type Driver struct {
+ dbBinDir string
+ config db.ConnectionConfig
+
+ db *sql.DB
+ sshClient *ssh.Client
+ // connectionString is the connection string registered by pgx.
+ // Unregister connectionString if we don't need it.
+ connectionString string
+ databaseName string
+}
+
+func newDriver(config db.DriverConfig) db.Driver {
+ return &Driver{
+ dbBinDir: config.DbBinDir,
+ }
+}
+
+// Open opens a RisingWave driver.
+func (driver *Driver) Open(_ context.Context, _ db.Type, config db.ConnectionConfig, _ db.ConnectionContext) (db.Driver, error) {
+ // Require username for Postgres, as the guessDSN 1st guess is to use the username as the connecting database
+ // if database name is not explicitly specified.
+ if config.Username == "" {
+ return nil, errors.Errorf("user must be set")
+ }
+
+ if config.Host == "" {
+ return nil, errors.Errorf("host must be set")
+ }
+
+ if config.Port == "" {
+ return nil, errors.Errorf("port must be set")
+ }
+
+ if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||
+ (config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {
+ return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")
+ }
+
+ connStr := fmt.Sprintf("host=%s port=%s", config.Host, config.Port)
+ connConfig, err := pgx.ParseConfig(connStr)
+ if err != nil {
+ return nil, err
+ }
+ connConfig.Config.User = config.Username
+ connConfig.Config.Password = config.Password
+ connConfig.Config.Database = config.Database
+ if config.TLSConfig.SslCert != "" {
+ cfg, err := config.TLSConfig.GetSslConfig()
+ if err != nil {
+ return nil, err
+ }
+ connConfig.TLSConfig = cfg
+ }
+ if config.SSHConfig.Host != "" {
+ sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if err != nil {
+ return nil, err
+ }
+ driver.sshClient = sshClient
+
+ connConfig.Config.DialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ conn, err := sshClient.Dial(network, addr)
+ if err != nil {
+ return nil, err
+ }
+ return &noDeadlineConn{Conn: conn}, nil
+ }
+ }
+ if config.ReadOnly {
+ connConfig.RuntimeParams["default_transaction_read_only"] = "true"
+ }
+
+ driver.databaseName = config.Database
+ if config.Database == "" {
+ databaseName, cfg, err := guessDSN(connConfig)
+ if err != nil {
+ return nil, err
+ }
+ connConfig = cfg
+ driver.databaseName = databaseName
+ }
+ driver.config = config
+
+ driver.connectionString = stdlib.RegisterConnConfig(connConfig)
+ db, err := sql.Open(driverName, driver.connectionString)
+ if err != nil {
+ return nil, err
+ }
+ driver.db = db
+ return driver, nil
+}
+
+type noDeadlineConn struct{ net.Conn }
+
+func (*noDeadlineConn) SetDeadline(time.Time) error { return nil }
+func (*noDeadlineConn) SetReadDeadline(time.Time) error { return nil }
+func (*noDeadlineConn) SetWriteDeadline(time.Time) error { return nil }
+
+// guessDSN will guess a valid DB connection and its database name.
+func guessDSN(baseConnConfig *pgx.ConnConfig) (string, *pgx.ConnConfig, error) {
+ // RisingWave creates the default `dev` database.
+ guesses := []string{"dev"}
+ for _, guessDatabase := range guesses {
+ connConfig := *baseConnConfig
+ connConfig.Database = guessDatabase
+ if err := func() error {
+ connectionString := stdlib.RegisterConnConfig(&connConfig)
+ defer stdlib.UnregisterConnConfig(connectionString)
+ db, err := sql.Open(driverName, connectionString)
+ if err != nil {
+ return err
+ }
+ defer db.Close()
+ return db.Ping()
+ }(); err != nil {
+ log.Debug("guessDSN attempt failed", zap.Error(err))
+ continue
+ }
+ return guessDatabase, &connConfig, nil
+ }
+ return "", nil, errors.Errorf("cannot connect to the instance, make sure the connection info is correct")
+}
+
+// Close closes the driver.
+func (driver *Driver) Close(context.Context) error {
+ stdlib.UnregisterConnConfig(driver.connectionString)
+ var err error
+ err = multierr.Append(err, driver.db.Close())
+ if driver.sshClient != nil {
+ err = multierr.Append(err, driver.sshClient.Close())
+ }
+ return err
+}
+
+// Ping pings the database.
+func (driver *Driver) Ping(ctx context.Context) error {
+ return driver.db.PingContext(ctx)
+}
+
+// GetType returns the database type.
+func (*Driver) GetType() db.Type {
+ return db.RisingWave
+}
+
+// GetDB gets the database.
+func (driver *Driver) GetDB() *sql.DB {
+ return driver.db
+}
+
+// getDatabases gets all databases of an instance.
+func (driver *Driver) getDatabases(ctx context.Context) ([]*storepb.DatabaseSchemaMetadata, error) {
+ var databases []*storepb.DatabaseSchemaMetadata
+ rows, err := driver.db.QueryContext(ctx, "SELECT datname, pg_encoding_to_char(encoding), datcollate FROM pg_database;")
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ database := &storepb.DatabaseSchemaMetadata{}
+ if err := rows.Scan(&database.Name, &database.CharacterSet, &database.Collation); err != nil {
+ return nil, err
+ }
+ databases = append(databases, database)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return databases, nil
+}
+
+// getVersion gets the version of Postgres server.
+func (driver *Driver) getVersion(ctx context.Context) (string, error) {
+ // Likes PostgreSQL 9.5-RisingWave-1.1.0 (f41ff20612323dc56f654939cfa3be9ca684b52f)
+ // We will return 1.1.0
+ regexp := regexp.MustCompile(`(?m)PostgreSQL (?P<PG_VERSION>.*)-RisingWave-(?P<RISINGWAVE_VERSION>\d+\.\d+\.\d+) \((?P<BUILD_SHA>.*)\)$`)
+ query := "SELECT version();"
+ var version string
+ if err := driver.db.QueryRowContext(ctx, query).Scan(&version); err != nil {
+ if err == sql.ErrNoRows {
+ return "", common.FormatDBErrorEmptyRowWithQuery(query)
+ }
+ return "", util.FormatErrorWithQuery(err, query)
+ }
+ matches := regexp.FindStringSubmatch(version)
+ if len(matches) != 4 {
+ return "", errors.Errorf("cannot parse version %q", version)
+ }
+ return matches[2], nil
+}
+
+// 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 (driver *Driver) Execute(ctx context.Context, statement string, createDatabase bool, _ db.ExecuteOptions) (int64, error) {
+ if createDatabase {
+ databases, err := driver.getDatabases(ctx)
+ if err != nil {
+ return 0, err
+ }
+ databaseName, err := getDatabaseInCreateDatabaseStatement(statement)
+ if err != nil {
+ return 0, err
+ }
+ exist := false
+ for _, database := range databases {
+ if database.Name == databaseName {
+ exist = true
+ break
+ }
+ }
+ if exist {
+ return 0, err
+ }
+
+ f := func(stmt string) error {
+ if _, err := driver.db.ExecContext(ctx, stmt); err != nil {
+ return err
+ }
+ return nil
+ }
+ if _, err := parser.SplitMultiSQLStream(parser.Postgres, strings.NewReader(statement), f); err != nil {
+ return 0, err
+ }
+ return 0, nil
+ }
+
+ var remainingStmts []string
+ var nonTransactionStmts []string
+ totalRowsAffected := int64(0)
+ f := func(stmt string) error {
+ // We don't use transaction for creating / altering databases in Postgres.
+ // We will execute the statement directly before "\\connect" statement.
+ // https://github.com/bytebase/bytebase/issues/202
+ if isSuperuserStatement(stmt) {
+ remainingStmts = append(remainingStmts, stmt)
+ } else if isNonTransactionStatement(stmt) {
+ nonTransactionStmts = append(nonTransactionStmts, stmt)
+ } else if !isIgnoredStatement(stmt) {
+ remainingStmts = append(remainingStmts, stmt)
+ }
+ return nil
+ }
+
+ if _, err := parser.SplitMultiSQLStream(parser.Postgres, strings.NewReader(statement), f); err != nil {
+ return 0, err
+ }
+
+ if len(remainingStmts) != 0 {
+ tx, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+
+ sqlResult, err := tx.ExecContext(ctx, strings.Join(remainingStmts, "\n"))
+ if err != nil {
+ return 0, err
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ rowsAffected, err := sqlResult.RowsAffected()
+ if err != nil {
+ // Since we cannot differentiate DDL and DML yet, we have to ignore the error.
+ log.Debug("rowsAffected returns error", zap.Error(err))
+ } else {
+ totalRowsAffected += rowsAffected
+ }
+ }
+
+ // Run non-transaction statements at the end.
+ for _, stmt := range nonTransactionStmts {
+ if _, err := driver.db.ExecContext(ctx, stmt); err != nil {
+ return 0, err
+ }
+ }
+ return totalRowsAffected, nil
+}
+
+func isSuperuserStatement(stmt string) bool {
+ upperCaseStmt := strings.ToUpper(stmt)
+ if strings.HasPrefix(upperCaseStmt, "GRANT") || strings.HasPrefix(upperCaseStmt, "CREATE EXTENSION") || strings.HasPrefix(upperCaseStmt, "CREATE EVENT TRIGGER") || strings.HasPrefix(upperCaseStmt, "COMMENT ON EVENT TRIGGER") {
+ return true
+ }
+ return false
+}
+
+func isIgnoredStatement(stmt string) bool {
+ // Extensions created in AWS Aurora PostgreSQL are owned by rdsadmin.
+ // We don't have privileges to comment on the extension and have to ignore it.
+ upperCaseStmt := strings.ToUpper(stmt)
+ return strings.HasPrefix(upperCaseStmt, "COMMENT ON EXTENSION")
+}
+
+func isNonTransactionStatement(stmt string) bool {
+ // CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
+ // CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON [ ONLY ] table_name [ USING method ] ...
+ createIndexReg := regexp.MustCompile(`(?i)CREATE(\s+(UNIQUE\s+)?)INDEX(\s+)CONCURRENTLY`)
+ if len(createIndexReg.FindString(stmt)) > 0 {
+ return true
+ }
+
+ // DROP INDEX CONCURRENTLY cannot run inside a transaction block.
+ // DROP INDEX [ CONCURRENTLY ] [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
+ dropIndexReg := regexp.MustCompile(`(?i)DROP(\s+)INDEX(\s+)CONCURRENTLY`)
+ return len(dropIndexReg.FindString(stmt)) > 0
+}
+
+func getDatabaseInCreateDatabaseStatement(createDatabaseStatement string) (string, error) {
+ raw := strings.TrimRight(createDatabaseStatement, ";")
+ raw = strings.TrimPrefix(raw, "CREATE DATABASE")
+ tokens := strings.Fields(raw)
+ if len(tokens) == 0 {
+ return "", errors.Errorf("database name not found")
+ }
+ databaseName := strings.TrimLeft(tokens[0], `"`)
+ databaseName = strings.TrimRight(databaseName, `"`)
+ return databaseName, nil
+}
+
+// GetCurrentDatabaseOwner gets the role of the current database.
+func (driver *Driver) GetCurrentDatabaseOwner() (string, error) {
+ const query = `
+ SELECT
+ u.rolname
+ FROM
+ pg_roles AS u JOIN pg_database AS d ON (d.datdba = u.oid)
+ WHERE
+ d.datname = current_database();
+ `
+ rows, err := driver.db.Query(query)
+ if err != nil {
+ return "", err
+ }
+ defer rows.Close()
+
+ var owner string
+ for rows.Next() {
+ var o string
+ if err := rows.Scan(&o); err != nil {
+ return "", err
+ }
+ owner = o
+ }
+ if err := rows.Err(); err != nil {
+ return "", err
+ }
+ if owner == "" {
+ return "", errors.Errorf("owner not found for the current database")
+ }
+ return owner, nil
+}
+
+// QueryConn queries a SQL statement in a given connection.
+func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string, queryContext *db.QueryContext) ([]*v1pb.QueryResult, error) {
+ singleSQLs, err := parser.SplitMultiSQL(parser.Postgres, statement)
+ if err != nil {
+ return nil, err
+ }
+ if len(singleSQLs) == 0 {
+ return nil, nil
+ }
+
+ var results []*v1pb.QueryResult
+ for _, singleSQL := range singleSQLs {
+ result, err := driver.querySingleSQL(ctx, conn, singleSQL, queryContext)
+ if err != nil {
+ results = append(results, &v1pb.QueryResult{
+ Error: err.Error(),
+ })
+ } else {
+ results = append(results, result)
+ }
+ }
+
+ return results, nil
+}
+
+func getStatementWithResultLimit(stmt string, limit int) string {
+ return fmt.Sprintf("WITH result AS (%s) SELECT * FROM result LIMIT %d;", stmt, limit)
+}
+
+func (*Driver) querySingleSQL(ctx context.Context, conn *sql.Conn, singleSQL parser.SingleSQL, queryContext *db.QueryContext) (*v1pb.QueryResult, error) {
+ statement := strings.TrimRight(singleSQL.Text, " \n\t;")
+
+ stmt := statement
+ if !strings.HasPrefix(stmt, "EXPLAIN") && queryContext.Limit > 0 {
+ stmt = getStatementWithResultLimit(stmt, queryContext.Limit)
+ }
+
+ startTime := time.Now()
+ result, err := util.Query(ctx, db.Postgres, conn, stmt, queryContext)
+ if err != nil {
+ return nil, err
+ }
+ result.Latency = durationpb.New(time.Since(startTime))
+ result.Statement = statement
+ return result, nil
+}
+
+// RunStatement runs a SQL statement in a given connection.
+func (*Driver) RunStatement(ctx context.Context, conn *sql.Conn, statement string) ([]*v1pb.QueryResult, error) {
+ return util.RunStatement(ctx, parser.Postgres, conn, statement)
+}
diff --git a/backend/plugin/db/risingwave/risingwave_test.go b/backend/plugin/db/risingwave/risingwave_test.go
new file mode 100644
index 0000000000..284f4bc8bd
--- /dev/null
+++ b/backend/plugin/db/risingwave/risingwave_test.go
@@ -0,0 +1,51 @@
+package risingwave
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetDatabaseInCreateDatabaseStatement(t *testing.T) {
+ tests := []struct {
+ createDatabaseStatement string
+ want string
+ wantErr bool
+ }{
+ {
+ `CREATE DATABASE "hello" ENCODING "UTF8";`,
+ "hello",
+ false,
+ },
+ {
+ `CREATE DATABASE "hello";`,
+ "hello",
+ false,
+ },
+ {
+ `CREATE DATABASE hello;`,
+ "hello",
+ false,
+ },
+ {
+ `CREATE DATABASE hello ENCODING "UTF8";`,
+ "hello",
+ false,
+ },
+ {
+ `CREATE DATABASE;`,
+ "",
+ true,
+ },
+ }
+
+ for _, test := range tests {
+ got, err := getDatabaseInCreateDatabaseStatement(test.createDatabaseStatement)
+ if test.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ require.Equal(t, test.want, got)
+ }
+}
diff --git a/backend/plugin/db/risingwave/role.go b/backend/plugin/db/risingwave/role.go
new file mode 100644
index 0000000000..46a1920ad4
--- /dev/null
+++ b/backend/plugin/db/risingwave/role.go
@@ -0,0 +1,401 @@
+package risingwave
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/util"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+// RoleAttribute is the attribute string for role.
+type RoleAttribute string
+
+const (
+ // SUPERUSER is the role attribute for rolsuper.
+ SUPERUSER RoleAttribute = "SUPERUSER"
+ // NOSUPERUSER is the role attribute for rolsuper.
+ NOSUPERUSER RoleAttribute = "NOSUPERUSER"
+ // LOGIN is the role attribute for rolcanlogin.
+ LOGIN RoleAttribute = "LOGIN"
+ // NOLOGIN is the role attribute for rolcanlogin.
+ NOLOGIN RoleAttribute = "NOLOGIN"
+ // INHERIT is the role attribute for rolinherit.
+ INHERIT RoleAttribute = "INHERIT"
+ // NOINHERIT is the role attribute for rolinherit.
+ NOINHERIT RoleAttribute = "NOINHERIT"
+ // CREATEDB is the role attribute for rolcreatedb.
+ CREATEDB RoleAttribute = "CREATEDB"
+ // NOCREATEDB is the role attribute for rolcreatedb.
+ NOCREATEDB RoleAttribute = "NOCREATEDB"
+ // CREATEROLE is the role attribute for rolcreaterole.
+ CREATEROLE RoleAttribute = "CREATEROLE"
+ // NOCREATEROLE is the role attribute for rolcreaterole.
+ NOCREATEROLE RoleAttribute = "NOCREATEROLE"
+ // REPLICATION is the role attribute for rolreplication.
+ REPLICATION RoleAttribute = "REPLICATION"
+ // NOREPLICATION is the role attribute for rolreplication.
+ NOREPLICATION RoleAttribute = "NOREPLICATION"
+ // BYPASSRLS is the role attribute for rolbypassrls.
+ BYPASSRLS RoleAttribute = "BYPASSRLS"
+ // NOBYPASSRLS is the role attribute for rolbypassrls.
+ NOBYPASSRLS RoleAttribute = "NOBYPASSRLS"
+)
+
+// ToString returns the string value for role attribute.
+func (a RoleAttribute) ToString() string {
+ return string(a)
+}
+
+type roleFind struct {
+ Name *string
+}
+
+// CreateRole will create the PG role.
+func (driver *Driver) CreateRole(ctx context.Context, upsert *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {
+ txn, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer txn.Rollback()
+
+ if err := createRoleImpl(ctx, txn, upsert); err != nil {
+ return nil, err
+ }
+
+ roles, err := findRoleImpl(ctx, txn, &roleFind{
+ Name: &upsert.Name,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(roles) == 0 {
+ return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", upsert.Name))
+ }
+
+ if err := txn.Commit(); err != nil {
+ return nil, err
+ }
+
+ return roles[0], nil
+}
+
+// UpdateRole will alter the PG role.
+func (driver *Driver) UpdateRole(ctx context.Context, roleName string, upsert *db.DatabaseRoleUpsertMessage) (*db.DatabaseRoleMessage, error) {
+ txn, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer txn.Rollback()
+
+ if err := alterRoleImpl(ctx, txn, roleName, upsert); err != nil {
+ return nil, err
+ }
+
+ roles, err := findRoleImpl(ctx, txn, &roleFind{
+ Name: &upsert.Name,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(roles) == 0 {
+ return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", upsert.Name))
+ }
+
+ if err := txn.Commit(); err != nil {
+ return nil, err
+ }
+
+ return roles[0], nil
+}
+
+// FindRole will find the PG role by name.
+func (driver *Driver) FindRole(ctx context.Context, roleName string) (*db.DatabaseRoleMessage, error) {
+ txn, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer txn.Rollback()
+
+ roles, err := findRoleImpl(ctx, txn, &roleFind{
+ Name: &roleName,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(roles) == 0 {
+ return nil, common.Errorf(common.NotFound, fmt.Sprintf("cannot find the role %s", roleName))
+ }
+
+ if err := txn.Commit(); err != nil {
+ return nil, err
+ }
+
+ return roles[0], nil
+}
+
+// ListRole lists the role.
+func (driver *Driver) ListRole(ctx context.Context) ([]*db.DatabaseRoleMessage, error) {
+ txn, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer txn.Rollback()
+
+ roles, err := findRoleImpl(ctx, txn, &roleFind{})
+ if err != nil {
+ return nil, err
+ }
+
+ if err := txn.Commit(); err != nil {
+ return nil, err
+ }
+
+ return roles, nil
+}
+
+// DeleteRole will drop the PG role by name.
+func (driver *Driver) DeleteRole(ctx context.Context, roleName string) error {
+ statement := fmt.Sprintf(`DROP ROLE IF EXISTS "%s"`, roleName)
+ if _, err := driver.db.ExecContext(ctx, statement); err != nil {
+ return util.FormatErrorWithQuery(err, statement)
+ }
+
+ return nil
+}
+
+func findRoleImpl(ctx context.Context, txn *sql.Tx, find *roleFind) ([]*db.DatabaseRoleMessage, error) {
+ where := []string{}
+ if v := find.Name; v != nil {
+ where = append(where, fmt.Sprintf("r.rolname = '%s'", *v))
+ }
+ if len(where) == 0 {
+ where = append(where, "r.rolname !~ '^pg_'")
+ }
+
+ statement := fmt.Sprintf(`
+ SELECT
+ r.rolname,
+ r.rolsuper,
+ r.rolinherit,
+ r.rolcreaterole,
+ r.rolcreatedb,
+ r.rolcanlogin,
+ r.rolreplication,
+ r.rolbypassrls,
+ r.rolvaliduntil,
+ r.rolconnlimit
+ FROM pg_catalog.pg_roles r
+ WHERE %s;
+ `, strings.Join(where, " AND "))
+
+ rows, err := txn.QueryContext(ctx, statement)
+ if err != nil {
+ return nil, util.FormatErrorWithQuery(err, statement)
+ }
+ defer rows.Close()
+
+ var roleList []*db.DatabaseRoleMessage
+
+ for rows.Next() {
+ var name string
+ var super, inherit, createRole, createDB, canLogin, replication, bypassRLS bool
+ var validUntil sql.NullString
+ var connectionLimit int32
+ if err := rows.Scan(
+ &name,
+ &super,
+ &inherit,
+ &createRole,
+ &createDB,
+ &canLogin,
+ &replication,
+ &bypassRLS,
+ &validUntil,
+ &connectionLimit,
+ ); err != nil {
+ return nil, util.FormatErrorWithQuery(err, statement)
+ }
+
+ var attributes []string
+ if super {
+ attributes = append(attributes, SUPERUSER.ToString())
+ } else {
+ attributes = append(attributes, NOSUPERUSER.ToString())
+ }
+ if inherit {
+ attributes = append(attributes, INHERIT.ToString())
+ } else {
+ attributes = append(attributes, NOINHERIT.ToString())
+ }
+ if createRole {
+ attributes = append(attributes, CREATEROLE.ToString())
+ } else {
+ attributes = append(attributes, NOCREATEROLE.ToString())
+ }
+ if createDB {
+ attributes = append(attributes, CREATEDB.ToString())
+ } else {
+ attributes = append(attributes, NOCREATEDB.ToString())
+ }
+ if canLogin {
+ attributes = append(attributes, LOGIN.ToString())
+ } else {
+ attributes = append(attributes, NOLOGIN.ToString())
+ }
+ if replication {
+ attributes = append(attributes, REPLICATION.ToString())
+ } else {
+ attributes = append(attributes, NOREPLICATION.ToString())
+ }
+ if bypassRLS {
+ attributes = append(attributes, BYPASSRLS.ToString())
+ } else {
+ attributes = append(attributes, NOBYPASSRLS.ToString())
+ }
+
+ attribute := strings.Join(attributes, " ")
+ role := &db.DatabaseRoleMessage{
+ Name: name,
+ ConnectionLimit: connectionLimit,
+ Attribute: &attribute,
+ }
+
+ if validUntil.Valid {
+ role.ValidUntil = &validUntil.String
+ }
+
+ roleList = append(roleList, role)
+ }
+
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return roleList, nil
+}
+
+func createRoleImpl(ctx context.Context, txn *sql.Tx, upsert *db.DatabaseRoleUpsertMessage) error {
+ statement := fmt.Sprintf(`CREATE ROLE "%s" %s;`, upsert.Name, convertToAttributeStatement(upsert))
+ if _, err := txn.ExecContext(ctx, statement); err != nil {
+ return util.FormatErrorWithQuery(err, statement)
+ }
+
+ return nil
+}
+
+func alterRoleImpl(ctx context.Context, txn *sql.Tx, roleName string, upsert *db.DatabaseRoleUpsertMessage) error {
+ if roleName != upsert.Name {
+ renameStatement := fmt.Sprintf(`ALTER ROLE "%s" RENAME TO "%s";`, roleName, upsert.Name)
+ if _, err := txn.ExecContext(ctx, renameStatement); err != nil {
+ return util.FormatErrorWithQuery(err, renameStatement)
+ }
+ }
+
+ attributeStatement := convertToAttributeStatement(upsert)
+ if attributeStatement == "" {
+ return nil
+ }
+
+ statement := fmt.Sprintf(`ALTER ROLE "%s" %s;`, upsert.Name, attributeStatement)
+ if _, err := txn.ExecContext(ctx, statement); err != nil {
+ return util.FormatErrorWithQuery(err, statement)
+ }
+
+ return nil
+}
+
+func convertToAttributeStatement(r *db.DatabaseRoleUpsertMessage) string {
+ attributeList := []string{}
+
+ if r.Attribute != nil {
+ attributeList = append(attributeList, *r.Attribute)
+ }
+
+ if v := r.Password; v != nil {
+ attributeList = append(attributeList, fmt.Sprintf("ENCRYPTED PASSWORD '%s'", *v))
+ }
+ if v := r.ValidUntil; v != nil {
+ attributeList = append(attributeList, fmt.Sprintf("VALID UNTIL '%s'", *v))
+ }
+ if v := r.ConnectionLimit; v != nil {
+ attributeList = append(attributeList, fmt.Sprintf("CONNECTION LIMIT %d", *v))
+ }
+
+ attribute := ""
+ if len(attributeList) > 0 {
+ attribute = fmt.Sprintf("WITH %s", strings.Join(attributeList, " "))
+ }
+
+ return attribute
+}
+
+func (driver *Driver) getInstanceRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata, error) {
+ query := `
+ SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolreplication, r.rolvaliduntil, r.rolbypassrls
+ FROM pg_catalog.pg_roles r
+ WHERE r.rolname !~ '^pg_';
+ `
+ var instanceRoles []*storepb.InstanceRoleMetadata
+ rows, err := driver.db.QueryContext(ctx, query)
+ if err != nil {
+ return nil, util.FormatErrorWithQuery(err, query)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var role string
+ var super, inherit, createRole, createDB, canLogin, replication, bypassRLS bool
+ var rolValidUntil sql.NullString
+ if err := rows.Scan(
+ &role,
+ &super,
+ &inherit,
+ &createRole,
+ &createDB,
+ &canLogin,
+ &replication,
+ &rolValidUntil,
+ &bypassRLS,
+ ); err != nil {
+ return nil, err
+ }
+
+ var attributes []string
+ if super {
+ attributes = append(attributes, "Superuser")
+ }
+ if !inherit {
+ attributes = append(attributes, "No inheritance")
+ }
+ if createRole {
+ attributes = append(attributes, "Create role")
+ }
+ if createDB {
+ attributes = append(attributes, "Create DB")
+ }
+ if !canLogin {
+ attributes = append(attributes, "Cannot login")
+ }
+ if replication {
+ attributes = append(attributes, "Replication")
+ }
+ if rolValidUntil.Valid {
+ attributes = append(attributes, fmt.Sprintf("Password valid until %s", rolValidUntil.String))
+ }
+ if bypassRLS {
+ attributes = append(attributes, "Bypass RLS+")
+ }
+
+ instanceRoles = append(instanceRoles, &storepb.InstanceRoleMetadata{
+ Name: role,
+ Grant: strings.Join(attributes, ", "),
+ })
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return instanceRoles, nil
+}
diff --git a/backend/plugin/db/risingwave/sync.go b/backend/plugin/db/risingwave/sync.go
new file mode 100644
index 0000000000..dece7a5616
--- /dev/null
+++ b/backend/plugin/db/risingwave/sync.go
@@ -0,0 +1,448 @@
+package risingwave
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "regexp"
+ "sort"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/types/known/wrapperspb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/util"
+ parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"
+ "github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+const systemSchemas = "'rw_catalog', 'information_schema', 'pg_catalog'"
+
+// SyncInstance syncs the instance.
+func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error) {
+ version, err := driver.getVersion(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ instanceRoles, err := driver.getInstanceRoles(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // Query db info
+ databases, err := driver.getDatabases(ctx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get databases")
+ }
+
+ return &db.InstanceMetadata{
+ Version: version,
+ InstanceRoles: instanceRoles,
+ Databases: databases,
+ }, nil
+}
+
+// SyncDBSchema syncs a single database schema.
+func (driver *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchemaMetadata, error) {
+ // Query db info
+ databases, err := driver.getDatabases(ctx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get databases")
+ }
+
+ var databaseMetadata *storepb.DatabaseSchemaMetadata
+ for _, database := range databases {
+ if database.Name == driver.databaseName {
+ databaseMetadata = database
+ break
+ }
+ }
+ if databaseMetadata == nil {
+ return nil, common.Errorf(common.NotFound, "database %q not found", driver.databaseName)
+ }
+
+ txn, err := driver.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer txn.Rollback()
+
+ schemaList, err := getSchemas(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get schemas from database %q", driver.databaseName)
+ }
+ tableMap, err := getTables(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get tables from database %q", driver.databaseName)
+ }
+ viewMap, err := getViews(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get views from database %q", driver.databaseName)
+ }
+ functionMap, err := getFunctions(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get functions from database %q", driver.databaseName)
+ }
+
+ if err := txn.Commit(); err != nil {
+ return nil, err
+ }
+
+ schemaNameMap := make(map[string]bool)
+ for _, schemaName := range schemaList {
+ schemaNameMap[schemaName] = true
+ }
+ for schemaName := range tableMap {
+ schemaNameMap[schemaName] = true
+ }
+ for schemaName := range viewMap {
+ schemaNameMap[schemaName] = true
+ }
+ var schemaNames []string
+ for schemaName := range schemaNameMap {
+ schemaNames = append(schemaNames, schemaName)
+ }
+ sort.Strings(schemaNames)
+ for _, schemaName := range schemaNames {
+ var tables []*storepb.TableMetadata
+ var views []*storepb.ViewMetadata
+ var functions []*storepb.FunctionMetadata
+ var exists bool
+ if tables, exists = tableMap[schemaName]; !exists {
+ tables = []*storepb.TableMetadata{}
+ }
+ if views, exists = viewMap[schemaName]; !exists {
+ views = []*storepb.ViewMetadata{}
+ }
+ if functions, exists = functionMap[schemaName]; !exists {
+ functions = []*storepb.FunctionMetadata{}
+ }
+ databaseMetadata.Schemas = append(databaseMetadata.Schemas, &storepb.SchemaMetadata{
+ Name: schemaName,
+ Tables: tables,
+ Views: views,
+ Functions: functions,
+ })
+ }
+ // No extensions in RisingWave.
+ databaseMetadata.Extensions = make([]*storepb.ExtensionMetadata, 0)
+
+ return databaseMetadata, err
+}
+
+var listSchemaQuery = fmt.Sprintf(`
+SELECT nspname
+FROM pg_catalog.pg_namespace
+WHERE nspname NOT IN (%s);
+`, systemSchemas)
+
+func getSchemas(txn *sql.Tx) ([]string, error) {
+ rows, err := txn.Query(listSchemaQuery)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []string
+ for rows.Next() {
+ var schemaName string
+ if err := rows.Scan(&schemaName); err != nil {
+ return nil, err
+ }
+ result = append(result, schemaName)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return result, nil
+}
+
+var listTableQuery = `
+SELECT
+ T.name as table_name,
+ S.name AS schema_name
+FROM rw_catalog.rw_tables AS T
+ JOIN rw_catalog.rw_schemas AS S
+ ON T.schema_id = S.id;`
+
+// getTables gets all tables of a database.
+func getTables(txn *sql.Tx) (map[string][]*storepb.TableMetadata, error) {
+ columnMap, err := getTableColumns(txn)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get table columns")
+ }
+ indexMap, err := getIndexes(txn)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get indices")
+ }
+
+ tableMap := make(map[string][]*storepb.TableMetadata)
+ rows, err := txn.Query(listTableQuery)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ table := &storepb.TableMetadata{}
+ // var tbl tableSchema
+ var schemaName string
+ if err := rows.Scan(&table.Name, &schemaName); err != nil {
+ return nil, err
+ }
+ // TODO: get table statistics of RisingWave later.
+ table.DataSize = 0
+ table.IndexSize = 0
+ table.RowCount = 0
+ // Comment is not supported in RisingWave.
+ table.Comment = ""
+ key := db.TableKey{Schema: schemaName, Table: table.Name}
+ table.Columns = columnMap[key]
+ table.Indexes = indexMap[key]
+ // No foreign keys in RisingWave.
+ table.ForeignKeys = make([]*storepb.ForeignKeyMetadata, 0)
+
+ tableMap[schemaName] = append(tableMap[schemaName], table)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return tableMap, nil
+}
+
+var listColumnQuery = `
+SELECT
+ cols.table_schema,
+ cols.table_name,
+ cols.column_name,
+ cols.data_type,
+ cols.ordinal_position,
+ cols.column_default,
+ cols.is_nullable,
+ cols.collation_name,
+ cols.udt_schema,
+ cols.udt_name
+FROM INFORMATION_SCHEMA.COLUMNS AS cols` + fmt.Sprintf(`
+WHERE cols.table_schema NOT IN (%s)
+ORDER BY cols.table_schema, cols.table_name, cols.ordinal_position;`, systemSchemas)
+
+// getTableColumns gets the columns of a table.
+func getTableColumns(txn *sql.Tx) (map[db.TableKey][]*storepb.ColumnMetadata, error) {
+ columnsMap := make(map[db.TableKey][]*storepb.ColumnMetadata)
+ rows, err := txn.Query(listColumnQuery)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ column := &storepb.ColumnMetadata{}
+ var schemaName, tableName, nullable string
+ var defaultStr, collation, udtSchema, udtName sql.NullString
+ if err := rows.Scan(&schemaName, &tableName, &column.Name, &column.Type, &column.Position, &defaultStr, &nullable, &collation, &udtSchema, &udtName); err != nil {
+ return nil, err
+ }
+ if defaultStr.Valid {
+ column.Default = &wrapperspb.StringValue{Value: defaultStr.String}
+ }
+ isNullBool, err := util.ConvertYesNo(nullable)
+ if err != nil {
+ return nil, err
+ }
+ column.Nullable = isNullBool
+ switch column.Type {
+ case "USER-DEFINED":
+ column.Type = fmt.Sprintf("%s.%s", udtSchema.String, udtName.String)
+ case "ARRAY":
+ column.Type = udtName.String
+ }
+ column.Collation = collation.String
+ column.Comment = ""
+
+ key := db.TableKey{Schema: schemaName, Table: tableName}
+ columnsMap[key] = append(columnsMap[key], column)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return columnsMap, nil
+}
+
+var listViewQuery = `
+WITH all_views AS (
+ SELECT
+ schema_id,
+ name,
+ definition
+ FROM
+ rw_materialized_views
+ UNION
+ ALL
+ SELECT
+ schema_id,
+ name,
+ definition
+ FROM
+ rw_views
+)
+SELECT
+ S.name AS schema_name,
+ all_views.name AS view_name,
+ definition
+FROM
+ all_views
+ JOIN rw_schemas S ON all_views.schema_id = S.id
+ AND S.name NOT IN ` + fmt.Sprintf("(%s)", systemSchemas)
+
+// getViews gets all views of a database.
+func getViews(txn *sql.Tx) (map[string][]*storepb.ViewMetadata, error) {
+ viewMap := make(map[string][]*storepb.ViewMetadata)
+
+ rows, err := txn.Query(listViewQuery)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ view := &storepb.ViewMetadata{}
+ var schemaName string
+ var def sql.NullString
+ if err := rows.Scan(&schemaName, &view.Name, &def); err != nil {
+ return nil, err
+ }
+ // Return error on NULL view definition.
+ // https://github.com/bytebase/bytebase/issues/343
+ if !def.Valid {
+ return nil, errors.Errorf("schema %q view %q has empty definition; please check whether proper privileges have been granted to Bytebase", schemaName, view.Name)
+ }
+ view.Definition = def.String
+ view.Comment = ""
+
+ viewMap[schemaName] = append(viewMap[schemaName], view)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ // TODO: RisingWave doesn't support view dependencies analyze yet.
+
+ return viewMap, nil
+}
+
+var listIndexQuery = `
+SELECT
+ I.name AS idx_name,
+ T.name AS table_name,
+ S.name AS schema_name,
+ I.definition
+FROM rw_indexes AS I
+ JOIN rw_tables AS T
+ ON I.primary_table_id = T.id
+ JOIN rw_schemas AS S
+ ON I.schema_id = S.id;
+`
+
+// getIndexes gets all indices of a database.
+func getIndexes(txn *sql.Tx) (map[db.TableKey][]*storepb.IndexMetadata, error) {
+ indexMap := make(map[db.TableKey][]*storepb.IndexMetadata)
+
+ rows, err := txn.Query(listIndexQuery)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ index := &storepb.IndexMetadata{}
+ var schemaName, tableName, statement string
+ if err := rows.Scan(&index.Name, &tableName, &schemaName, &statement); err != nil {
+ return nil, err
+ }
+
+ nodes, err := parser.Parse(parser.Postgres, parser.ParseContext{}, statement)
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) != 1 {
+ return nil, errors.Errorf("invalid number of statements %v, expecting one", len(nodes))
+ }
+ node, ok := nodes[0].(*ast.CreateIndexStmt)
+ if !ok {
+ return nil, errors.Errorf("statement %q is not index statement", statement)
+ }
+
+ index.Type = getIndexMethodType(statement)
+ index.Unique = node.Index.Unique
+ index.Expressions = node.Index.GetKeyNameList()
+ // No primary key index in RisingWave.
+ index.Primary = false
+ // Comment is unsupported in RisingWave in v1.0.
+ index.Comment = ""
+
+ key := db.TableKey{Schema: schemaName, Table: tableName}
+ indexMap[key] = append(indexMap[key], index)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return indexMap, nil
+}
+
+func getIndexMethodType(stmt string) string {
+ re := regexp.MustCompile(`USING (\w+) `)
+ matches := re.FindStringSubmatch(stmt)
+ if len(matches) == 0 {
+ return ""
+ }
+ return matches[1]
+}
+
+var listFunctionQuery = `SELECT
+ F.name AS function_name,
+ S.name AS schema_name
+FROM rw_catalog.rw_functions AS F
+ JOIN rw_schemas AS S
+ ON F.schema_id = S.id;`
+
+// getFunctions gets all functions of a database.
+func getFunctions(txn *sql.Tx) (map[string][]*storepb.FunctionMetadata, error) {
+ functionMap := make(map[string][]*storepb.FunctionMetadata)
+
+ rows, err := txn.Query(listFunctionQuery)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ function := &storepb.FunctionMetadata{}
+ var schemaName string
+ if err := rows.Scan(&function.Name, &schemaName); err != nil {
+ return nil, err
+ }
+ // Omit the definition.
+ function.Definition = "..."
+
+ functionMap[schemaName] = append(functionMap[schemaName], function)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return functionMap, nil
+}
+
+// SyncSlowQuery syncs the slow query.
+func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]*storepb.SlowQueryStatistics, error) {
+ return nil, errors.Errorf("not implemented")
+}
+
+// CheckSlowQueryLogEnabled checks if slow query log is enabled.
+func (*Driver) CheckSlowQueryLogEnabled(_ context.Context) error {
+ return errors.Errorf("not implemented")
+}
diff --git a/backend/plugin/db/util/mask_sensitive_data.go b/backend/plugin/db/util/mask_sensitive_data.go
index 3fc8b5613f..f51feaf85f 100644
--- a/backend/plugin/db/util/mask_sensitive_data.go
+++ b/backend/plugin/db/util/mask_sensitive_data.go
@@ -45,7 +45,7 @@ func extractSensitiveField(dbType db.Type, statement string, currentDatabase str
schemaInfo: schemaInfo,
}
return extractor.extractMySQLSensitiveField(statement)
- case db.Postgres, db.Redshift:
+ case db.Postgres, db.Redshift, db.RisingWave:
extractor := &sensitiveFieldExtractor{
schemaInfo: schemaInfo,
}
@@ -53,7 +53,7 @@ func extractSensitiveField(dbType db.Type, statement string, currentDatabase str
if err != nil {
tableNotFound := regexp.MustCompile("^Table \"(.*)\\.(.*)\" not found$")
content := tableNotFound.FindStringSubmatch(err.Error())
- if len(content) == 3 && isPostgreSQLSystemSchema(content[1]) {
+ if len(content) == 3 && (isPostgreSQLSystemSchema(content[1]) || dbType == db.RisingWave && isRisingWaveSystemSchema(content[1])) {
// skip for system schema
return nil, nil
}
@@ -91,6 +91,14 @@ func isPostgreSQLSystemSchema(schema string) bool {
return false
}
+func isRisingWaveSystemSchema(schema string) bool {
+ switch schema {
+ case "information_schema", "pg_catalog", "rw_catalog":
+ return true
+ }
+ return false
+}
+
func (extractor *sensitiveFieldExtractor) extractPostgreSQLSensitiveField(statement string) ([]db.SensitiveField, error) {
res, err := pgquery.Parse(statement)
if err != nil {
diff --git a/backend/plugin/parser/sql/parser.go b/backend/plugin/parser/sql/parser.go
index 602e0ecd95..0d27de4fea 100644
--- a/backend/plugin/parser/sql/parser.go
+++ b/backend/plugin/parser/sql/parser.go
@@ -36,6 +36,8 @@ const (
Snowflake EngineType = "SNOWFLAKE"
// SQLServer is the engine type for SQLServer.
SQLServer EngineType = "SQLSERVER"
+ // RisingWave is the engine type for RisingWave.
+ RisingWave EngineType = "RISINGWAVE"
// DeparseIndentString is the string for each indent level.
DeparseIndentString = " "
)
diff --git a/backend/plugin/parser/sql/utils.go b/backend/plugin/parser/sql/utils.go
index bb567ca49f..ed7594a508 100644
--- a/backend/plugin/parser/sql/utils.go
+++ b/backend/plugin/parser/sql/utils.go
@@ -88,7 +88,7 @@ func ExtractResourceList(engineType EngineType, currentDatabase string, currentS
case Oracle:
// The resource list for Oracle may contains table, view and temporary table.
return extractOracleResourceList(currentDatabase, currentSchema, sql)
- case Postgres:
+ case Postgres, RisingWave:
// The resource list for Postgres may contains table, view and temporary table.
return extractPostgresResourceList(currentDatabase, "public", sql)
case Snowflake:
@@ -438,7 +438,7 @@ func SplitMultiSQL(engineType EngineType, statement string) ([]SingleSQL, error)
case MSSQL:
t := newTokenizer(statement)
list, err = t.splitStandardMultiSQL()
- case Postgres, Redshift:
+ case Postgres, Redshift, RisingWave:
t := newTokenizer(statement)
list, err = t.splitPostgreSQLMultiSQL()
case MySQL, MariaDB, OceanBase:
@@ -602,7 +602,7 @@ func SplitMultiSQLStream(engineType EngineType, src io.Reader, f func(string) er
case MSSQL:
t := newStreamTokenizer(src, f)
list, err = t.splitStandardMultiSQL()
- case Postgres, Redshift:
+ case Postgres, Redshift, RisingWave:
t := newStreamTokenizer(src, f)
list, err = t.splitPostgreSQLMultiSQL()
case MySQL, MariaDB, OceanBase:
diff --git a/backend/plugin/parser/sql/validate_sql_for_editor.go b/backend/plugin/parser/sql/validate_sql_for_editor.go
index d9995dfca5..207701db9b 100644
--- a/backend/plugin/parser/sql/validate_sql_for_editor.go
+++ b/backend/plugin/parser/sql/validate_sql_for_editor.go
@@ -21,7 +21,7 @@ import (
// We also support CTE with SELECT statements, but not with DML statements.
func ValidateSQLForEditor(engine EngineType, statement string) bool {
switch engine {
- case Postgres, Redshift:
+ case Postgres, Redshift, RisingWave:
return postgresValidateSQLForEditor(statement)
case MySQL, TiDB, MariaDB, OceanBase:
return mysqlValidateSQLForEditor(statement)
@@ -164,7 +164,7 @@ func checkStatementWithoutQuotedTextAndComment(statement string) bool {
func removeQuotedTextAndComment(engine EngineType, statement string) (string, error) {
switch engine {
- case Postgres:
+ case Postgres, RisingWave:
return "", errors.Errorf("unsupported engine type: %s", engine)
case MySQL, TiDB, MariaDB, OceanBase:
return mysqlRemoveQuotedTextAndComment(statement)
diff --git a/backend/runner/taskcheck/statement_type_executor.go b/backend/runner/taskcheck/statement_type_executor.go
index 9a0f5ff36f..c9441d2498 100644
--- a/backend/runner/taskcheck/statement_type_executor.go
+++ b/backend/runner/taskcheck/statement_type_executor.go
@@ -82,7 +82,7 @@ func (exec *StatementTypeExecutor) Run(ctx context.Context, _ *store.TaskCheckRu
renderedStatement := backendutils.RenderStatement(statement, materials)
switch instance.Engine {
- case db.Postgres:
+ case db.Postgres, db.RisingWave:
result, err = postgresqlStatementTypeCheck(renderedStatement, task.Type)
if err != nil {
return nil, err
diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.go
index 42e4f07b58..c83a104fd1 100644
--- a/backend/runner/taskrun/database_create_executor.go
+++ b/backend/runner/taskrun/database_create_executor.go
@@ -291,7 +291,7 @@ func getConnectionStatement(dbType db.Type, databaseName string) (string, error)
return fmt.Sprintf("USE `%s`;\n", databaseName), nil
case db.MSSQL:
return fmt.Sprintf(`USE "%s";\n`, databaseName), nil
- case db.Postgres:
+ case db.Postgres, db.RisingWave:
return fmt.Sprintf("\\connect \"%s\";\n", databaseName), nil
case db.ClickHouse:
return fmt.Sprintf("USE `%s`;\n", databaseName), nil
diff --git a/backend/runner/utils/sdl_utils.go b/backend/runner/utils/sdl_utils.go
index ab93c4bac9..715d4ff5ec 100644
--- a/backend/runner/utils/sdl_utils.go
+++ b/backend/runner/utils/sdl_utils.go
@@ -36,7 +36,7 @@ func ComputeDatabaseSchemaDiff(ctx context.Context, instance *store.InstanceMess
var engine parser.EngineType
switch instance.Engine {
- case db.Postgres:
+ case db.Postgres, db.RisingWave:
engine = parser.Postgres
case db.MySQL, db.TiDB, db.MariaDB, db.OceanBase:
engine = parser.MySQL
diff --git a/backend/server/issue.go b/backend/server/issue.go
index 6263ff628d..48165a8d93 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -1774,6 +1774,8 @@ func getCreateDatabaseStatement(dbType db.Type, createDatabaseContext api.Create
stmt = fmt.Sprintf("%s WITH\n\t%s", stmt, strings.Join(list, "\n\t"))
}
return fmt.Sprintf("%s;", stmt), nil
+ case db.RisingWave:
+ return fmt.Sprintf("CREATE DATABASE %s;", databaseName), nil
}
return "", errors.Errorf("unsupported database type %s", dbType)
}
@@ -1859,6 +1861,13 @@ func checkCharacterSetCollationOwner(dbType db.Type, characterSet, collation, ow
if owner == "" {
return errors.Errorf("database owner is required for Redshift")
}
+ case db.RisingWave:
+ if characterSet != "" {
+ return errors.Errorf("RisingWave does not support character set, but got %s", characterSet)
+ }
+ if collation != "" {
+ return errors.Errorf("RisingWave does not support collation, but got %s", collation)
+ }
case db.SQLite, db.MongoDB, db.MSSQL:
// no-op.
default:
diff --git a/backend/server/server.go b/backend/server/server.go
index ad0e3507a8..6247549612 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -111,6 +111,8 @@ import (
_ "github.com/bytebase/bytebase/backend/plugin/db/clickhouse"
// Register dm driver.
_ "github.com/bytebase/bytebase/backend/plugin/db/dm"
+ // Register risingwave driver.
+ _ "github.com/bytebase/bytebase/backend/plugin/db/risingwave"
// Register fake advisor.
_ "github.com/bytebase/bytebase/backend/plugin/advisor/fake"
diff --git a/frontend/src/assets/db-risingwave.png b/frontend/src/assets/db-risingwave.png
new file mode 100644
index 0000000000..efe6d87df4
Binary files /dev/null and b/frontend/src/assets/db-risingwave.png differ
diff --git a/frontend/src/components/ColumnTable.vue b/frontend/src/components/ColumnTable.vue
index df8fc2d219..b670bdafea 100644
--- a/frontend/src/components/ColumnTable.vue
+++ b/frontend/src/components/ColumnTable.vue
@@ -166,7 +166,8 @@ const showSensitiveColumn = computed(() => {
engine.value === Engine.REDSHIFT ||
engine.value === Engine.ORACLE ||
engine.value === Engine.SNOWFLAKE ||
- engine.value === Engine.MSSQL)
+ engine.value === Engine.MSSQL ||
+ engine.value === Engine.RISINGWAVE)
);
});
diff --git a/frontend/src/components/CreateDataSourceExample.vue b/frontend/src/components/CreateDataSourceExample.vue
index f642e801a4..b1c5b86c3c 100644
--- a/frontend/src/components/CreateDataSourceExample.vue
+++ b/frontend/src/components/CreateDataSourceExample.vue
@@ -32,7 +32,8 @@
v-if="
props.engine === Engine.MYSQL ||
props.engine === Engine.TIDB ||
- props.engine === Engine.OCEANBASE
+ props.engine === Engine.OCEANBASE ||
+ props.engine === Engine.RISINGWAVE
"
>
<i18n-t
@@ -211,7 +212,7 @@ const grantStatement = (
CREATE OR REPLACE USER bytebase PASSWORD = 'YOUR_DB_PWD'
DEFAULT_ROLE = "ACCOUNTADMIN"
DEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';
-
+
GRANT ROLE "ACCOUNTADMIN" TO USER bytebase;
-- Option 2: grant more granular privileges
@@ -299,7 +300,7 @@ GRANT ALL PRIVILEGES ON FUTURE SESSION POLICYS IN DATABASE {{YOUR_DB_NAME}} TO R
-- PIPE are not allowed to be bulk granted, you need to grant them one by one.
GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;
`;
- case Engine.POSTGRES:
+ case (Engine.POSTGRES, Engine.RISINGWAVE):
return "CREATE USER bytebase WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER bytebase WITH SUPERUSER;";
case Engine.REDSHIFT:
return "CREATE USER bytebase WITH PASSWORD 'YOUR_DB_PWD' CREATEUSER CREATEDB;";
@@ -330,7 +331,7 @@ GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE
CREATE OR REPLACE USER bytebase PASSWORD = 'YOUR_DB_PWD'
DEFAULT_ROLE = "ACCOUNTADMIN"
DEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';
-
+
GRANT ROLE "ACCOUNTADMIN" TO USER bytebase;
-- Option 2: grant more granular privileges
@@ -418,7 +419,7 @@ GRANT ALL PRIVILEGES ON FUTURE SESSION POLICYS IN DATABASE {{YOUR_DB_NAME}} TO R
-- PIPE are not allowed to be bulk granted, you need to grant them one by one.
GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;
`;
- case Engine.POSTGRES:
+ case (Engine.POSTGRES, Engine.RISINGWAVE):
return "CREATE USER bytebase WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER bytebase WITH SUPERUSER;";
case Engine.MONGODB:
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});';
diff --git a/frontend/src/components/DatabaseOverviewPanel.vue b/frontend/src/components/DatabaseOverviewPanel.vue
index c1d1782f37..0407fa67ad 100644
--- a/frontend/src/components/DatabaseOverviewPanel.vue
+++ b/frontend/src/components/DatabaseOverviewPanel.vue
@@ -206,7 +206,8 @@ const hasSchemaProperty = computed(() => {
databaseEngine.value === Engine.ORACLE ||
databaseEngine.value === Engine.DM ||
databaseEngine.value === Engine.MSSQL ||
- databaseEngine.value === Engine.REDSHIFT
+ databaseEngine.value === Engine.REDSHIFT ||
+ databaseEngine.value === Engine.RISINGWAVE
);
});
diff --git a/frontend/src/components/FunctionTable.vue b/frontend/src/components/FunctionTable.vue
index 45edf30402..c62b6203d6 100644
--- a/frontend/src/components/FunctionTable.vue
+++ b/frontend/src/components/FunctionTable.vue
@@ -60,7 +60,8 @@ const hasSchemaProperty = computed(() => {
engine.value === Engine.SNOWFLAKE ||
engine.value === Engine.ORACLE ||
engine.value === Engine.DM ||
- engine.value === Engine.MSSQL
+ engine.value === Engine.MSSQL ||
+ engine.value === Engine.RISINGWAVE
);
});
diff --git a/frontend/src/components/Icon/EngineIcon.vue b/frontend/src/components/Icon/EngineIcon.vue
index 432b0bb6cd..05a7f1d645 100644
--- a/frontend/src/components/Icon/EngineIcon.vue
+++ b/frontend/src/components/Icon/EngineIcon.vue
@@ -35,6 +35,10 @@ const ICON_PATH_MAP = new Map([
Engine.OCEANBASE,
new URL("@/assets/db-oceanbase.png", import.meta.url).href,
],
+ [
+ Engine.RISINGWAVE,
+ new URL("@/assets/db-risingwave.png", import.meta.url).href,
+ ],
]);
const icon = computed(() => {
return ICON_PATH_MAP.get(props.engine);
diff --git a/frontend/src/components/InstanceForm/constants.ts b/frontend/src/components/InstanceForm/constants.ts
index 25833b8296..34a24fa770 100644
--- a/frontend/src/components/InstanceForm/constants.ts
+++ b/frontend/src/components/InstanceForm/constants.ts
@@ -51,6 +51,8 @@ export const EngineIconPath: Record<number, string> = {
[Engine.MARIADB]: new URL("@/assets/db-mariadb.png", import.meta.url).href,
[Engine.OCEANBASE]: new URL("@/assets/db-oceanbase.png", import.meta.url)
.href,
+ [Engine.RISINGWAVE]: new URL("@/assets/db-risingwave.png", import.meta.url)
+ .href,
};
export const MongoDBConnectionStringSchemaList = [
diff --git a/frontend/src/components/TableDetailDrawer.vue b/frontend/src/components/TableDetailDrawer.vue
index 57c90940ea..3d7a8359cf 100644
--- a/frontend/src/components/TableDetailDrawer.vue
+++ b/frontend/src/components/TableDetailDrawer.vue
@@ -270,7 +270,9 @@ const allowQuery = computed(() => {
return isDatabaseV1Queryable(database.value, currentUserV1.value);
});
const hasSchemaProperty = computed(
- () => instanceEngine.value === Engine.POSTGRES
+ () =>
+ instanceEngine.value === Engine.POSTGRES ||
+ instanceEngine.value === Engine.RISINGWAVE
);
const shouldShowColumnTable = computed(() => {
return instanceEngine.value !== Engine.MONGODB;
diff --git a/frontend/src/components/TableTable.vue b/frontend/src/components/TableTable.vue
index 643d99f85e..9520cae39b 100644
--- a/frontend/src/components/TableTable.vue
+++ b/frontend/src/components/TableTable.vue
@@ -105,7 +105,9 @@ const state = reactive<LocalState>({
const engine = computed(() => props.database.instanceEntity.engine);
-const isPostgres = computed(() => engine.value === Engine.POSTGRES);
+const isPostgres = computed(
+ () => engine.value === Engine.POSTGRES || engine.value === Engine.RISINGWAVE
+);
const hasSchemaProperty = computed(() => {
return (
diff --git a/frontend/src/components/ViewTable.vue b/frontend/src/components/ViewTable.vue
index 9a089d486f..27766dca75 100644
--- a/frontend/src/components/ViewTable.vue
+++ b/frontend/src/components/ViewTable.vue
@@ -48,7 +48,11 @@ const { t } = useI18n();
const engine = computed(() => props.database.instanceEntity.engine);
const hasSchemaProperty = computed(() => {
- return engine.value === Engine.POSTGRES || engine.value === Engine.SNOWFLAKE;
+ return (
+ engine.value === Engine.POSTGRES ||
+ engine.value === Engine.SNOWFLAKE ||
+ engine.value === Engine.RISINGWAVE
+ );
});
const columnList = computed(() => [
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index 86461757bf..73f9702726 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -20,6 +20,7 @@ export const EngineTypeList = [
"MARIADB",
"OCEANBASE",
"DM",
+ "RISINGWAVE",
] as const;
export type EngineType = typeof EngineTypeList[number];
@@ -54,6 +55,8 @@ export function convertEngineType(type: EngineType): Engine {
return Engine.OCEANBASE;
case "DM":
return Engine.DM;
+ case "RISINGWAVE":
+ return Engine.RISINGWAVE;
}
return Engine.ENGINE_UNSPECIFIED;
}
@@ -84,6 +87,8 @@ export function defaultCharset(type: EngineType): string {
return "";
case "REDSHIFT":
return "UNICODE";
+ case "RISINGWAVE":
+ return "UTF8";
}
}
@@ -117,6 +122,8 @@ export function engineName(type: EngineType): string {
return "OceanBase";
case "DM":
return "DM";
+ case "RISINGWAVE":
+ return "RisingWave";
}
}
@@ -134,6 +141,7 @@ export function defaultCollation(type: EngineType): string {
// If that's the case, setting an explicit default such as "en_US.UTF-8" might fail if the instance doesn't
// install it.
case "POSTGRES":
+ case "RISINGWAVE":
return "";
case "MONGODB":
return "";
diff --git a/frontend/src/types/proto/v1/common.ts b/frontend/src/types/proto/v1/common.ts
index 6127391a9a..abcc16ee2c 100644
--- a/frontend/src/types/proto/v1/common.ts
+++ b/frontend/src/types/proto/v1/common.ts
@@ -58,6 +58,7 @@ export enum Engine {
MARIADB = 13,
OCEANBASE = 14,
DM = 15,
+ RISINGWAVE = 16,
UNRECOGNIZED = -1,
}
@@ -111,6 +112,9 @@ export function engineFromJSON(object: any): Engine {
case 15:
case "DM":
return Engine.DM;
+ case 16:
+ case "RISINGWAVE":
+ return Engine.RISINGWAVE;
case -1:
case "UNRECOGNIZED":
default:
@@ -152,6 +156,8 @@ export function engineToJSON(object: Engine): string {
return "OCEANBASE";
case Engine.DM:
return "DM";
+ case Engine.RISINGWAVE:
+ return "RISINGWAVE";
case Engine.UNRECOGNIZED:
default:
return "UNRECOGNIZED";
diff --git a/frontend/src/utils/database.ts b/frontend/src/utils/database.ts
index bbd01fb670..08d238a151 100644
--- a/frontend/src/utils/database.ts
+++ b/frontend/src/utils/database.ts
@@ -166,6 +166,7 @@ export const hasSchemaProperty = (databaseEngine: Engine) => {
databaseEngine === Engine.SNOWFLAKE ||
databaseEngine === Engine.ORACLE ||
databaseEngine === Engine.MSSQL ||
- databaseEngine === Engine.REDSHIFT
+ databaseEngine === Engine.REDSHIFT ||
+ databaseEngine === Engine.RISINGWAVE
);
};
diff --git a/frontend/src/utils/instance.ts b/frontend/src/utils/instance.ts
index 4e5551ce38..b2f2151632 100644
--- a/frontend/src/utils/instance.ts
+++ b/frontend/src/utils/instance.ts
@@ -28,6 +28,7 @@ export const supportedEngineList = () => {
"MSSQL",
"REDSHIFT",
"DM",
+ "RISINGWAVE",
];
return engines;
};
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 364697b589..1e84d4dc20 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -88,6 +88,7 @@ export const supportedEngineV1List = () => {
Engine.MARIADB,
Engine.MSSQL,
Engine.REDSHIFT,
+ Engine.RISINGWAVE,
];
if (locale.value === "zh-CN") {
engines.push(Engine.DM);
@@ -195,6 +196,7 @@ export const instanceV1HasCollationAndCharacterSet = (
Engine.CLICKHOUSE,
Engine.SNOWFLAKE,
Engine.REDSHIFT,
+ Engine.RISINGWAVE,
];
return !excludedList.includes(engine);
};
@@ -236,6 +238,8 @@ export const engineNameV1 = (type: Engine): string => {
return "OceanBase";
case Engine.DM:
return "DM";
+ case Engine.RISINGWAVE:
+ return "RisingWave";
}
return "";
};
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 83bf16e75a..c4316faf6a 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -773,6 +773,7 @@ When paginating, all other parameters provided to `ListDebugLog` must match the
| MARIADB | 13 | |
| OCEANBASE | 14 | |
| DM | 15 | |
+| RISINGWAVE | 16 | |
diff --git a/proto/generated-go/v1/common.pb.go b/proto/generated-go/v1/common.pb.go
index 421ce1c7ea..ce7a84b31a 100644
--- a/proto/generated-go/v1/common.pb.go
+++ b/proto/generated-go/v1/common.pb.go
@@ -88,6 +88,7 @@ const (
Engine_MARIADB Engine = 13
Engine_OCEANBASE Engine = 14
Engine_DM Engine = 15
+ Engine_RISINGWAVE Engine = 16
)
// Enum value maps for Engine.
@@ -109,6 +110,7 @@ var (
13: "MARIADB",
14: "OCEANBASE",
15: "DM",
+ 16: "RISINGWAVE",
}
Engine_value = map[string]int32{
"ENGINE_UNSPECIFIED": 0,
@@ -127,6 +129,7 @@ var (
"MARIADB": 13,
"OCEANBASE": 14,
"DM": 15,
+ "RISINGWAVE": 16,
}
)
@@ -165,7 +168,7 @@ var file_v1_common_proto_rawDesc = []byte{
0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x45,
0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a,
0x0a, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x44, 0x45,
- 0x4c, 0x45, 0x54, 0x45, 0x44, 0x10, 0x02, 0x2a, 0xdc, 0x01, 0x0a, 0x06, 0x45, 0x6e, 0x67, 0x69,
+ 0x4c, 0x45, 0x54, 0x45, 0x44, 0x10, 0x02, 0x2a, 0xec, 0x01, 0x0a, 0x06, 0x45, 0x6e, 0x67, 0x69,
0x6e, 0x65, 0x12, 0x16, 0x0a, 0x12, 0x45, 0x4e, 0x47, 0x49, 0x4e, 0x45, 0x5f, 0x55, 0x4e, 0x53,
0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x43, 0x4c,
0x49, 0x43, 0x4b, 0x48, 0x4f, 0x55, 0x53, 0x45, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x4d, 0x59,
@@ -179,7 +182,8 @@ var file_v1_common_proto_rawDesc = []byte{
0x51, 0x4c, 0x10, 0x0b, 0x12, 0x0c, 0x0a, 0x08, 0x52, 0x45, 0x44, 0x53, 0x48, 0x49, 0x46, 0x54,
0x10, 0x0c, 0x12, 0x0b, 0x0a, 0x07, 0x4d, 0x41, 0x52, 0x49, 0x41, 0x44, 0x42, 0x10, 0x0d, 0x12,
0x0d, 0x0a, 0x09, 0x4f, 0x43, 0x45, 0x41, 0x4e, 0x42, 0x41, 0x53, 0x45, 0x10, 0x0e, 0x12, 0x06,
- 0x0a, 0x02, 0x44, 0x4d, 0x10, 0x0f, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61,
+ 0x0a, 0x02, 0x44, 0x4d, 0x10, 0x0f, 0x12, 0x0e, 0x0a, 0x0a, 0x52, 0x49, 0x53, 0x49, 0x4e, 0x47,
+ 0x57, 0x41, 0x56, 0x45, 0x10, 0x10, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61,
0x74, 0x65, 0x64, 0x2d, 0x67, 0x6f, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
diff --git a/proto/v1/common.proto b/proto/v1/common.proto
index e43c9997f6..41d2d274b6 100644
--- a/proto/v1/common.proto
+++ b/proto/v1/common.proto
@@ -27,4 +27,5 @@ enum Engine {
MARIADB = 13;
OCEANBASE = 14;
DM = 15;
+ RISINGWAVE = 16;
}