Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
lint fix: fix Go lint warnings in the plugin/store package. (#98)
spinningbota314b00773ec
diff --git a/bin/bb/cmd/dump.go b/bin/bb/cmd/dump.goindex 25e530a86f..5c97a27364 100644--- a/bin/bb/cmd/dump.go+++ b/bin/bb/cmd/dump.go@@ -34,7 +34,7 @@ var (Use: "dump",Short: "Exports the schema of a database instance",RunE: func(cmd *cobra.Command, args []string) error {- tlsCfg := db.TlsConfig{+ tlsCfg := db.TLSConfig{SslCA: sslCA,SslCert: sslCert,SslKey: sslKey,@@ -46,7 +46,7 @@ var (// dumpDatabase exports the schema of a database instance.// When file isn't specified, the schema will be exported to stdout.-func dumpDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TlsConfig, schemaOnly bool) error {+func dumpDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TLSConfig, schemaOnly bool) error {var dbType db.Typeswitch databaseType {case "mysql":@@ -70,7 +70,7 @@ func dumpDatabase(ctx context.Context, databaseType, username, password, hostnamUsername: username,Password: password,Database: database,- TlsConfig: tlsCfg,+ TLSConfig: tlsCfg,},db.ConnectionContext{},)diff --git a/bin/bb/cmd/restore.go b/bin/bb/cmd/restore.goindex 262855d65e..b3c4f3493f 100644--- a/bin/bb/cmd/restore.go+++ b/bin/bb/cmd/restore.go@@ -35,7 +35,7 @@ var (Use: "restore",Short: "restores the schema of a database instance",RunE: func(cmd *cobra.Command, args []string) error {- tlsCfg := db.TlsConfig{+ tlsCfg := db.TLSConfig{SslCA: sslCA,SslCert: sslCert,SslKey: sslKey,@@ -46,7 +46,7 @@ var ()// restoreDatabase restores the schema of a database instance.-func restoreDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TlsConfig) error {+func restoreDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TLSConfig) error {f, err := os.OpenFile(file, os.O_RDONLY, os.ModePerm)if err != nil {return fmt.Errorf("os.OpenFile(%q) error: %v", file, err)@@ -76,7 +76,7 @@ func restoreDatabase(ctx context.Context, databaseType, username, password, hostUsername: username,Password: password,Database: database,- TlsConfig: tlsCfg,+ TLSConfig: tlsCfg,},db.ConnectionContext{},)diff --git a/bin/server/main.go b/bin/server/main.goindex b3a52f85f6..8f12430fb7 100644--- a/bin/server/main.go+++ b/bin/server/main.go@@ -6,18 +6,25 @@ import ("github.com/bytebase/bytebase/bin/server/cmd"- // Register clickhouse driver+ // Import sqlite3 driver.+ _ "github.com/mattn/go-sqlite3"++ // Register clickhouse driver._ "github.com/bytebase/bytebase/plugin/db/clickhouse"- // Register mysql driver+ // Register mysql driver._ "github.com/bytebase/bytebase/plugin/db/mysql"- // Register postgres driver+ // Register postgres driver._ "github.com/bytebase/bytebase/plugin/db/pg"- // Register snowflake driver+ _ "github.com/lib/pq"++ // Register snowflake driver._ "github.com/bytebase/bytebase/plugin/db/snowflake"- // Register fake advisor+ // Register pingcap parser driver.+ _ "github.com/pingcap/tidb/types/parser_driver"+ // Register fake advisor._ "github.com/bytebase/bytebase/plugin/advisor/fake"- // Register mysql advisor+ // Register mysql advisor._ "github.com/bytebase/bytebase/plugin/advisor/mysql")diff --git a/plugin/advisor/fake/fake_advisor.go b/plugin/advisor/fake/fake_advisor.goindex faf32e5f23..8d65536f32 100644--- a/plugin/advisor/fake/fake_advisor.go+++ b/plugin/advisor/fake/fake_advisor.go@@ -16,10 +16,11 @@ func init() {advisor.Register(db.TiDB, advisor.Fake, &Advisor{})}+// Advisor is the fake sql advisor.type Advisor struct {}-// A fake advisor to report 1 advice for each severity.+// Check is a fake advisor check reporting 1 advice for each severity.func (adv *Advisor) Check(ctx advisor.AdvisorContext, statement string) ([]advisor.Advice, error) {return []advisor.Advice{{diff --git a/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go b/plugin/advisor/mysql/mysql_migration_compatibility_advisor.goindex 19c8bb35fc..d31e502820 100644--- a/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go+++ b/plugin/advisor/mysql/mysql_migration_compatibility_advisor.go@@ -9,7 +9,6 @@ import ("github.com/pingcap/parser""github.com/pingcap/parser/ast"- _ "github.com/pingcap/tidb/types/parser_driver")var (@@ -21,6 +20,7 @@ func init() {advisor.Register(db.TiDB, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})}+// CompatibilityAdvisor is the advisor checking for schema backward compatability.type CompatibilityAdvisor struct {}diff --git a/plugin/advisor/mysql/mysql_migration_compatibility_advisor_test.go b/plugin/advisor/mysql/mysql_migration_compatibility_advisor_test.goindex 882dd398da..f4c56506ac 100644--- a/plugin/advisor/mysql/mysql_migration_compatibility_advisor_test.go+++ b/plugin/advisor/mysql/mysql_migration_compatibility_advisor_test.go@@ -4,8 +4,9 @@ import ("reflect""testing"- "github.com/bytebase/bytebase/common"+ _ "github.com/pingcap/tidb/types/parser_driver"+ "github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/advisor""go.uber.org/zap")diff --git a/plugin/advisor/mysql/mysql_syntax_advisor.go b/plugin/advisor/mysql/mysql_syntax_advisor.goindex 9e2397c4cb..456b105b17 100644--- a/plugin/advisor/mysql/mysql_syntax_advisor.go+++ b/plugin/advisor/mysql/mysql_syntax_advisor.go@@ -6,8 +6,6 @@ import ("github.com/bytebase/bytebase/plugin/db""github.com/pingcap/parser"-- _ "github.com/pingcap/tidb/types/parser_driver")var (@@ -19,6 +17,7 @@ func init() {advisor.Register(db.TiDB, advisor.MySQLSyntax, &SyntaxAdvisor{})}+// SyntaxAdvisor is the advisor for checking syntax.type SyntaxAdvisor struct {}diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 601c4cfa57..1900283a2a 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -4,12 +4,14 @@ import ("bufio""context""database/sql"- _ "embed""fmt""io""strings""time"+ // embed will embeds the migration schema.+ _ "embed"+clickhouse "github.com/ClickHouse/clickhouse-go""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db"@@ -32,6 +34,7 @@ func init() {db.Register(db.ClickHouse, newDriver)}+// Driver is the ClickHouse driver.type Driver struct {l *zap.LoggerconnectionCtx db.ConnectionContext@@ -46,6 +49,7 @@ func newDriver(config db.DriverConfig) db.Driver {}}+// Open opens a ClickHouse driver.func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {protocol := "tcp"if strings.HasPrefix(config.Host, "/") {@@ -67,7 +71,7 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connecparams = append(params, fmt.Sprintf("database=%s", config.Database))}// Set SSL configuration.- tlsConfig, err := config.TlsConfig.GetSslConfig()+ tlsConfig, err := config.TLSConfig.GetSslConfig()if err != nil {return nil, fmt.Errorf("sql: tls config error: %v", err)}@@ -104,18 +108,22 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connecreturn driver, nil}+// Close closes the driver.func (driver *Driver) Close(ctx context.Context) error {return driver.db.Close()}+// Ping pings the database.func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetDbConnection gets a database connection.func (driver *Driver) GetDbConnection(ctx context.Context, database string) (*sql.DB, error) {return driver.db, nil}+// GetVersion gets the version.func (driver *Driver) GetVersion(ctx context.Context) (string, error) {query := "SELECT VERSION()"versionRow, err := driver.db.QueryContext(ctx, query)@@ -132,7 +140,8 @@ func (driver *Driver) GetVersion(ctx context.Context) (string, error) {return version, nil}-func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchema, error) {+// SyncSchema synces the schema.+func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema, error) {excludedDatabaseList := []string{// Skip our internal "bytebase" database"'bytebase'",@@ -169,11 +178,11 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdefer columnRows.Close()// dbName/tableName -> columnList map- columnMap := make(map[string][]db.DBColumn)+ columnMap := make(map[string][]db.Column)for columnRows.Next() {var dbName stringvar tableName string- var column db.DBColumn+ var column db.Columnif err := columnRows.Scan(&dbName,&tableName,@@ -191,7 +200,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchif ok {columnMap[key] = append(tableList, column)} else {- list := make([]db.DBColumn, 0)+ list := make([]db.Column, 0)columnMap[key] = append(list, column)}}@@ -217,9 +226,9 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdefer tableRows.Close()// dbName -> tableList map- tableMap := make(map[string][]db.DBTable)+ tableMap := make(map[string][]db.Table)// dbName -> viewList map- viewMap := make(map[string][]db.DBView)+ viewMap := make(map[string][]db.View)for tableRows.Next() {var dbName, name, engine, definition, comment string@@ -239,14 +248,14 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSch}if engine == "View" {- var view db.DBView+ var view db.Viewview.Name = nameview.UpdatedTs = lastUpdatedTime.Unix()view.Definition = definitionview.Comment = commentviewMap[dbName] = append(viewMap[dbName], view)} else {- var table db.DBTable+ var table db.Tabletable.Type = "BASE TABLE"table.Name = nametable.Engine = engine@@ -264,7 +273,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSch}}- schemaList := make([]*db.DBSchema, 0)+ schemaList := make([]*db.Schema, 0)// Query db infowhere := fmt.Sprintf("name NOT IN (%s)", strings.Join(excludedDatabaseList, ", "))query = `@@ -278,7 +287,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSch}defer rows.Close()for rows.Next() {- var schema db.DBSchema+ var schema db.Schemaif err := rows.Scan(&schema.Name,); err != nil {@@ -296,7 +305,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn userList, schemaList, nil}-func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {+func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {// Query user info// host_ip isn't used for user identifier.query := `@@ -304,7 +313,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {nameFROM system.users`- userList := make([]*db.DBUser, 0)+ userList := make([]*db.User, 0)userRows, err := driver.db.QueryContext(ctx, query)if err != nil {@@ -341,7 +350,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {grantList = append(grantList, grant)}- userList = append(userList, &db.DBUser{+ userList = append(userList, &db.User{Name: user,Grant: strings.Join(grantList, "\n"),})@@ -349,6 +358,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {return userList, nil}+// Execute executes a SQL statement.func (driver *Driver) Execute(ctx context.Context, statement string) error {tx, err := driver.db.BeginTx(ctx, nil)if err != nil {@@ -374,7 +384,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {return err}-// Migration related+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {const query = `SELECT@@ -385,6 +395,7 @@ func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {return util.NeedsSetupMigrationSchema(ctx, driver.db, query)}+// SetupMigrationIfNeeded sets up migration if needed.func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {setup, err := driver.NeedsSetupMigration(ctx)if err != nil {@@ -413,7 +424,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration for MySQL.+// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {insertHistoryQuery := `INSERT INTO bytebase.migration_history (@@ -466,6 +477,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,return util.ExecuteMigration(ctx, driver.l, db.ClickHouse, driver, m, statement, args)}+// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `SELECT@@ -511,6 +523,7 @@ const ("%s;\n")+// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer, schemaOnly bool) error {txn, err := driver.db.BeginTx(ctx, &sql.TxOptions{})if err != nil {@@ -671,6 +684,7 @@ func getTables(txn *sql.Tx, dbName string) ([]*tableSchema, error) {return tables, nil}+// Restore restores a database.func (driver *Driver) Restore(ctx context.Context, sc *bufio.Scanner) (err error) {txn, err := driver.db.BeginTx(ctx, nil)if err != nil {diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex db28ccac52..b7bbd4398c 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -14,22 +14,30 @@ import ("go.uber.org/zap")+// Type is the type of a database.type Type stringconst (+ // ClickHouse is the database type for CLICKHOUSE.ClickHouse Type = "CLICKHOUSE"- MySQL Type = "MYSQL"- Postgres Type = "POSTGRES"- Snowflake Type = "SNOWFLAKE"- TiDB Type = "TIDB"+ // MySQL is the database type for MYSQL.+ MySQL Type = "MYSQL"+ // Postgres is the database type for POSTGRES.+ Postgres Type = "POSTGRES"+ // Snowflake is the database type for SNOWFLAKE.+ Snowflake Type = "SNOWFLAKE"+ // TiDB is the database type for TIDB.+ TiDB Type = "TIDB")-type DBUser struct {+// User is the database user.+type User struct {Name stringGrant string}-type DBView struct {+// View is the database view.+type View struct {Name string// CreatedTs isn't supported for ClickHouse.CreatedTs int64@@ -38,7 +46,8 @@ type DBView struct {Comment string}-type DBIndex struct {+// Index is the database index.+type Index struct {Name string// This could refer to a column or an expressionExpression string@@ -50,7 +59,8 @@ type DBIndex struct {Comment string}-type DBColumn struct {+// Column the database table column.+type Column struct {Name stringPosition intDefault *string@@ -64,7 +74,8 @@ type DBColumn struct {Comment string}-type DBTable struct {+// Table is the database table.+type Table struct {Name string// CreatedTs isn't supported for ClickHouse.CreatedTs int64@@ -83,37 +94,42 @@ type DBTable struct {// CreateOptions isn't supported for Postgres, ClickHouse, Snowflake.CreateOptions stringComment string- ColumnList []DBColumn+ ColumnList []Column// IndexList isn't supported for ClickHouse, Snowflake.- IndexList []DBIndex+ IndexList []Index}-type DBSchema struct {+// Schema is the database schema.+type Schema struct {Name string// CharacterSet isn't supported for ClickHouse, Snowflake.CharacterSet string// Collation isn't supported for ClickHouse, Snowflake.Collation string- UserList []DBUser- TableList []DBTable- ViewList []DBView+ UserList []User+ TableList []Table+ ViewList []View}var (driversMu sync.RWMutex- drivers = make(map[Type]DriverFunc)+ drivers = make(map[Type]driverFunc))+// DriverConfig is the driver configuration.type DriverConfig struct {Logger *zap.Logger}-type DriverFunc func(DriverConfig) Driver+type driverFunc func(DriverConfig) Driver+// MigrationEngine is the migration engine.type MigrationEngine stringconst (- UI MigrationEngine = "UI"+ // UI is the migration engine type for UI.+ UI MigrationEngine = "UI"+ // VCS is the migration engine type for VCSUI.VCS MigrationEngine = "VCS")@@ -127,12 +143,16 @@ func (e MigrationEngine) String() string {return "UNKNOWN"}+// MigrationType is the type of a migration.type MigrationType stringconst (+ // Baseline is the migration type for BASELINE.Baseline MigrationType = "BASELINE"- Migrate MigrationType = "MIGRATE"- Branch MigrationType = "BRANCH"+ // Migrate is the migration type for MIGRATE.+ Migrate MigrationType = "MIGRATE"+ // Branch is the migration type for BRANCH.+ Branch MigrationType = "BRANCH")func (e MigrationType) String() string {@@ -147,12 +167,16 @@ func (e MigrationType) String() string {return "UNKNOWN"}+// MigrationStatus is the status of migration.type MigrationStatus stringconst (+ // Pending is the migration status for PENDING.Pending MigrationStatus = "PENDING"- Done MigrationStatus = "DONE"- Failed MigrationStatus = "FAILED"+ // Done is the migration status for DONE.+ Done MigrationStatus = "DONE"+ // Failed is the migration status for FAILED.+ Failed MigrationStatus = "FAILED")func (e MigrationStatus) String() string {@@ -167,10 +191,12 @@ func (e MigrationStatus) String() string {return "UNKNOWN"}+// MigrationInfoPayload is the API message for migration info payload.type MigrationInfoPayload struct {VCSPushEvent *common.VCSPushEvent `json:"pushEvent,omitempty"`}+// MigrationInfo is the API message for migration info.type MigrationInfo struct {ReleaseVersion stringVersion string@@ -262,6 +288,7 @@ func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInfreturn mi, nil}+// MigrationHistory is the API message for migration history.type MigrationHistory struct {ID int@@ -286,6 +313,7 @@ type MigrationHistory struct {Payload string}+// MigrationHistoryFind is the API message for finding migration historys.type MigrationHistoryFind struct {ID *int@@ -295,21 +323,24 @@ type MigrationHistoryFind struct {Limit *int}+// ConnectionConfig is the configuration for connections.type ConnectionConfig struct {Host stringPort stringUsername stringPassword stringDatabase string- TlsConfig TlsConfig+ TLSConfig TLSConfig}-// Context not used for establishing the db connection, but is useful for logging.+// ConnectionContext is the context for connection.+// It's not used for establishing the db connection, but is useful for logging.type ConnectionContext struct {EnvironmentName stringInstanceName string}+// Driver is the interface for database driver.type Driver interface {// A driver might support multiple engines (e.g. MySQL driver can support both MySQL and TiDB),// So we pass the dbType to tell the exact engine.@@ -319,7 +350,7 @@ type Driver interface {Ping(ctx context.Context) errorGetDbConnection(ctx context.Context, database string) (*sql.DB, error)GetVersion(ctx context.Context) (string, error)- SyncSchema(ctx context.Context) ([]*DBUser, []*DBSchema, error)+ SyncSchema(ctx context.Context) ([]*User, []*Schema, error)Execute(ctx context.Context, statement string) error// Migration related@@ -343,7 +374,7 @@ type Driver interface {// Register makes a database driver available by the provided type.// If Register is called twice with the same name or if driver is nil,// it panics.-func Register(dbType Type, f DriverFunc) {+func Register(dbType Type, f driverFunc) {driversMu.Lock()defer driversMu.Unlock()if f == nil {diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 2d3364f876..040e929849 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -4,11 +4,13 @@ import ("bufio""context""database/sql"- _ "embed""fmt""io""strings"+ // embed will embeds the migration schema.+ _ "embed"+"github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"@@ -37,6 +39,7 @@ func init() {db.Register(db.TiDB, newDriver)}+// Driver is the MySQL driver.type Driver struct {l *zap.LoggerconnectionCtx db.ConnectionContext@@ -51,6 +54,7 @@ func newDriver(config db.DriverConfig) db.Driver {}}+// Open opens a MySQL driver.func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {protocol := "tcp"if strings.HasPrefix(config.Host, "/") {@@ -67,7 +71,7 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connec}}- tlsConfig, err := config.TlsConfig.GetSslConfig()+ tlsConfig, err := config.TLSConfig.GetSslConfig()if err != nil {return nil, fmt.Errorf("sql: tls config error: %v", err)@@ -103,18 +107,22 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connecreturn driver, nil}+// Close closes the driver.func (driver *Driver) Close(ctx context.Context) error {return driver.db.Close()}+// Ping pings the database.func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetDbConnection gets a database connection.func (driver *Driver) GetDbConnection(ctx context.Context, database string) (*sql.DB, error) {return driver.db, nil}+// GetVersion gets the version.func (driver *Driver) GetVersion(ctx context.Context) (string, error) {query := "SELECT VERSION()"versionRow, err := driver.db.QueryContext(ctx, query)@@ -131,7 +139,8 @@ func (driver *Driver) GetVersion(ctx context.Context) (string, error) {return version, nil}-func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchema, error) {+// SyncSchema synces the schema.+func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema, error) {// Query MySQL versionversion, err := driver.GetVersion(ctx)if err != nil {@@ -194,13 +203,13 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdefer indexRows.Close()// dbName/tableName -> indexList map- indexMap := make(map[string][]db.DBIndex)+ indexMap := make(map[string][]db.Index)for indexRows.Next() {var dbName stringvar tableName stringvar columnName sql.NullStringvar expression sql.NullString- var index db.DBIndex+ var index db.Indexif err := indexRows.Scan(&dbName,&tableName,@@ -227,7 +236,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchif ok {indexMap[key] = append(indexList, index)} else {- list := make([]db.DBIndex, 0)+ list := make([]db.Index, 0)indexMap[key] = append(list, index)}}@@ -255,13 +264,13 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdefer columnRows.Close()// dbName/tableName -> columnList map- columnMap := make(map[string][]db.DBColumn)+ columnMap := make(map[string][]db.Column)for columnRows.Next() {var dbName stringvar tableName stringvar nullable stringvar defaultStr sql.NullString- var column db.DBColumn+ var column db.Columnif err := columnRows.Scan(&dbName,&tableName,@@ -286,7 +295,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchif ok {columnMap[key] = append(tableList, column)} else {- list := make([]db.DBColumn, 0)+ list := make([]db.Column, 0)columnMap[key] = append(list, column)}}@@ -317,7 +326,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdefer tableRows.Close()// dbName -> tableList map- tableMap := make(map[string][]db.DBTable)+ tableMap := make(map[string][]db.Table)type ViewInfo struct {createdTs int64updatedTs int64@@ -329,7 +338,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchvar dbName string// Workaround TiDB bug https://github.com/pingcap/tidb/issues/27970var tableCollation sql.NullString- var table db.DBTable+ var table db.Tableif err := tableRows.Scan(&dbName,&table.Name,@@ -361,7 +370,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchif ok {tableMap[dbName] = append(tableList, table)} else {- list := make([]db.DBTable, 0)+ list := make([]db.Table, 0)tableMap[dbName] = append(list, table)}} else if table.Type == "VIEW" {@@ -389,10 +398,10 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdefer viewRows.Close()// dbName -> viewList map- viewMap := make(map[string][]db.DBView)+ viewMap := make(map[string][]db.View)for viewRows.Next() {var dbName string- var view db.DBView+ var view db.Viewif err := viewRows.Scan(&dbName,&view.Name,@@ -410,7 +419,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchif ok {viewMap[dbName] = append(viewList, view)} else {- list := make([]db.DBView, 0)+ list := make([]db.View, 0)viewMap[dbName] = append(list, view)}}@@ -430,9 +439,9 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSch}defer rows.Close()- schemaList := make([]*db.DBSchema, 0)+ schemaList := make([]*db.Schema, 0)for rows.Next() {- var schema db.DBSchema+ var schema db.Schemaif err := rows.Scan(&schema.Name,&schema.CharacterSet,@@ -453,7 +462,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn userList, schemaList, err}-func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {+func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {// Query user infoquery := `SELECT@@ -462,7 +471,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {FROM mysql.userWHERE user NOT LIKE 'mysql.%'`- userList := make([]*db.DBUser, 0)+ userList := make([]*db.User, 0)userRows, err := driver.db.QueryContext(ctx, query)if err != nil {@@ -502,7 +511,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {grantList = append(grantList, grant)}- userList = append(userList, &db.DBUser{+ userList = append(userList, &db.User{Name: name,Grant: strings.Join(grantList, "\n"),})@@ -510,6 +519,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {return userList, nil}+// Execute executes a SQL statement.func (driver *Driver) Execute(ctx context.Context, statement string) error {tx, err := driver.db.BeginTx(ctx, nil)if err != nil {@@ -528,7 +538,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {return err}-// Migration related+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {const query = `SELECT@@ -539,6 +549,7 @@ func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {return util.NeedsSetupMigrationSchema(ctx, driver.db, query)}+// SetupMigrationIfNeeded sets up migration if needed.func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {setup, err := driver.NeedsSetupMigration(ctx)if err != nil {@@ -570,7 +581,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration for MySQL.+// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {insertHistoryQuery := `INSERT INTO bytebase.migration_history (@@ -623,6 +634,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,return util.ExecuteMigration(ctx, driver.l, db.MySQL, driver, m, statement, args)}+// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `SELECT@@ -698,6 +710,7 @@ const ("DELIMITER ;\n")+// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer, schemaOnly bool) error {// mysqldump -u root --databases dbName --no-data --routines --events --triggers --compact@@ -723,6 +736,7 @@ func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer,return nil}+// Restore restores a database.func (driver *Driver) Restore(ctx context.Context, sc *bufio.Scanner) (err error) {txn, err := driver.db.BeginTx(ctx, nil)if err != nil {diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex d1cbc90ac2..45cf5e619d 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -4,16 +4,17 @@ import ("bufio""context""database/sql"- _ "embed""fmt""io""regexp""strings""time"+ // embed will embeds the migration schema.+ _ "embed"+"github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"- _ "github.com/lib/pq""go.uber.org/zap")@@ -189,6 +190,7 @@ func init() {db.Register(db.Postgres, newDriver)}+// Driver is the Postgres driver.type Driver struct {l *zap.LoggerconnectionCtx db.ConnectionContext@@ -203,9 +205,10 @@ func newDriver(config db.DriverConfig) db.Driver {}}+// Open opens a Postgres driver.func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {- if (config.TlsConfig.SslCert == "" && config.TlsConfig.SslKey != "") ||- (config.TlsConfig.SslCert != "" && config.TlsConfig.SslKey == "") {+ if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||+ (config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {return nil, fmt.Errorf("ssl-cert and ssl-key must be both set or unset")}@@ -215,9 +218,9 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connecconfig.Host,config.Port,config.Database,- config.TlsConfig.SslCA,- config.TlsConfig.SslCert,- config.TlsConfig.SslKey,+ config.TLSConfig.SslCA,+ config.TLSConfig.SslCert,+ config.TLSConfig.SslKey,)if err != nil {return nil, err@@ -292,14 +295,17 @@ func guessDSN(username, password, hostname, port, database, sslCA, sslCert, sslKreturn "", fmt.Errorf("cannot connecting instance, make sure the connection info is correct")}+// Close closes the driver.func (driver *Driver) Close(ctx context.Context) error {return driver.db.Close()}+// Ping pings the database.func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetDbConnection gets a database connection.func (driver *Driver) GetDbConnection(ctx context.Context, database string) (*sql.DB, error) {if err := driver.switchDatabase(database); err != nil {return nil, err@@ -307,6 +313,7 @@ func (driver *Driver) GetDbConnection(ctx context.Context, database string) (*sqreturn driver.db, nil}+// GetVersion gets the version.func (driver *Driver) GetVersion(ctx context.Context) (string, error) {query := "SHOW server_version"versionRow, err := driver.db.QueryContext(ctx, query)@@ -323,7 +330,8 @@ func (driver *Driver) GetVersion(ctx context.Context) (string, error) {return version, nil}-func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchema, error) {+// SyncSchema synces the schema.+func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema, error) {excludedDatabaseList := map[string]bool{// Skip our internal "bytebase" database"bytebase": true,@@ -351,14 +359,14 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn nil, nil, fmt.Errorf("failed to get databases: %s", err)}- schemaList := make([]*db.DBSchema, 0)+ schemaList := make([]*db.Schema, 0)for _, database := range databases {dbName := database.nameif _, ok := excludedDatabaseList[dbName]; ok {continue}- var schema db.DBSchema+ var schema db.Schemaschema.Name = dbNameschema.CharacterSet = database.encodingschema.Collation = database.collate@@ -390,7 +398,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn nil, nil, fmt.Errorf("failed to get tables from database %q: %s", dbName, err)}for _, tbl := range tables {- var dbTable db.DBTable+ var dbTable db.TabledbTable.Name = fmt.Sprintf("%s.%s", tbl.schemaName, tbl.name)dbTable.Type = "BASE TABLE"dbTable.Comment = tbl.comment@@ -398,7 +406,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchdbTable.DataSize = tbl.tableSizeBytedbTable.IndexSize = tbl.indexSizeBytefor _, col := range tbl.columns {- var dbColumn db.DBColumn+ var dbColumn db.ColumndbColumn.Name = col.columnNamedbColumn.Position = col.ordinalPositiondbColumn.Default = &col.columnDefault@@ -411,7 +419,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchindices := indicesMap[dbTable.Name]for _, idx := range indices {for i, colExp := range idx.columnExpressions {- var dbIndex db.DBIndex+ var dbIndex db.IndexdbIndex.Name = idx.namedbIndex.Expression = colExpdbIndex.Position = i + 1@@ -430,7 +438,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn nil, nil, fmt.Errorf("failed to get views from database %q: %s", dbName, err)}for _, view := range views {- var dbView db.DBView+ var dbView db.ViewdbView.Name = fmt.Sprintf("%s.%s", view.schemaName, view.name)// Postgres does not storedbView.CreatedTs = time.Now().Unix()@@ -450,7 +458,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn userList, schemaList, err}-func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {+func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {// Query user infoquery := `SELECT usename AS role_name,@@ -467,7 +475,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {FROM pg_catalog.pg_userORDER BY role_name`- userList := make([]*db.DBUser, 0)+ userList := make([]*db.User, 0)userRows, err := driver.db.QueryContext(ctx, query)if err != nil {return nil, util.FormatErrorWithQuery(err, query)@@ -484,7 +492,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {return nil, err}- userList = append(userList, &db.DBUser{+ userList = append(userList, &db.User{Name: role,Grant: attr,})@@ -492,6 +500,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {return userList, nil}+// Execute executes a SQL statement.func (driver *Driver) Execute(ctx context.Context, statement string) error {tx, err := driver.db.BeginTx(ctx, nil)if err != nil {@@ -510,7 +519,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {return err}-// Migration related+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {exist, err := driver.hasBytebaseDatabase(ctx)if err != nil {@@ -547,6 +556,7 @@ func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {return exist, nil}+// SetupMigrationIfNeeded sets up migration if needed.func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {setup, err := driver.NeedsSetupMigration(ctx)if err != nil {@@ -606,6 +616,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}+// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {insertHistoryQuery := `INSERT INTO migration_history (@@ -659,6 +670,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,return util.ExecuteMigration(ctx, driver.l, db.Postgres, driver, m, statement, args)}+// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `SELECT@@ -686,6 +698,8 @@ func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Mig}// Dump and restore++// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer, schemaOnly bool) error {// pg_dump -d dbName --schema-only+@@ -727,6 +741,7 @@ func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer,return nil}+// Restore restores a database.func (driver *Driver) Restore(ctx context.Context, sc *bufio.Scanner) (err error) {txn, err := driver.db.BeginTx(ctx, nil)if err != nil {@@ -1753,7 +1768,7 @@ func quoteIdentifier(s string) string {}if quote {return fmt.Sprintf("\"%s\"", strings.ReplaceAll(s, "\"", "\"\""))- } else {- return s}+ return s+}diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex 21db748fad..a93389b1f1 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -4,11 +4,13 @@ import ("bufio""context""database/sql"- _ "embed""fmt""io""strings"+ // embed will embeds the migration schema.+ _ "embed"+"github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"snow "github.com/snowflakedb/gosnowflake"@@ -33,6 +35,7 @@ func init() {db.Register(db.Snowflake, newDriver)}+// Driver is the Snowflake driver.type Driver struct {l *zap.LoggerconnectionCtx db.ConnectionContext@@ -47,6 +50,7 @@ func newDriver(config db.DriverConfig) db.Driver {}}+// Open opens a Snowflake driver.func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {prefixParts, loggedPrefixParts := []string{config.Username}, []string{config.Username}if config.Password != "" {@@ -97,18 +101,22 @@ func (driver *Driver) Open(ctx context.Context, dbType db.Type, config db.Connecreturn driver, nil}+// Close closes the driver.func (driver *Driver) Close(ctx context.Context) error {return driver.db.Close()}+// Ping pings the database.func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetDbConnection gets a database connection.func (driver *Driver) GetDbConnection(ctx context.Context, database string) (*sql.DB, error) {return driver.db, nil}+// GetVersion gets the version.func (driver *Driver) GetVersion(ctx context.Context) (string, error) {query := "SELECT CURRENT_VERSION()"versionRow, err := driver.db.QueryContext(ctx, query)@@ -125,7 +133,7 @@ func (driver *Driver) GetVersion(ctx context.Context) (string, error) {return version, nil}-func (driver *Driver) UseRole(ctx context.Context, role string) error {+func (driver *Driver) useRole(ctx context.Context, role string) error {query := fmt.Sprintf("USE ROLE %s", role)if _, err := driver.db.ExecContext(ctx, query); err != nil {return util.FormatErrorWithQuery(err, query)@@ -133,9 +141,10 @@ func (driver *Driver) UseRole(ctx context.Context, role string) error {return nil}-func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchema, error) {+// SyncSchema synces the schema.+func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.User, []*db.Schema, error) {// Query user info- if err := driver.UseRole(ctx, accountAdminRole); err != nil {+ if err := driver.useRole(ctx, accountAdminRole); err != nil {return nil, nil, err}@@ -150,13 +159,13 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn nil, nil, err}- var schemaList []*db.DBSchema+ var schemaList []*db.Schemafor _, database := range databases {if database == bytebaseDatabase {continue}- var schema db.DBSchema+ var schema db.Schemaschema.Name = databasetableList, viewList, err := driver.syncTableSchema(ctx, database)if err != nil {@@ -170,7 +179,7 @@ func (driver *Driver) SyncSchema(ctx context.Context) ([]*db.DBUser, []*db.DBSchreturn userList, schemaList, nil}-func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]db.DBTable, []db.DBView, error) {+func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]db.Table, []db.View, error) {// Query table infovar excludedSchemaList []string@@ -202,13 +211,13 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]ddefer columnRows.Close()// schemaName.tableName -> columnList map- columnMap := make(map[string][]db.DBColumn)+ columnMap := make(map[string][]db.Column)for columnRows.Next() {var schemaName stringvar tableName stringvar nullable stringvar defaultStr sql.NullString- var column db.DBColumn+ var column db.Columnif err := columnRows.Scan(&schemaName,&tableName,@@ -250,10 +259,10 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]d}defer tableRows.Close()- var tables []db.DBTable+ var tables []db.Tablefor tableRows.Next() {var schemaName, tableName string- var table db.DBTable+ var table db.Tableif err := tableRows.Scan(&schemaName,&tableName,@@ -291,11 +300,11 @@ func (driver *Driver) syncTableSchema(ctx context.Context, database string) ([]d}defer viewRows.Close()- var views []db.DBView+ var views []db.Viewfor viewRows.Next() {var schemaName, viewName stringvar createdTs, updatedTs sql.NullInt64- var view db.DBView+ var view db.Viewif err := viewRows.Scan(&schemaName,&viewName,@@ -408,7 +417,7 @@ func getDatabasesTxn(ctx context.Context, tx *sql.Tx) ([]string, error) {return databases, nil}-func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {+func (driver *Driver) getUserList(ctx context.Context) ([]*db.User, error) {query := `SELECTGRANTEE_NAME,@@ -440,7 +449,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {nameFROM SNOWFLAKE.ACCOUNT_USAGE.USERS`- userList := make([]*db.DBUser, 0)+ userList := make([]*db.User, 0)userRows, err := driver.db.QueryContext(ctx, query)if err != nil {@@ -456,7 +465,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {return nil, err}- userList = append(userList, &db.DBUser{+ userList = append(userList, &db.User{Name: name,Grant: strings.Join(grants[name], ", "),})@@ -464,6 +473,7 @@ func (driver *Driver) getUserList(ctx context.Context) ([]*db.DBUser, error) {return userList, nil}+// Execute executes a SQL statement.func (driver *Driver) Execute(ctx context.Context, statement string) error {count := 0f := func(stmt string) error {@@ -479,7 +489,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {return nil}- if err := driver.UseRole(ctx, sysAdminRole); err != nil {+ if err := driver.useRole(ctx, sysAdminRole); err != nil {return nil}tx, err := driver.db.BeginTx(ctx, nil)@@ -502,7 +512,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {return err}-// Migration related+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {exist, err := driver.hasBytebaseDatabase(ctx)if err != nil {@@ -536,6 +546,7 @@ func (driver *Driver) hasBytebaseDatabase(ctx context.Context) (bool, error) {return exist, nil}+// SetupMigrationIfNeeded sets up migration if needed.func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {setup, err := driver.NeedsSetupMigration(ctx)if err != nil {@@ -567,7 +578,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- if err := driver.UseRole(ctx, sysAdminRole); err != nil {+ if err := driver.useRole(ctx, sysAdminRole); err != nil {return int64(0), "", err}insertHistoryQuery := `@@ -621,6 +632,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,return util.ExecuteMigration(ctx, driver.l, db.Snowflake, driver, m, statement, args)}+// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `SELECT@@ -655,6 +667,7 @@ const ("--\n")+// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer, schemaOnly bool) error {txn, err := driver.db.BeginTx(ctx, &sql.TxOptions{})if err != nil {@@ -767,8 +780,9 @@ func dumpOneDatabase(ctx context.Context, txn *sql.Tx, database string, out io.Wreturn nil}+// Restore restores a database.func (driver *Driver) Restore(ctx context.Context, sc *bufio.Scanner) (err error) {- if err := driver.UseRole(ctx, sysAdminRole); err != nil {+ if err := driver.useRole(ctx, sysAdminRole); err != nil {return nil}txn, err := driver.db.BeginTx(ctx, nil)diff --git a/plugin/db/ssl.go b/plugin/db/ssl.goindex 026cd338d7..738604a0f0 100644--- a/plugin/db/ssl.go+++ b/plugin/db/ssl.go@@ -7,15 +7,15 @@ import ("io/ioutil")-// TlsConfig is the configuration for SSL connection.-type TlsConfig struct {+// TLSConfig is the configuration for SSL connection.+type TLSConfig struct {SslCA stringSslCert stringSslKey string}// GetSslConfig gets the SSL config for connection.-func (tc TlsConfig) GetSslConfig() (*tls.Config, error) {+func (tc TLSConfig) GetSslConfig() (*tls.Config, error) {if tc.SslCA == "" {return nil, nil}diff --git a/plugin/webhook/dingtalk.go b/plugin/webhook/dingtalk.goindex eb83ae073a..3209cc2aea 100644--- a/plugin/webhook/dingtalk.go+++ b/plugin/webhook/dingtalk.go@@ -10,16 +10,19 @@ import ("time")+// DingTalkWebhookResponse is the API message for DingTalk webhook response.type DingTalkWebhookResponse struct {ErrorCode int `json:"errcode"`ErrorMessage string `json:"errmsg"`}+// DingTalkWebhookMarkdown is the API message for DingTalk webhook markdown.type DingTalkWebhookMarkdown struct {Title string `json:"title"`Text string `json:"text"`}+// DingTalkWebhook is the API message for DingTalk webhook.type DingTalkWebhook struct {MessageType string `json:"msgtype"`Markdown DingTalkWebhookMarkdown `json:"markdown"`@@ -29,10 +32,11 @@ func init() {register("bb.plugin.webhook.dingtalk", &DingTalkReceiver{})}+// DingTalkReceiver is the receiver for DingTalk.type DingTalkReceiver struct {}-func (receiver *DingTalkReceiver) post(context WebhookContext) error {+func (receiver *DingTalkReceiver) post(context Context) error {metaStrList := []string{}for _, meta := range context.MetaList {metaStrList = append(metaStrList, fmt.Sprintf("##### **%s:** %s", meta.Name, meta.Value))diff --git a/plugin/webhook/discord.go b/plugin/webhook/discord.goindex b57b9b4d66..3a6aa2cc03 100644--- a/plugin/webhook/discord.go+++ b/plugin/webhook/discord.go@@ -9,20 +9,24 @@ import ("time")+// DiscordWebhookResponse is the API message for Discord webhook response.type DiscordWebhookResponse struct {Code int `json:"code"`Message string `json:"message"`}+// DiscordWebhookEmbedField is the API message for Discord webhook embed field.type DiscordWebhookEmbedField struct {Name string `json:"name"`Value string `json:"value"`}+// DiscordWebhookEmbedAuthor is the API message for Discord webhook embed Author.type DiscordWebhookEmbedAuthor struct {Name string `json:"name"`}+// DiscordWebhookEmbed is the API message for Discord webhook embed.type DiscordWebhookEmbed struct {Title string `json:"title"`Type string `json:"type"`@@ -33,6 +37,7 @@ type DiscordWebhookEmbed struct {FieldList []DiscordWebhookEmbedField `json:"fields,omitempty"`}+// DiscordWebhook is the API message for Discord webhook.type DiscordWebhook struct {EmbedList []DiscordWebhookEmbed `json:"embeds"`}@@ -41,10 +46,11 @@ func init() {register("bb.plugin.webhook.discord", &DiscordReceiver{})}+// DiscordReceiver is the receiver for Discord.type DiscordReceiver struct {}-func (receiver *DiscordReceiver) post(context WebhookContext) error {+func (receiver *DiscordReceiver) post(context Context) error {embedList := []DiscordWebhookEmbed{}fieldList := []DiscordWebhookEmbedField{}diff --git a/plugin/webhook/feishu.go b/plugin/webhook/feishu.goindex bf9e07ec35..4934ab2bf8 100644--- a/plugin/webhook/feishu.go+++ b/plugin/webhook/feishu.go@@ -9,34 +9,41 @@ import ("time")+// FeishuWebhookResponse is the API message for Feishu webhook response.type FeishuWebhookResponse struct {Code int `json:"code"`Message string `json:"msg"`}+// FeishuWebhookPostSection is the API message for Feishu webhook POST section.type FeishuWebhookPostSection struct {Tag string `json:"tag"`Text string `json:"text"`Href string `json:"href,omitempty"`}+// FeishuWebhookPostLine is the API message for Feishu webhook POST line.type FeishuWebhookPostLine struct {SectionList []FeishuWebhookPostSection `json:""`}+// FeishuWebhookPost is the API message for Feishu webhook POST.type FeishuWebhookPost struct {Title string `json:"title"`ContentList [][]FeishuWebhookPostSection `json:"content"`}+// FeishuWebhookPostLanguage is the API message for Feishu webhook POST language.type FeishuWebhookPostLanguage struct {English FeishuWebhookPost `json:"en_us"`}+// FeishuWebhookContent is the API message for Feishu webhook content.type FeishuWebhookContent struct {Post FeishuWebhookPostLanguage `json:"post"`}+// FeishuWebhook is the API message for Feishu webhook.type FeishuWebhook struct {MessageType string `json:"msg_type"`Content FeishuWebhookContent `json:"content"`@@ -46,10 +53,11 @@ func init() {register("bb.plugin.webhook.feishu", &FeishuReceiver{})}+// FeishuReceiver is the receiver for Feishu.type FeishuReceiver struct {}-func (receiver *FeishuReceiver) post(context WebhookContext) error {+func (receiver *FeishuReceiver) post(context Context) error {contentList := [][]FeishuWebhookPostSection{}if context.Description != "" {sectionList := []FeishuWebhookPostSection{}diff --git a/plugin/webhook/slack.go b/plugin/webhook/slack.goindex 7499aa9e43..c1875910a3 100644--- a/plugin/webhook/slack.go+++ b/plugin/webhook/slack.go@@ -9,28 +9,33 @@ import ("time")+// SlackWebhookBlockMarkdown is the API message for Slack webhook block markdown.type SlackWebhookBlockMarkdown struct {Type string `json:"type"`Text string `json:"text"`}+// SlackWebhookElementButton is the API message for Slack webhook element button.type SlackWebhookElementButton struct {Type string `json:"type"`Text string `json:"text,omitempty"`}+// SlackWebhookElement is the API message for Slack webhook element.type SlackWebhookElement struct {Type string `json:"type"`Button SlackWebhookElementButton `json:"text,omitempty"`URL string `json:"url,omitempty"`}+// SlackWebhookBlock is the API message for Slack webhook block.type SlackWebhookBlock struct {Type string `json:"type"`Text *SlackWebhookBlockMarkdown `json:"text,omitempty"`ElementList []SlackWebhookElement `json:"elements,omitempty"`}+// SlackWebhook is the API message for Slack webhook.type SlackWebhook struct {Text string `json:"text"`BlockList []SlackWebhookBlock `json:"blocks"`@@ -40,10 +45,11 @@ func init() {register("bb.plugin.webhook.slack", &SlackReceiver{})}+// SlackReceiver is the receiver for Slack.type SlackReceiver struct {}-func (receiver *SlackReceiver) post(context WebhookContext) error {+func (receiver *SlackReceiver) post(context Context) error {blockList := []SlackWebhookBlock{}status := ""diff --git a/plugin/webhook/teams.go b/plugin/webhook/teams.goindex e941cd6d7d..4d06108b4b 100644--- a/plugin/webhook/teams.go+++ b/plugin/webhook/teams.go@@ -9,24 +9,28 @@ import ("time")-var THEME_COLOR = "4f46e5"+var themeColor = "4f46e5"+// TeamsWebhookActionTarget is the API message for Teams webhook action target.type TeamsWebhookActionTarget struct {OS string `json:"os"`URI string `json:"uri"`}+// TeamsWebhookAction is the API message for Teams webhook action.type TeamsWebhookAction struct {Type string `json:"@type"`Name string `json:"name"`TargetList []TeamsWebhookActionTarget `json:"targets"`}+// TeamsWebhookSectionFact is the API message for Teams webhook section fact.type TeamsWebhookSectionFact struct {Name string `json:"name"`Value string `json:"value"`}+// TeamsWebhookSection is the API message for Teams webhook section.type TeamsWebhookSection struct {ActivityTitle string `json:"activityTitle"`ActivitySubtitle string `json:"activitySubtitle"`@@ -34,6 +38,7 @@ type TeamsWebhookSection struct {Text string `json:"text"`}+// TeamsWebhook is the API message for Teams webhook.type TeamsWebhook struct {Type string `json:"@type"`Context string `json:"@context"`@@ -48,10 +53,11 @@ func init() {register("bb.plugin.webhook.teams", &TeamsReceiver{})}+// TeamsReceiver is the receiver for Teams.type TeamsReceiver struct {}-func (receiver *TeamsReceiver) post(context WebhookContext) error {+func (receiver *TeamsReceiver) post(context Context) error {factList := []TeamsWebhookSectionFact{}for _, meta := range context.MetaList {factList = append(factList, TeamsWebhookSectionFact(meta))@@ -61,7 +67,7 @@ func (receiver *TeamsReceiver) post(context WebhookContext) error {Type: "MessageCard",Context: "https://schema.org/extensions",Summary: context.Title,- ThemeColor: THEME_COLOR,+ ThemeColor: themeColor,Title: context.Title,SectionList: []TeamsWebhookSection{{diff --git a/plugin/webhook/webhook.go b/plugin/webhook/webhook.goindex 8da809a0ab..06ba1a2396 100644--- a/plugin/webhook/webhook.go+++ b/plugin/webhook/webhook.go@@ -8,46 +8,54 @@ import (var (receiverMu sync.RWMutex- receivers = make(map[string]WebhookReceiver)+ receivers = make(map[string]Receiver)// Based on the local test, Teams sometimes cannot finish the request in 1 second, so use 3s.timeout = 3 * time.SecondtimeFormat = "2006-01-02 15:04:05")-type WebhookMeta struct {+// Meta is the webhook metadata.+type Meta struct {Name stringValue string}-type WebhookLevel string+// Level is the level of webhook.+type Level stringconst (- WebhookInfo WebhookLevel = "INFO"- WebhookSuccess WebhookLevel = "SUCCESS"- WebhookWarn WebhookLevel = "WARN"- WebhookError WebhookLevel = "ERROR"+ // WebhookInfo is the webhook level for INFO.+ WebhookInfo Level = "INFO"+ // WebhookSuccess is the webhook level for SUCCESS.+ WebhookSuccess Level = "SUCCESS"+ // WebhookWarn is the webhook level for WARN.+ WebhookWarn Level = "WARN"+ // WebhookError is the webhook level for ERROR.+ WebhookError Level = "ERROR")-type WebhookContext struct {+// Context is the context of webhook.+type Context struct {URL string- Level WebhookLevel+ Level LevelTitle stringDescription stringLink stringCreatorName stringCreatorEmail stringCreatedTs int64- MetaList []WebhookMeta+ MetaList []Meta}-type WebhookReceiver interface {- post(context WebhookContext) error+// Receiver is the webhook receiver.+type Receiver interface {+ post(context Context) error}// Register makes a receiver available by the url host// If Register is called twice with the same url host or if receiver is nil,// it panics.-func register(host string, r WebhookReceiver) {+func register(host string, r Receiver) {receiverMu.Lock()defer receiverMu.Unlock()if r == nil {@@ -59,7 +67,8 @@ func register(host string, r WebhookReceiver) {receivers[host] = r}-func Post(webhookType string, context WebhookContext) error {+// Post posts the message to webhook.+func Post(webhookType string, context Context) error {receiverMu.RLock()r, ok := receivers[webhookType]receiverMu.RUnlock()diff --git a/plugin/webhook/wecom.go b/plugin/webhook/wecom.goindex ded5c8ce6f..ee45a4a1bd 100644--- a/plugin/webhook/wecom.go+++ b/plugin/webhook/wecom.go@@ -10,15 +10,18 @@ import ("time")+// WeComWebhookResponse is the API message for WeCom webhook response.type WeComWebhookResponse struct {ErrorCode int `json:"errcode"`ErrorMessage string `json:"errmsg"`}+// WeComWebhookMarkdown is the API message for WeCom webhook markdown.type WeComWebhookMarkdown struct {Content string `json:"content"`}+// WeComWebhook is the API message for WeCom webhook.type WeComWebhook struct {MessageType string `json:"msgtype"`Markdown WeComWebhookMarkdown `json:"markdown"`@@ -28,10 +31,11 @@ func init() {register("bb.plugin.webhook.wecom", &WeComReceiver{})}+// WeComReceiver is the receiver for WeCom.type WeComReceiver struct {}-func (receiver *WeComReceiver) post(context WebhookContext) error {+func (receiver *WeComReceiver) post(context Context) error {metaStrList := []string{}for _, meta := range context.MetaList {metaStrList = append(metaStrList, fmt.Sprintf("%s: <font color=\"comment\">%s</font>", meta.Name, meta.Value))diff --git a/server/activity_manager.go b/server/activity_manager.goindex 8f8d7267e7..bfeef5ce0a 100644--- a/server/activity_manager.go+++ b/server/activity_manager.go@@ -110,8 +110,8 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activireturn activity, nil}-func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Activity, meta *ActivityMeta, updater *api.Principal) (webhook.WebhookContext, error) {- var webhookCtx webhook.WebhookContext+func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Activity, meta *ActivityMeta, updater *api.Principal) (webhook.Context, error) {+ var webhookCtx webhook.Contextlevel := webhook.WebhookInfotitle := ""link := fmt.Sprintf("%s:%d/issue/%s", m.s.frontendHost, m.s.frontendPort, api.IssueSlug(meta.issue))@@ -242,7 +242,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.A}}- metaList := []webhook.WebhookMeta{+ metaList := []webhook.Meta{{Name: "Issue",Value: meta.issue.Name,@@ -252,7 +252,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.AValue: meta.issue.Project.Name,},}- webhookCtx = webhook.WebhookContext{+ webhookCtx = webhook.Context{Level: level,Title: title,Description: activity.Comment,diff --git a/server/project_webhook.go b/server/project_webhook.goindex 47e2fe0c6c..b6628ba3c1 100644--- a/server/project_webhook.go+++ b/server/project_webhook.go@@ -219,7 +219,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {result := &api.ProjectWebhookTestResult{}err = webhook.Post(hook.Type,- webhook.WebhookContext{+ webhook.Context{URL: hook.URL,Level: webhook.WebhookInfo,Title: fmt.Sprintf("Test webhook %q", hook.Name),@@ -228,7 +228,7 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {CreatorName: "Bytebase",CreatorEmail: "[email protected]",CreatedTs: time.Now().Unix(),- MetaList: []webhook.WebhookMeta{+ MetaList: []webhook.Meta{{Name: "Project",Value: project.Name,diff --git a/server/server.go b/server/server.goindex dfa1faf5d8..aa338e0bb6 100644--- a/server/server.go+++ b/server/server.go@@ -7,6 +7,7 @@ import ("strings""time"+ // embed will embeds the acl policy._ "embed""github.com/bytebase/bytebase/api"diff --git a/server/sql.go b/server/sql.goindex 88cdd05171..9c0124de9b 100644--- a/server/sql.go+++ b/server/sql.go@@ -171,7 +171,7 @@ func (s *Server) syncEngineVersionAndSchema(ctx context.Context, instance *api.Ireturn nil}- var recreateTableSchema = func(database *api.Database, table db.DBTable) error {+ var recreateTableSchema = func(database *api.Database, table db.Table) error {// TabletableCreate := &api.TableCreate{CreatorID: api.SystemBotID,@@ -260,7 +260,7 @@ func (s *Server) syncEngineVersionAndSchema(ctx context.Context, instance *api.Ireturn nil}- var recreateViewSchema = func(database *api.Database, view db.DBView) error {+ var recreateViewSchema = func(database *api.Database, view db.View) error {// ViewviewCreate := &api.ViewCreate{CreatorID: api.SystemBotID,diff --git a/store/data_source.go b/store/data_source.goindex f45ef8da01..5096ceabd0 100644--- a/store/data_source.go+++ b/store/data_source.go@@ -46,6 +46,7 @@ func (s *DataSourceService) CreateDataSource(ctx context.Context, create *api.Dareturn dataSource, nil}+// CreateDataSourceTx creates a data source with a transaction.func (s *DataSourceService) CreateDataSourceTx(ctx context.Context, tx *sql.Tx, create *api.DataSourceCreate) (*api.DataSource, error) {return s.createDataSource(ctx, tx, create)}diff --git a/store/database.go b/store/database.goindex eb6b152899..1ea2925924 100644--- a/store/database.go+++ b/store/database.go@@ -57,6 +57,7 @@ func (s *DatabaseService) CreateDatabase(ctx context.Context, create *api.Databareturn database, nil}+// CreateDatabaseTx creates a database with a transaction.func (s *DatabaseService) CreateDatabaseTx(ctx context.Context, tx *sql.Tx, create *api.DatabaseCreate) (*api.Database, error) {backupPlanPolicy, err := s.policyService.GetBackupPlanPolicy(ctx, create.EnvironmentID)if err != nil {diff --git a/store/project_member.go b/store/project_member.goindex 69438d3412..1844f25fb6 100644--- a/store/project_member.go+++ b/store/project_member.go@@ -61,6 +61,7 @@ func (s *ProjectMemberService) FindProjectMemberList(ctx context.Context, find *return list, nil}+// FindProjectMember finds project members.func (s *ProjectMemberService) FindProjectMember(ctx context.Context, find *api.ProjectMemberFind) (*api.ProjectMember, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {diff --git a/store/sqlite.go b/store/sqlite.goindex f0e4335347..6958cd54c1 100644--- a/store/sqlite.go+++ b/store/sqlite.go@@ -13,7 +13,6 @@ import ("time""github.com/bytebase/bytebase/common"- _ "github.com/mattn/go-sqlite3""go.uber.org/zap")@@ -21,7 +20,7 @@ const (// We use SQLite "PRAGMA user_version" to manage the schema version. The schema version consists of// major version and minor version. Backward compatible schema change increases the minor version,// while backward non-compatible schema change increase the majar version.- // MAJOR_SCHEMA_VERSION and MAJOR_SCHEMA_VERSION defines the schema version this version of code can handle.+ // majorSchemaVervion and majorSchemaVervion defines the schema version this version of code can handle.// We reserve 4 least significant digits for minor version.// e.g.// 10001 -> Major verion 1, minor version 1@@ -39,8 +38,8 @@ const (// will require a separate process to upgrade the schema.// If the new release requires a higher MINOR version than the schema file, then it will apply the migration upon// startup.- MAJOR_SCHEMA_VERSION = 1- MINOR_SCHEMA_VERSION = 1+ majorSchemaVervion = 1+ minorSchemaVersion = 1)// If both debug and sqlite_trace build tags are enabled, then sqliteDriver will be set to "sqlite3_trace" in sqlite_trace.go@@ -226,8 +225,8 @@ func (db *DB) migrate() error {db.l.Info(fmt.Sprintf("Current schema version before migration: %s", curVer))// major version is 0 when the store isn't yet setup for the first time.- if curVer.major != 0 && curVer.major != MAJOR_SCHEMA_VERSION {- return fmt.Errorf("current major schema version %d is different from the major schema version %d this release %s expects", curVer.major, MAJOR_SCHEMA_VERSION, db.releaseVersion)+ if curVer.major != 0 && curVer.major != majorSchemaVervion {+ return fmt.Errorf("current major schema version %d is different from the major schema version %d this release %s expects", curVer.major, majorSchemaVervion, db.releaseVersion)}// Apply migrations@@ -263,12 +262,12 @@ func (db *DB) migrate() error {// This is a sanity check to prevent us setting the incorrect user_version in the migration script.// e.g. We set PRAGMA user_version = 20001 for migration script 20002__add_foo.sql- if curVer.major != MAJOR_SCHEMA_VERSION {- return fmt.Errorf("current schema major version %d does not match the expected schema major version %d after migration, make sure to set the correct PRAGMA user_version in the migration script", curVer.major, MAJOR_SCHEMA_VERSION)+ if curVer.major != majorSchemaVervion {+ return fmt.Errorf("current schema major version %d does not match the expected schema major version %d after migration, make sure to set the correct PRAGMA user_version in the migration script", curVer.major, majorSchemaVervion)}- if curVer.minor != MINOR_SCHEMA_VERSION {- return fmt.Errorf("current schema minor version %d does not match the expected schema minor version %d after migration, make sure to set the correct PRAGMA user_version in the migration script", curVer.minor, MINOR_SCHEMA_VERSION)+ if curVer.minor != minorSchemaVersion {+ return fmt.Errorf("current schema minor version %d does not match the expected schema minor version %d after migration, make sure to set the correct PRAGMA user_version in the migration script", curVer.minor, minorSchemaVersion)}db.l.Info("Completed database migration.")diff --git a/store/task_check_run.go b/store/task_check_run.goindex 39e20a6a38..4985d5da69 100644--- a/store/task_check_run.go+++ b/store/task_check_run.go@@ -21,12 +21,12 @@ type TaskCheckRunService struct {db *DB}-// newTaskCheckRunService returns a new TaskCheckRunService.+// NewTaskCheckRunService returns a new TaskCheckRunService.func NewTaskCheckRunService(logger *zap.Logger, db *DB) *TaskCheckRunService {return &TaskCheckRunService{l: logger, db: db}}-// CreateTaskCheckRun creates a new taskCheckRun. See interface for the expected behavior+// CreateTaskCheckRunIfNeeded creates a new taskCheckRun. See interface for the expected behaviorfunc (s *TaskCheckRunService) CreateTaskCheckRunIfNeeded(ctx context.Context, create *api.TaskCheckRunCreate) (*api.TaskCheckRun, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {diff --git a/store/task_run.go b/store/task_run.goindex db84bb84f1..a4b1e8e592 100644--- a/store/task_run.go+++ b/store/task_run.go@@ -21,7 +21,7 @@ type TaskRunService struct {db *DB}-// newTaskRunService returns a new TaskRunService.+// NewTaskRunService returns a new TaskRunService.func NewTaskRunService(logger *zap.Logger, db *DB) *TaskRunService {return &TaskRunService{l: logger, db: db}}