Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: execute the statement before the \connect statement directly (#3318)
Danny Xu4e50a0a4940e
diff --git a/plugin/advisor/db/db.go b/plugin/advisor/db/db.goindex c1612d087b..9c9e94dfc1 100644--- a/plugin/advisor/db/db.go+++ b/plugin/advisor/db/db.go@@ -8,7 +8,7 @@ import ()// Type is the type of a database.-//nolint+// nolinttype Type stringconst (diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.goindex 9e694a0aed..4487188991 100644--- a/plugin/advisor/utils_for_tests.go+++ b/plugin/advisor/utils_for_tests.go@@ -187,7 +187,7 @@ func (*MockDriver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error)}// Execute implements the Driver interface.-func (*MockDriver) Execute(_ context.Context, _ string) error {+func (*MockDriver) Execute(_ context.Context, _ string, _ bool) error {return nil}diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 94bacb8819..5508a12763 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -115,7 +115,7 @@ func (driver *Driver) getVersion(ctx context.Context) (string, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string) error {+func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) error {tx, err := driver.db.BeginTx(ctx, nil)if err != nil {return errdiff --git a/plugin/db/clickhouse/migrate.go b/plugin/db/clickhouse/migrate.goindex 99768f2e3c..fd96f8c8c4 100644--- a/plugin/db/clickhouse/migrate.go+++ b/plugin/db/clickhouse/migrate.go@@ -47,7 +47,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {zap.String("environment", driver.connectionCtx.EnvironmentName),zap.String("database", driver.connectionCtx.InstanceName),)- if err := driver.Execute(ctx, migrationSchema); err != nil {+ if err := driver.Execute(ctx, migrationSchema, true /* createDatabase */); err != nil {log.Error("Failed to initialize migration schema.",zap.Error(err),zap.String("environment", driver.connectionCtx.EnvironmentName),diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex 9f983bbd2e..45f9024cab 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -457,7 +457,7 @@ type Driver interface {GetDBConnection(ctx context.Context, database string) (*sql.DB, error)// 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.- Execute(ctx context.Context, statement string) error+ Execute(ctx context.Context, statement string, createDatabase bool) error// Used for execute readonly SELECT statement// limit is the maximum row count returned. No limit enforced if limit <= 0Query(ctx context.Context, statement string, limit int, readOnly bool) ([]interface{}, error)diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 93aeba7970..6069eb307b 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -163,7 +163,7 @@ func (driver *Driver) getVersion(ctx context.Context) (string, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string) error {+func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) error {var buf bytes.Bufferif err := transformDelimiter(&buf, statement); err != nil {return errdiff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 679e24f339..d66bfd5ccc 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -219,68 +219,78 @@ func (driver *Driver) getVersion(ctx context.Context) (string, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string) error {+func (driver *Driver) Execute(ctx context.Context, statement string, createDatabase bool) error {owner, err := driver.GetCurrentDatabaseOwner()if err != nil {return err}+ connected := falsevar remainingStmts []stringf := 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 strings.HasPrefix(stmt, "CREATE DATABASE ") {- databases, err := driver.getDatabases(ctx)- if err != nil {- return err- }- databaseName, err := getDatabaseInCreateDatabaseStatement(stmt)- if err != nil {- return err- }- exist := false- for _, database := range databases {- if database.name == databaseName {- exist = true- break+ if createDatabase && !connected {+ if strings.HasPrefix(stmt, "CREATE DATABASE ") {+ databases, err := driver.getDatabases(ctx)+ if err != nil {+ return err}- }-- if !exist {+ databaseName, err := getDatabaseInCreateDatabaseStatement(stmt)+ if err != nil {+ return err+ }+ exist := false+ for _, database := range databases {+ if database.name == databaseName {+ exist = true+ break+ }+ }+ if !exist {+ if _, err := driver.db.ExecContext(ctx, stmt); err != nil {+ return err+ }+ }+ } else if strings.HasPrefix(stmt, "ALTER DATABASE") && strings.Contains(stmt, " OWNER TO ") {+ if _, err := driver.db.ExecContext(ctx, stmt); err != nil {+ return err+ }+ } else if strings.HasPrefix(stmt, "\\connect ") {+ // For the case of `\connect "dbname";`, we need to use GetDBConnection() instead of executing the statement.+ parts := strings.Split(stmt, `"`)+ if len(parts) != 3 {+ return errors.Errorf("invalid statement %q", stmt)+ }+ if _, err = driver.GetDBConnection(ctx, parts[1]); err != nil {+ return err+ }+ // Update current owner+ if owner, err = driver.GetCurrentDatabaseOwner(); err != nil {+ return err+ }+ connected = true+ } else {if _, err := driver.db.ExecContext(ctx, stmt); err != nil {return err}}- } else if strings.HasPrefix(stmt, "GRANT") || strings.HasPrefix(stmt, "ALTER DATABASE") && strings.Contains(stmt, " OWNER TO ") {- if _, err := driver.db.ExecContext(ctx, stmt); err != nil {- return err- }- } else if strings.HasPrefix(stmt, "\\connect ") {- // For the case of `\connect "dbname";`, we need to use GetDBConnection() instead of executing the statement.- parts := strings.Split(stmt, `"`)- if len(parts) != 3 {- return errors.Errorf("invalid statement %q", stmt)- }- if _, err = driver.GetDBConnection(ctx, parts[1]); err != nil {- return err- }- // Update current owner- if owner, err = driver.GetCurrentDatabaseOwner(); err != nil {- return err- }- } else if isSuperuserStatement(stmt) {- // CREATE EVENT TRIGGER statement only supports EXECUTE PROCEDURE in version 10 and before, while newer version supports both EXECUTE { FUNCTION | PROCEDURE }.- // Since we use pg_dump version 14, the dump uses a new style even for an old version of PostgreSQL.- // We should convert EXECUTE FUNCTION to EXECUTE PROCEDURE to make the restoration work on old versions.- // https://www.postgresql.org/docs/14/sql-createeventtrigger.html- if strings.Contains(strings.ToUpper(stmt), "CREATE EVENT TRIGGER") {- stmt = strings.ReplaceAll(stmt, "EXECUTE FUNCTION", "EXECUTE PROCEDURE")- }- // Use superuser privilege to run privileged statements.- stmt = fmt.Sprintf("SET LOCAL ROLE NONE;%sSET LOCAL ROLE %s;", stmt, owner)- remainingStmts = append(remainingStmts, stmt)} else {- remainingStmts = append(remainingStmts, stmt)+ if isSuperuserStatement(stmt) {+ // CREATE EVENT TRIGGER statement only supports EXECUTE PROCEDURE in version 10 and before, while newer version supports both EXECUTE { FUNCTION | PROCEDURE }.+ // Since we use pg_dump version 14, the dump uses a new style even for an old version of PostgreSQL.+ // We should convert EXECUTE FUNCTION to EXECUTE PROCEDURE to make the restoration work on old versions.+ // https://www.postgresql.org/docs/14/sql-createeventtrigger.html+ if strings.Contains(strings.ToUpper(stmt), "CREATE EVENT TRIGGER") {+ stmt = strings.ReplaceAll(stmt, "EXECUTE FUNCTION", "EXECUTE PROCEDURE")+ }+ // Use superuser privilege to run privileged statements.+ stmt = fmt.Sprintf("SET LOCAL ROLE NONE;%sSET LOCAL ROLE %s;", stmt, owner)+ remainingStmts = append(remainingStmts, stmt)+ } else {+ remainingStmts = append(remainingStmts, stmt)+ }}return nil}@@ -313,7 +323,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {func isSuperuserStatement(stmt string) bool {upperCaseStmt := strings.ToUpper(stmt)- if strings.Contains(upperCaseStmt, "CREATE EVENT TRIGGER") || strings.Contains(upperCaseStmt, "CREATE EXTENSION") || strings.Contains(upperCaseStmt, "COMMENT ON EXTENSION") || strings.Contains(upperCaseStmt, "COMMENT ON EVENT TRIGGER") {+ if strings.HasPrefix(upperCaseStmt, "GRANT") || strings.HasPrefix(upperCaseStmt, "CREATE EVENT TRIGGER") || strings.HasPrefix(upperCaseStmt, "CREATE EXTENSION") || strings.HasPrefix(upperCaseStmt, "COMMENT ON EXTENSION") || strings.HasPrefix(upperCaseStmt, "COMMENT ON EVENT TRIGGER") {return true}return falsediff --git a/plugin/db/snowflake/migrate.go b/plugin/db/snowflake/migrate.goindex e5ee0061ed..b572c54b2e 100644--- a/plugin/db/snowflake/migrate.go+++ b/plugin/db/snowflake/migrate.go@@ -55,7 +55,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {zap.String("database", driver.connectionCtx.InstanceName),)// Should use role SYSADMIN.- if err := driver.Execute(ctx, migrationSchema); err != nil {+ if err := driver.Execute(ctx, migrationSchema, true /* createDatabase */); err != nil {log.Error("Failed to initialize migration schema.",zap.Error(err),zap.String("environment", driver.connectionCtx.EnvironmentName),diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex 4aa0bad5ee..44fd0989ad 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -217,7 +217,7 @@ func getDatabasesTxn(ctx context.Context, tx *sql.Tx) ([]string, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string) error {+func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) error {count := 0f := func(stmt string) error {count++diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex a0f3c03238..69c7785e1f 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -123,7 +123,7 @@ func (driver *Driver) hasBytebaseDatabase() (bool, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string) error {+func (driver *Driver) Execute(ctx context.Context, statement string, _ bool) error {var remainingStmts []stringf := func(stmt string) error {// This is a fake CREATE DATABASE statement. Engine driver will recognize it and establish a connection to create the database.diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 37ea8a84b9..bd88ea4b09 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -197,7 +197,7 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Migreturn -1, "", err}}- if err := executor.Execute(ctx, statement); err != nil {+ if err := executor.Execute(ctx, statement, m.CreateDatabase); err != nil {return -1, "", FormatError(err)}}diff --git a/server/issue.go b/server/issue.goindex 44cc9e186e..662aa02317 100644--- a/server/issue.go+++ b/server/issue.go@@ -1194,6 +1194,7 @@ func getDatabaseNameAndStatement(dbType db.Type, createDatabaseContext api.Creat// ERROR: must be member of role "hello"//// For tenant project, the schema for the newly created database will belong to the same owner.+ // TODO(d): alter schema "public" owner to the database owner.stmt = fmt.Sprintf("%s\nALTER DATABASE \"%s\" OWNER TO %s;\n", stmt, databaseName, createDatabaseContext.Owner)if schema != "" {stmt = fmt.Sprintf("%s\n\\connect \"%s\";\n%s", stmt, databaseName, schema)