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: simplify driver.Execute() interface and figure out the transaction usage within Execute() implementation (#946)
Danny Xu805d38e08559
diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex c220132ea9..4af45e4051 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -337,7 +337,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string, useTransaction bool) error {+func (driver *Driver) Execute(ctx context.Context, statement string) error {tx, err := driver.db.BeginTx(ctx, nil)if err != nil {return err@@ -390,7 +390,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, true /* useTransaction */); err != nil {+ if err := driver.Execute(ctx, migrationSchema); err != nil {driver.l.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 db948eeed3..ed0503def2 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -383,7 +383,9 @@ type Driver interface {GetDbConnection(ctx context.Context, database string) (*sql.DB, error)GetVersion(ctx context.Context) (string, error)SyncSchema(ctx context.Context) ([]*User, []*Schema, error)- Execute(ctx context.Context, statement string, useTransaction bool) 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// 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) ([]interface{}, error)diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 27150d0f84..9c0b0c304a 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -517,7 +517,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string, useTransaction bool) error {+func (driver *Driver) Execute(ctx context.Context, statement string) error {tx, err := driver.db.BeginTx(ctx, nil)if err != nil {return errdiff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 140d964eb2..bfdaaa135d 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -357,31 +357,37 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string, useTransaction bool) error {- // We don't use transaction for creating databases in Postgres.- // https://github.com/bytebase/bytebase/issues/202- if !useTransaction {- f := func(stmt string) error {- // For the case of `\connect "dbname";`, we need to use GetDbConnection() instead of executing the statement.- if strings.HasPrefix(stmt, "\\connect ") {- parts := strings.Split(stmt, `"`)- if len(parts) != 3 {- return fmt.Errorf("invalid statement %q", stmt)- }- _, err := driver.GetDbConnection(ctx, parts[1])- return err- }+func (driver *Driver) Execute(ctx context.Context, statement string) error {+ var remainingStmts []string+ f := func(stmt string) error {+ stmt = strings.TrimLeft(stmt, " \t")+ if strings.HasPrefix(stmt, "CREATE DATABASE ") {+ // We don't use transaction for creating databases in Postgres.+ // https://github.com/bytebase/bytebase/issues/202if _, err := driver.db.ExecContext(ctx, stmt); err != nil {return err}- return nil- }- sc := bufio.NewScanner(strings.NewReader(statement))- if err := util.ApplyMultiStatements(sc, f); err != nil {+ } 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 fmt.Errorf("invalid statement %q", stmt)+ }+ _, err := driver.GetDbConnection(ctx, parts[1])return err+ } else {+ remainingStmts = append(remainingStmts, stmt)}return nil}+ sc := bufio.NewScanner(strings.NewReader(statement))+ if err := util.ApplyMultiStatements(sc, f); err != nil {+ return err+ }++ if len(remainingStmts) == 0 {+ return nil+ }tx, err := driver.db.BeginTx(ctx, nil)if err != nil {@@ -389,9 +395,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, useTransact}defer tx.Rollback()- _, err = tx.ExecContext(ctx, statement)-- if err == nil {+ if _, err = tx.ExecContext(ctx, strings.Join(remainingStmts, "\n")); err == nil {if err := tx.Commit(); err != nil {return err}diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex c2c292a16f..e4f13a0c3b 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -476,7 +476,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string, useTransaction bool) error {+func (driver *Driver) Execute(ctx context.Context, statement string) error {count := 0f := func(stmt string) error {count++@@ -566,7 +566,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, true /* useTransaction */); err != nil {+ if err := driver.Execute(ctx, migrationSchema); err != nil {driver.l.Error("Failed to initialize migration schema.",zap.Error(err),zap.String("environment", driver.connectionCtx.EnvironmentName),diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex 99ecd112b8..828b79f988 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -316,23 +316,39 @@ func (driver *Driver) hasBytebaseDatabase() (bool, error) {}// Execute executes a SQL statement.-func (driver *Driver) Execute(ctx context.Context, statement string, useTransaction bool) error {- // This is a fake CREATA DATABASE statement. Engine driver will recognize it and establish a connect to create the database.- if strings.HasPrefix(statement, "CREATE DATABASE ") {- parts := strings.Split(statement, `'`)- if len(parts) != 3 {- return fmt.Errorf("invalid statement %q", statement)- }- db, err := driver.GetDbConnection(ctx, parts[1])- if err != nil {- return err- }- // We need to query to persist the database file.- if _, err := db.Query("SELECT 1;"); err != nil {- return err+func (driver *Driver) Execute(ctx context.Context, statement string) error {+ var remainingStmts []string+ f := func(stmt string) error {+ // This is a fake CREATE DATABASE statement. Engine driver will recognize it and establish a connection to create the database.+ stmt = strings.TrimLeft(stmt, " \t")+ if strings.HasPrefix(stmt, "CREATE DATABASE ") {+ parts := strings.Split(stmt, `'`)+ if len(parts) != 3 {+ return fmt.Errorf("invalid statement %q", stmt)+ }+ db, err := driver.GetDbConnection(ctx, parts[1])+ if err != nil {+ return err+ }+ // We need to query to persist the database file.+ if _, err := db.Query("SELECT 1;"); err != nil {+ return err+ }+ } else if strings.HasPrefix(stmt, "USE ") {+ // ignore this fake use database statement.+ } else {+ remainingStmts = append(remainingStmts, stmt)}return nil}+ sc := bufio.NewScanner(strings.NewReader(statement))+ if err := util.ApplyMultiStatements(sc, f); err != nil {+ return err+ }++ if len(remainingStmts) == 0 {+ return nil+ }tx, err := driver.db.BeginTx(ctx, nil)if err != nil {@@ -340,9 +356,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, useTransact}defer tx.Rollback()- _, err = tx.ExecContext(ctx, statement)-- if err == nil {+ if _, err = tx.ExecContext(ctx, strings.Join(remainingStmts, "\n")); err == nil {if err := tx.Commit(); err != nil {return err}diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 386a2ee679..51de9a21d8 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -168,10 +168,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExecreturn -1, "", err}}- // MySQL executes DDL in its own transaction, so there is no need to supply a transaction from previous migration history updates.- // Also, we don't use transaction for creating databases in Postgres.- // https://github.com/bytebase/bytebase/issues/202- if err := executor.Execute(ctx, statement, !m.CreateDatabase); err != nil {+ if err := executor.Execute(ctx, statement); err != nil {return -1, "", formatError(err)}}diff --git a/server/issue.go b/server/issue.goindex 5f2da52393..9557212632 100644--- a/server/issue.go+++ b/server/issue.go@@ -1016,8 +1016,11 @@ func getDatabaseNameAndStatement(dbType db.Type, databaseName, characterSet, colstmt = fmt.Sprintf("%s\nUSE DATABASE %s;\n%s", stmt, databaseName, schema)}case db.SQLite:- // This is a fake CREATE DATABASE statement since a single SQLite file represents a database. Engine driver will recognize it and establish a connection to create the sqlite file representing the database.+ // This is a fake CREATE DATABASE and USE statement since a single SQLite file represents a database. Engine driver will recognize it and establish a connection to create the sqlite file representing the database.stmt = fmt.Sprintf("CREATE DATABASE '%s';", databaseName)+ if schema != "" {+ stmt = fmt.Sprintf("%s\nUSE `%s`;\n%s", stmt, databaseName, schema)+ }}return databaseName, stmt