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: refactor history (#15139)
Danny Xu0b854ff8e61a
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sqlindex c417f65769..09b6fa20a2 100644--- a/backend/migrator/migration/LATEST.sql+++ b/backend/migrator/migration/LATEST.sql@@ -506,51 +506,14 @@ CREATE INDEX idx_issue_subscriber_subscriber_id ON issue_subscriber(subscriber_i-- instance change history records the changes an instance and its databases.CREATE TABLE instance_change_history (id BIGSERIAL PRIMARY KEY,- row_status row_status NOT NULL DEFAULT 'NORMAL',- creator_id INTEGER NOT NULL REFERENCES principal (id),created_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),- updater_id INTEGER NOT NULL REFERENCES principal (id),updated_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),- -- NULL means the migrations for Bytebase's own metadata database.- instance_id INTEGER REFERENCES instance (id),- -- NULL means an instance-level change.- database_id INTEGER REFERENCES db (id),- project_id INTEGER REFERENCES project (id),- -- issue_id is nullable because this field is backfilled and may not be present.- issue_id INTEGER REFERENCES issue (id),- -- Record the client version creating this change history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and this field helps to handle such situation properly. Moreover, it helps debugging.- release_version TEXT NOT NULL,- -- Used to detect out of order change history together with 'namespace' and 'version' column.- sequence BIGINT NOT NULL CONSTRAINT instance_change_history_sequence_check CHECK (sequence >= 0),- -- We call it source because maybe we could load history from other migration tool.- -- Currently allowed values are UI, VCS, LIBRARY.- source TEXT NOT NULL CONSTRAINT instance_change_history_source_check CHECK (source IN ('UI', 'VCS', 'LIBRARY')),- -- Currently allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.- type TEXT NOT NULL CONSTRAINT instance_change_history_type_check CHECK (type IN ('BASELINE', 'MIGRATE', 'MIGRATE_SDL', 'BRANCH', 'DATA')),- -- Currently allowed values are PENDING, DONE, FAILED.- -- PostgreSQL can't do cross database transaction, so we can't record DDL and change_history into a single transaction.- -- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.status TEXT NOT NULL CONSTRAINT instance_change_history_status_check CHECK (status IN ('PENDING', 'DONE', 'FAILED')),- -- Record the change version.version TEXT NOT NULL,- description TEXT NOT NULL,- -- Record the change statement in preview format.- statement TEXT NOT NULL,- -- Record the sheet for the change statement. Optional.- sheet_id BIGINT NULL,- -- Record the schema after change- schema TEXT NOT NULL,- -- Record the schema before change. Though we could also fetch it from the previous change history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the change history has any gaps.- schema_prev TEXT NOT NULL,- execution_duration_ns BIGINT NOT NULL,- payload JSONB NOT NULL DEFAULT '{}'+ execution_duration_ns BIGINT NOT NULL);-CREATE UNIQUE INDEX idx_instance_change_history_unique_instance_id_database_id_sequence ON instance_change_history (instance_id, database_id, sequence);--CREATE UNIQUE INDEX idx_instance_change_history_unique_instance_id_database_id_version ON instance_change_history (instance_id, database_id, version);+CREATE UNIQUE INDEX IF NOT EXISTS idx_instance_change_history_unique_version ON instance_change_history (version);ALTER SEQUENCE instance_change_history_id_seq RESTART WITH 101;diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.goindex a872060c66..b9201d102b 100644--- a/backend/migrator/migrator.go+++ b/backend/migrator/migrator.go@@ -18,11 +18,9 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"- api "github.com/bytebase/bytebase/backend/legacyapi"dbdriver "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/store/model"- "github.com/bytebase/bytebase/backend/utils"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -30,7 +28,7 @@ import (var migrationFS embed.FS// MigrateSchema migrates the schema for metadata database.-func MigrateSchema(ctx context.Context, storeDB *store.DB, storeInstance *store.Store, serverVersion string) (*semver.Version, error) {+func MigrateSchema(ctx context.Context, storeDB *store.DB, storeInstance *store.Store) (*semver.Version, error) {metadataDriver, err := dbdriver.Open(ctx,storepb.Engine_POSTGRES,@@ -52,10 +50,34 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, storeInstance *store.return nil, errors.Wrapf(err, "failed to get cutoff version")}slog.Info(fmt.Sprintf("The prod cutoff schema version: %s", cutoffSchemaVersion))- if err := initializeSchema(ctx, storeInstance, metadataDriver, cutoffSchemaVersion, serverVersion); err != nil {+ if err := initializeSchema(ctx, storeInstance, metadataDriver, cutoffSchemaVersion); err != nil {return nil, err}- if _, err := metadataDriver.GetDB().ExecContext(ctx, "ALTER TABLE instance_change_history ADD COLUMN IF NOT EXISTS project_id INTEGER REFERENCES project (id);"); err != nil {+ var c int+ err = metadataDriver.GetDB().QueryRowContext(ctx, "SELECT count(1) FROM instance_change_history WHERE database_id IS NOT NULL").Scan(c)+ if err != nil && c > 0 {+ return nil, errors.Errorf("Must upgrade to Bytebase 3.3.1 first")+ }+ if _, err := metadataDriver.GetDB().ExecContext(ctx, `+ ALTER TABLE instance_change_history+ DROP COLUMN IF EXISTS row_status,+ DROP COLUMN IF EXISTS creator_id,+ DROP COLUMN IF EXISTS updater_id,+ DROP COLUMN IF EXISTS instance_id,+ DROP COLUMN IF EXISTS database_id,+ DROP COLUMN IF EXISTS project_id,+ DROP COLUMN IF EXISTS issue_id,+ DROP COLUMN IF EXISTS release_version,+ DROP COLUMN IF EXISTS sequence,+ DROP COLUMN IF EXISTS source,+ DROP COLUMN IF EXISTS type,+ DROP COLUMN IF EXISTS description,+ DROP COLUMN IF EXISTS sheet_id,+ DROP COLUMN IF EXISTS statement,+ DROP COLUMN IF EXISTS schema,+ DROP COLUMN IF EXISTS schema_prev,+ DROP COLUMN IF EXISTS payload;+ CREATE UNIQUE INDEX IF NOT EXISTS idx_instance_change_history_unique_version ON instance_change_history (version);`); err != nil {return nil, err}@@ -64,15 +86,9 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, storeInstance *store.return nil, errors.Wrap(err, "failed to get current schema version")}- migrated, err := migrate(ctx, storeInstance, metadataDriver, verBefore, serverVersion, storeDB.ConnCfg.Database)- if err != nil {+ if _, err := migrate(ctx, storeInstance, metadataDriver, verBefore); err != nil {return nil, errors.Wrap(err, "failed to migrate")}- if migrated {- if err := backfillOracleSchema(ctx, storeInstance); err != nil {- return nil, errors.Wrap(err, "failed to backfill oracle schema")- }- }verAfter, err := getLatestVersion(ctx, storeInstance)if err != nil {@@ -83,7 +99,7 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, storeInstance *store.return &verAfter, nil}-func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataDriver dbdriver.Driver, cutoffSchemaVersion semver.Version, serverVersion string) error {+func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataDriver dbdriver.Driver, cutoffSchemaVersion semver.Version) error {// We use environment table to determine whether we've initialized the schema.var exists boolif err := metadataDriver.GetDB().QueryRowContext(ctx,@@ -120,24 +136,9 @@ func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataDreturn err}if err := storeInstance.CreateInstanceChangeHistoryForMigrator(ctx, &store.InstanceChangeHistoryMessage{- CreatorID: api.SystemBotID,- InstanceUID: nil,- DatabaseUID: nil,- ProjectUID: nil,- IssueUID: nil,- ReleaseVersion: serverVersion,- // Sequence starts from 1.- Sequence: 1,- Source: dbdriver.LIBRARY,- Type: dbdriver.Migrate,Status: dbdriver.Done,Version: version,- Description: fmt.Sprintf("Initial migration version %s server version %s with file %s.", cutoffSchemaVersion, serverVersion, latestSchemaPath),- Statement: stmt,- Schema: stmt,- SchemaPrev: "",ExecutionDurationNs: 0,- Payload: nil,}); err != nil {return err}@@ -194,11 +195,7 @@ func backfillSchemaObjectOwner(ctx context.Context, metadataDriver dbdriver.Driv// If there's no migration history, version will be nil.func getLatestVersion(ctx context.Context, storeInstance *store.Store) (semver.Version, error) {// We look back the past migration history records and return the latest successful (DONE) migration version.- histories, err := storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{- // Metadata database has instanceID nil;- InstanceID: nil,- ShowFull: true,- })+ histories, err := storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{})if err != nil {return semver.Version{}, errors.Wrap(err, "failed to get migration history")}@@ -208,19 +205,12 @@ func getLatestVersion(ctx context.Context, storeInstance *store.Store) (semver.Vfor _, h := range histories {if h.Status != dbdriver.Done {- stmt := h.Statement- // Only print out first 200 chars.- if len(stmt) > 200 {- stmt = stmt[:200]- }// Non-success migration history record is an anomaly, in the case where the actual// migration has been applied, the followup migration will likely fail because the// schema has already been applied. Thus emitting a warning here will assist debugging.- slog.Warn(fmt.Sprintf("Found %s migration history", h.Status),- slog.String("type", string(h.Type)),+ slog.Warn("Found stale migration history",+ slog.String("status", string(h.Status)),slog.String("version", h.Version.Version),- slog.String("description", h.Description),- slog.String("statement", stmt),)continue}@@ -247,7 +237,7 @@ const (// file run in a transaction to prevent partial migrations.//// The procedure follows https://github.com/bytebase/bytebase/blob/main/docs/schema-update-guide.md.-func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdriver.Driver, curVer semver.Version, serverVersion, databaseName string) (bool, error) {+func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdriver.Driver, curVer semver.Version) (bool, error) {slog.Info("Apply database migration if needed...")slog.Info(fmt.Sprintf("Current schema version before migration: %s", curVer))@@ -281,18 +271,7 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbd}slog.Info(fmt.Sprintf("Migrating %s...", pv.version))version := model.Version{Semantic: true, Version: pv.version.String(), Suffix: time.Now().Format("20060102150405")}- mi := &dbdriver.MigrationInfo{- InstanceID: nil,- CreatorID: api.SystemBotID,- ReleaseVersion: serverVersion,- Namespace: databaseName,- Database: databaseName,- Environment: "", /* unused in execute migration */- Source: dbdriver.LIBRARY,- Type: dbdriver.Migrate,- Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", pv.version, serverVersion, pv.filename),- }- if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, metadataDriver, mi, string(buf), version, dbdriver.ExecuteOptions{}); err != nil {+ if _, _, err := executeMigrationDefault(ctx, storeInstance, metadataDriver, string(buf), version); err != nil {return false, err}retVersion = pv.version@@ -425,48 +404,9 @@ func getMinorVersions(names []string) ([]semver.Version, error) {return versions, nil}-func backfillOracleSchema(ctx context.Context, stores *store.Store) error {- engine := storepb.Engine_ORACLE- databases, err := stores.ListDatabases(ctx, &store.FindDatabaseMessage{Engine: &engine})- if err != nil {- return err- }- for _, database := range databases {- dbSchema, err := stores.GetDBSchema(ctx, database.UID)- if err != nil {- return err- }- if dbSchema == nil {- continue- }- dbMetadata := dbSchema.GetMetadata()- if dbMetadata == nil {- continue- }- for _, schema := range dbMetadata.Schemas {- schema.Name = ""- }- if err := stores.UpsertDBSchema(ctx, database.UID, dbSchema, api.SystemBotID); err != nil {- return err- }- }- return nil-}-// executeMigrationDefault executes migration.-func executeMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, driver dbdriver.Driver, mi *dbdriver.MigrationInfo, statement string, version model.Version, opts dbdriver.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {- execFunc := func(ctx context.Context, execStatement string) error {- if _, err := driver.Execute(ctx, execStatement, opts); err != nil {- return err- }- return nil- }- return ExecuteMigrationWithFunc(ctx, driverCtx, store, mi, statement, version, execFunc, opts)-}--// ExecuteMigrationWithFunc executes the migration with custom migration function.-func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, m *dbdriver.MigrationInfo, statement string, version model.Version, execFunc func(ctx context.Context, execStatement string) error, _ dbdriver.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {- insertedID, err := BeginMigration(ctx, s, m, statement, version)+func executeMigrationDefault(ctx context.Context, stores *store.Store, driver dbdriver.Driver, statement string, version model.Version) (migrationHistoryID string, updatedSchema string, resErr error) {+ insertedID, err := beginMigration(ctx, stores, version)if err != nil {return "", "", errors.Wrapf(err, "failed to begin migration")}@@ -474,7 +414,7 @@ func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, sstartedNs := time.Now().UnixNano()defer func() {- if err := EndMigration(ctx, s, startedNs, insertedID, "" /* updatedSchema */, "" /* prevSchema */, nil /* sheetID */, resErr == nil /* isDone */); err != nil {+ if err := endMigration(ctx, stores, startedNs, insertedID, resErr == nil /* isDone */); err != nil {slog.Error("Failed to update migration history record",log.BBError(err),slog.String("migration_id", migrationHistoryID),@@ -482,65 +422,36 @@ func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s}}()- // Phase 3 - Executing migration- // Branch migration type always has empty sql.- // Baseline migration type could has non-empty sql but will not execute.- // https://github.com/bytebase/bytebase/issues/394- doMigrate := true- if statement == "" || m.Type == dbdriver.Baseline {- doMigrate = false- }- if doMigrate {- renderedStatement := statement- // The m.DatabaseID is nil means the migration is a instance level migration- if m.DatabaseID != nil {- database, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{- UID: m.DatabaseID,- })- if err != nil {- return "", "", err- }- if database == nil {- return "", "", errors.Errorf("database %d not found", *m.DatabaseID)- }- materials := utils.GetSecretMapFromDatabaseMessage(database)- // To avoid leak the rendered statement, the error message should use the original statement and not the rendered statement.- renderedStatement = utils.RenderStatement(statement, materials)- }-- if err := execFunc(driverCtx, renderedStatement); err != nil {- return "", "", err- }+ if _, err := driver.Execute(ctx, statement, dbdriver.ExecuteOptions{}); err != nil {+ return "", "", err}return insertedID, "", nil}-// BeginMigration checks before executing migration and inserts a migration history record with pending status.-func BeginMigration(ctx context.Context, stores *store.Store, m *dbdriver.MigrationInfo, statement string, version model.Version) (string, error) {+// beginMigration checks before executing migration and inserts a migration history record with pending status.+func beginMigration(ctx context.Context, stores *store.Store, version model.Version) (string, error) {// Phase 1 - Pre-check before executing migration// Check if the same migration version has already been applied.if list, err := stores.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{- InstanceID: m.InstanceID,- DatabaseID: m.DatabaseID,- Version: &version,+ Version: &version,}); err != nil {return "", errors.Wrap(err, "failed to check duplicate version")} else if len(list) > 0 {migrationHistory := list[0]switch migrationHistory.Status {case dbdriver.Done:- err := common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", m.Database, version.Version)+ err := common.Errorf(common.MigrationAlreadyApplied, "already applied version %s, hint: the version might be duplicate, please check the version", version.Version)slog.Debug(err.Error())// Force migrationreturn migrationHistory.UID, nilcase dbdriver.Pending:- err := errors.Errorf("database %q version %s migration is already in progress", m.Database, version.Version)+ err := errors.Errorf("version %s migration is already in progress", version.Version)slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.return migrationHistory.UID, nilcase dbdriver.Failed:- err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", m.Database, version.Version)+ err := errors.Errorf("version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", version.Version)slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.return migrationHistory.UID, nil@@ -548,8 +459,7 @@ func BeginMigration(ctx context.Context, stores *store.Store, m *dbdriver.Migrat}// Phase 2 - Record migration history as PENDING.- statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)- insertedID, err := stores.CreatePendingInstanceChangeHistoryForMigrator(ctx, "" /* prevSchema */, m, statementRecord, nil /* sheetID */, version)+ insertedID, err := stores.CreatePendingInstanceChangeHistoryForMigrator(ctx, version)if err != nil {return "", err}@@ -557,22 +467,17 @@ func BeginMigration(ctx context.Context, stores *store.Store, m *dbdriver.Migratreturn insertedID, nil}-// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.-func EndMigration(ctx context.Context, storeInstance *store.Store, startedNs int64, insertedID string, updatedSchema, schemaPrev string, sheetID *int, isDone bool) error {+// endMigration updates the migration history record to DONE or FAILED depending on migration is done or not.+func endMigration(ctx context.Context, storeInstance *store.Store, startedNs int64, insertedID string, isDone bool) error {migrationDurationNs := time.Now().UnixNano() - startedNsupdate := &store.UpdateInstanceChangeHistoryMessage{ID: insertedID,ExecutionDurationNs: &migrationDurationNs,- // Update the sheet ID just in case it has been updated.- Sheet: sheetID,- // Update schemaPrev because we might be re-using a previous change history entry.- SchemaPrev: &schemaPrev,}if isDone {// Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.status := dbdriver.Doneupdate.Status = &status- update.Schema = &updatedSchema} else {// Otherwise, update the migration history as 'FAILED', execution_duration.status := dbdriver.Faileddiff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex b9930e986d..77e0dbf0bd 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -139,8 +139,7 @@ func TestGetPatchVersions(t *testing.T) {}var (- pgPort = 6000- serverVersion = "server-version"+ pgPort = 6000)func TestMigrationCompatibility(t *testing.T) {@@ -193,23 +192,19 @@ func TestMigrationCompatibility(t *testing.T) {require.NoError(t, err)// Create initial schema.- err = initializeSchema(ctx, storeInstance, metadataDriver, releaseVersion, serverVersion)+ err = initializeSchema(ctx, storeInstance, metadataDriver, releaseVersion)require.NoError(t, err)// Check migration history.- histories, err := storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{- InstanceID: nil,- })+ histories, err := storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{})require.NoError(t, err)require.Len(t, histories, 1)require.Equal(t, histories[0].Version.Version, releaseVersion.String())// Check no migration after passing current version as the release cutoff version.- _, err = migrate(ctx, storeInstance, metadataDriver, releaseVersion, serverVersion, databaseName)+ _, err = migrate(ctx, storeInstance, metadataDriver, releaseVersion)require.NoError(t, err)// Check migration history.- histories, err = storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{- InstanceID: nil,- })+ histories, err = storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{})require.NoError(t, err)require.Len(t, histories, 1)}diff --git a/backend/plugin/db/sqlite/sqlite_migration_schema.sql b/backend/plugin/db/sqlite/sqlite_migration_schema.sqldeleted file mode 100644index c56b2191df..0000000000--- a/backend/plugin/db/sqlite/sqlite_migration_schema.sql+++ /dev/null@@ -1,45 +0,0 @@--- Create migration_history table-CREATE TABLE bytebase_migration_history (- id INTEGER PRIMARY KEY AUTOINCREMENT,- created_by TEXT NOT NULL,- created_ts INTEGER NOT NULL,- updated_by TEXT NOT NULL,- updated_ts INTEGER NOT NULL,- -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might- -- record different history info and thie field helps to handle such situation properly. Moreover, it helps debugging.- release_version TEXT NOT NULL,- -- Allows granular tracking of migration history (e.g If an application manages schemas for a multi-tenant service and each tenant has its own schema, that application can use namespace to record the tenant name to track the per-tenant schema migration)- -- Since bytebase also manages different application databases from an instance, it leverages this field to track each database migration history.- namespace TEXT NOT NULL,- -- Used to detect out of order migration together with 'namespace' and 'version' column.- sequence INTEGER UNSIGNED NOT NULL,- -- We call it source because maybe we could load history from other migration tool.- -- Current allowed values are UI, VCS, LIBRARY.- source TEXT NOT NULL,- -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.- type TEXT NOT NULL,- -- Current allowed values are PENDING, DONE, FAILED.- -- We create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- status TEXT NOT NULL,- -- Record the migration version.- version TEXT NOT NULL,- description TEXT NOT NULL,- -- Record the migration statement- statement TEXT NOT NULL,- -- Record the schema after migration- schema MEDIUMTEXT NOT NULL,- -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.- schema_prev MEDIUMTEXT NOT NULL,- execution_duration_ns INTEGER NOT NULL,- issue_id TEXT NOT NULL,- payload TEXT NOT NULL-);--CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_sequence ON bytebase_migration_history (namespace, sequence);--CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON bytebase_migration_history (namespace, version);--CREATE INDEX bytebase_idx_migration_history_namespace_source_type ON bytebase_migration_history(namespace, source, type);--CREATE INDEX bytebase_idx_migration_history_namespace_created ON bytebase_migration_history(namespace, created_ts);diff --git a/backend/server/server.go b/backend/server/server.goindex f434d1a2a2..49516db7c3 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -205,7 +205,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {if err := demo.LoadDemoDataIfNeeded(ctx, storeDB, profile.DemoName); err != nil {return nil, errors.Wrapf(err, "failed to load demo data")}- if _, err := migrator.MigrateSchema(ctx, storeDB, storeInstance, profile.Version); err != nil {+ if _, err := migrator.MigrateSchema(ctx, storeDB, storeInstance); err != nil {return nil, err}}diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.goindex 26f61347eb..b908cb9728 100644--- a/backend/store/instance_change_history.go+++ b/backend/store/instance_change_history.go@@ -6,69 +6,26 @@ import ("fmt""strings"- "google.golang.org/protobuf/encoding/protojson"-- "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/store/model"- storepb "github.com/bytebase/bytebase/proto/generated-go/store")// InstanceChangeHistoryMessage records the change history of an instance.// it deprecates the old MigrationHistory.type InstanceChangeHistoryMessage struct {- CreatorID int- CreatedTs int64- UpdaterID int- UpdatedTs int64- // nil means bytebase meta instance.- InstanceUID *int- DatabaseUID *int- ProjectUID *int- IssueUID *int- ReleaseVersion string- Sequence int64- Source db.MigrationSource- Type db.MigrationType+ CreatedTs int64+ UpdatedTs int64Status db.MigrationStatusVersion model.Version- Description string- Statement string- StatementSize int64- SheetID *int- Schema string- SchemaSize int64- SchemaPrev string- SchemaPrevSize int64ExecutionDurationNs int64- Payload *storepb.InstanceChangeHistoryPayload// Output only- UID string- Deleted bool- Creator *UserMessage- Updater *UserMessage- InstanceID string- DatabaseName string+ UID string}// FindInstanceChangeHistoryMessage is for listing a list of instance change history.type FindInstanceChangeHistoryMessage struct {- ID *string- InstanceID *int- DatabaseID *int- SheetID *int- Source *db.MigrationSource- Status *db.MigrationStatus- Version *model.Version- TypeList []db.MigrationType- ResourcesFilter *string- Limit *int- Offset *int-- // Truncate Statement, Schema, SchemaPrev unless ShowFull.- ShowFull bool- TruncateSize int+ Version *model.Version}// UpdateInstanceChangeHistoryMessage is for updating an instance change history.@@ -77,9 +34,6 @@ type UpdateInstanceChangeHistoryMessage struct {Status *db.MigrationStatusExecutionDurationNs *int64- Schema *string- SchemaPrev *string- Sheet *int}// CreateInstanceChangeHistoryForMigrator creates an instance change history for migrator.@@ -96,67 +50,27 @@ func (s *Store) CreateInstanceChangeHistoryForMigrator(ctx context.Context, creareturn tx.Commit()}-func (*Store) createInstanceChangeHistoryImpl(ctx context.Context, tx *Tx, create *InstanceChangeHistoryMessage) (string, error) {- query := `- INSERT INTO instance_change_history (- creator_id,- updater_id,- instance_id,- database_id,- project_id,- issue_id,- release_version,- sequence,- source,- type,- status,- version,- description,- statement,- "schema",- sheet_id,- schema_prev,- execution_duration_ns,- payload- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)- RETURNING id`-- payload, err := protojson.Marshal(create.Payload)+// CreatePendingInstanceChangeHistory creates an instance change history.+func (s *Store) CreatePendingInstanceChangeHistoryForMigrator(ctx context.Context, version model.Version) (string, error) {+ tx, err := s.db.BeginTx(ctx, nil)if err != nil {return "", err}- storedVersion, err := create.Version.Marshal()+ defer tx.Rollback()++ instanceChange := &InstanceChangeHistoryMessage{+ Status: db.Pending,+ Version: version,+ ExecutionDurationNs: 0,+ }+ var uid string+ id, err := s.createInstanceChangeHistoryImplForMigrator(ctx, tx, instanceChange)if err != nil {return "", err}+ uid = id- statement := create.Statement- if create.SheetID != nil {- statement = ""- }-- var uid string- if err := tx.QueryRowContext(ctx, query,- create.CreatorID,- create.CreatorID,- create.InstanceUID,- create.DatabaseUID,- create.ProjectUID,- create.IssueUID,- create.ReleaseVersion,- create.Sequence,- create.Source,- create.Type,- create.Status,- storedVersion,- create.Description,- statement,- create.Schema,- create.SheetID,- create.SchemaPrev,- create.ExecutionDurationNs,- payload,- ).Scan(&uid); err != nil {+ if err := tx.Commit(); err != nil {return "", err}@@ -166,31 +80,12 @@ func (*Store) createInstanceChangeHistoryImpl(ctx context.Context, tx *Tx, creatfunc (*Store) createInstanceChangeHistoryImplForMigrator(ctx context.Context, tx *Tx, create *InstanceChangeHistoryMessage) (string, error) {query := `INSERT INTO instance_change_history (- creator_id,- updater_id,- instance_id,- database_id,- project_id,- issue_id,- release_version,- sequence,- source,- type,status,version,- description,- statement,- "schema",- schema_prev,- execution_duration_ns,- payload- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)+ execution_duration_ns+ ) VALUES ($1, $2, $3)RETURNING id`- payload, err := protojson.Marshal(create.Payload)- if err != nil {- return "", err- }storedVersion, err := create.Version.Marshal()if err != nil {return "", err@@ -198,24 +93,9 @@ func (*Store) createInstanceChangeHistoryImplForMigrator(ctx context.Context, txvar uid stringif err := tx.QueryRowContext(ctx, query,- create.CreatorID,- create.CreatorID,- create.InstanceUID,- create.DatabaseUID,- create.ProjectUID,- create.IssueUID,- create.ReleaseVersion,- create.Sequence,- create.Source,- create.Type,create.Status,storedVersion,- create.Description,- create.Statement,- create.Schema,- create.SchemaPrev,create.ExecutionDurationNs,- payload,).Scan(&uid); err != nil {return "", err}@@ -233,15 +113,6 @@ func (s *Store) UpdateInstanceChangeHistory(ctx context.Context, update *UpdateIif v := update.ExecutionDurationNs; v != nil {set, args = append(set, fmt.Sprintf("execution_duration_ns = $%d", len(args)+1)), append(args, *v)}- if v := update.Schema; v != nil {- set, args = append(set, fmt.Sprintf("schema = $%d", len(args)+1)), append(args, *v)- }- if v := update.SchemaPrev; v != nil {- set, args = append(set, fmt.Sprintf("schema_prev = $%d", len(args)+1)), append(args, *v)- }- if v := update.Sheet; v != nil {- set, args = append(set, fmt.Sprintf("sheet_id = $%d", len(args)+1)), append(args, *v)- }if len(set) == 0 {return nil}@@ -264,157 +135,27 @@ func (s *Store) UpdateInstanceChangeHistory(ctx context.Context, update *UpdateIreturn tx.Commit()}-func (*Store) getNextInstanceChangeHistorySequence(ctx context.Context, tx *Tx, instanceID *int, databaseID *int) (int64, error) {- where, args := []string{"TRUE"}, []any{}- if instanceID != nil && databaseID != nil {- where, args = append(where, fmt.Sprintf("instance_id = $%d", len(args)+1)), append(args, *instanceID)- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *databaseID)- } else {- where = append(where, "instance_id is NULL AND database_id is NULL")- }-- query := `- SELECT- COALESCE(MAX(sequence), 0)+1- FROM instance_change_history- WHERE ` + strings.Join(where, " AND ")- var sequence int64- if err := tx.QueryRowContext(ctx, query, args...).Scan(&sequence); err != nil {- return 0, err- }- return sequence, nil-}--// CreatePendingInstanceChangeHistory creates an instance change history.-func (s *Store) CreatePendingInstanceChangeHistoryForMigrator(ctx context.Context, prevSchema string, m *db.MigrationInfo, statement string, sheetID *int, version model.Version) (string, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return "", err- }- defer tx.Rollback()-- nextSequence, err := s.getNextInstanceChangeHistorySequence(ctx, tx, m.InstanceID, m.DatabaseID)- if err != nil {- return "", err- }- instanceChange := &InstanceChangeHistoryMessage{- CreatorID: m.CreatorID,- InstanceUID: m.InstanceID,- DatabaseUID: m.DatabaseID,- ProjectUID: m.ProjectUID,- IssueUID: m.IssueUID,- ReleaseVersion: m.ReleaseVersion,- Sequence: nextSequence,- Source: m.Source,- Type: m.Type,- Status: db.Pending,- Version: version,- Description: m.Description,- Statement: statement,- SheetID: sheetID,- Schema: prevSchema,- SchemaPrev: prevSchema,- ExecutionDurationNs: 0,- Payload: m.Payload,- }- var uid string- if instanceChange.InstanceUID == nil {- id, err := s.createInstanceChangeHistoryImplForMigrator(ctx, tx, instanceChange)- if err != nil {- return "", err- }- uid = id- } else {- id, err := s.createInstanceChangeHistoryImpl(ctx, tx, instanceChange)- if err != nil {- return "", err- }- uid = id- }-- if err := tx.Commit(); err != nil {- return "", err- }-- return uid, nil-}--// ListInstanceChangeHistoryForMigrator finds the instance change history for the migrator,-// the users are not composed.-// The sheet_id is not loaded.+// ListInstanceChangeHistoryForMigrator finds the instance change history for the migrator.func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *FindInstanceChangeHistoryMessage) ([]*InstanceChangeHistoryMessage, error) {where, args := []string{"TRUE"}, []any{}- if v := find.ID; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.id = $%d", len(args)+1)), append(args, *v)- }- if v := find.InstanceID; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.instance_id = $%d", len(args)+1)), append(args, *v)- } else {- where = append(where, "instance_change_history.instance_id is NULL AND instance_change_history.database_id is NULL")- }- if v := find.DatabaseID; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.database_id = $%d", len(args)+1)), append(args, *v)- }- if v := find.Source; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.source = $%d", len(args)+1)), append(args, *v)- }if v := find.Version; v != nil {storedVersion, err := find.Version.Marshal()if err != nil {return nil, err}- where, args = append(where, fmt.Sprintf("instance_change_history.version = $%d", len(args)+1)), append(args, storedVersion)- }-- statementField := "instance_change_history.statement"- if !find.ShowFull {- statementField = fmt.Sprintf("LEFT(%s, %d)", statementField, find.TruncateSize)- }- schemaField := "instance_change_history.schema"- if !find.ShowFull {- schemaField = fmt.Sprintf("LEFT(%s, %d)", schemaField, find.TruncateSize)- }- schemaPrevField := "instance_change_history.schema_prev"- if !find.ShowFull {- schemaPrevField = fmt.Sprintf("LEFT(%s, %d)", schemaPrevField, find.TruncateSize)+ where, args = append(where, fmt.Sprintf("version = $%d", len(args)+1)), append(args, storedVersion)}- query := fmt.Sprintf(`+ query := `SELECT- instance_change_history.id,- instance_change_history.row_status,- instance_change_history.creator_id,- instance_change_history.created_ts,- instance_change_history.updater_id,- instance_change_history.updated_ts,- instance_change_history.instance_id,- instance_change_history.database_id,- instance_change_history.project_id,- instance_change_history.issue_id,- instance_change_history.release_version,- instance_change_history.sequence,- instance_change_history.source,- instance_change_history.type,- instance_change_history.status,- instance_change_history.version,- instance_change_history.description,- %s,- %s,- %s,- instance_change_history.execution_duration_ns,- instance_change_history.payload,- COALESCE(instance.resource_id, ''),- COALESCE(db.name, '')+ id,+ created_ts,+ updated_ts,+ status,+ version,+ execution_duration_nsFROM instance_change_history- LEFT JOIN instance on instance.id = instance_change_history.instance_id- LEFT JOIN db on db.id = instance_change_history.database_id- WHERE `+strings.Join(where, " AND ")+` ORDER BY instance_change_history.instance_id, instance_change_history.database_id, instance_change_history.sequence DESC`, statementField, schemaField, schemaPrevField)- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }- if v := find.Offset; v != nil {- query += fmt.Sprintf(" OFFSET %d", *v)- }+ WHERE ` + strings.Join(where, " AND ") + ` ORDER BY id DESC`tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})if err != nil {@@ -431,63 +172,23 @@ func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *var list []*InstanceChangeHistoryMessagefor rows.Next() {var changeHistory InstanceChangeHistoryMessage- var rowStatus, storedVersion, payload string- var instanceID, databaseID, projectID, issueID sql.NullInt32+ var storedVersion stringif err := rows.Scan(&changeHistory.UID,- &rowStatus,- &changeHistory.CreatorID,&changeHistory.CreatedTs,- &changeHistory.UpdaterID,&changeHistory.UpdatedTs,- &instanceID,- &databaseID,- &projectID,- &issueID,- &changeHistory.ReleaseVersion,- &changeHistory.Sequence,- &changeHistory.Source,- &changeHistory.Type,&changeHistory.Status,&storedVersion,- &changeHistory.Description,- &changeHistory.Statement,- &changeHistory.Schema,- &changeHistory.SchemaPrev,&changeHistory.ExecutionDurationNs,- &payload,- &changeHistory.InstanceID,- &changeHistory.DatabaseName,); err != nil {return nil, err}- if instanceID.Valid {- n := int(instanceID.Int32)- changeHistory.InstanceUID = &n- }- if databaseID.Valid {- n := int(databaseID.Int32)- changeHistory.DatabaseUID = &n- }- if projectID.Valid {- n := int(projectID.Int32)- changeHistory.ProjectUID = &n- }- if issueID.Valid {- n := int(issueID.Int32)- changeHistory.IssueUID = &n- }- changeHistory.Payload = &storepb.InstanceChangeHistoryPayload{}- if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(payload), changeHistory.Payload); err != nil {- return nil, err- }version, err := model.NewVersion(storedVersion)if err != nil {return nil, err}changeHistory.Version = version- changeHistory.Deleted = convertRowStatusToDeleted(rowStatus)list = append(list, &changeHistory)}if err := rows.Err(); err != nil {diff --git a/docs/README.md b/docs/README.mdindex 5d1b91749d..af24844945 100644--- a/docs/README.md+++ b/docs/README.md@@ -2,6 +2,6 @@## Helm Chart-bytebase-1.0.0.tgz and index.yaml is to host template for https://artifacthub.io/packages/helm/bytebase/bytebase.+bytebase-*.tgz and index.yaml is to host template for https://artifacthub.io/packages/helm/bytebase/bytebase.We use GitHub Pages as the web server to host Helm content and GitHub only allows to put the content under `/` or `/docs`.\ No newline at end of filediff --git a/docs/assets/codereview1.png b/docs/assets/codereview1.pngdeleted file mode 100644index 130049e660..0000000000Binary files a/docs/assets/codereview1.png and /dev/null differdiff --git a/docs/assets/codereview2.png b/docs/assets/codereview2.pngdeleted file mode 100644index fa8ae74daa..0000000000Binary files a/docs/assets/codereview2.png and /dev/null differdiff --git a/docs/assets/data-model-v1.webp b/docs/assets/data-model-v1.webpdeleted file mode 100644index 2fb3691ee0..0000000000Binary files a/docs/assets/data-model-v1.webp and /dev/null differdiff --git a/docs/assets/old-to-new-world.webp b/docs/assets/old-to-new-world.webpdeleted file mode 100644index 9a59b428eb..0000000000Binary files a/docs/assets/old-to-new-world.webp and /dev/null differdiff --git a/docs/assets/preview-env1.png b/docs/assets/preview-env1.pngdeleted file mode 100644index 7db2907501..0000000000Binary files a/docs/assets/preview-env1.png and /dev/null differdiff --git a/docs/assets/preview-env2.png b/docs/assets/preview-env2.pngdeleted file mode 100644index 17a3f510dc..0000000000Binary files a/docs/assets/preview-env2.png and /dev/null differdiff --git a/docs/assets/reset-bytebase-data.png b/docs/assets/reset-bytebase-data.pngdeleted file mode 100644index 11bc8a2e94..0000000000Binary files a/docs/assets/reset-bytebase-data.png and /dev/null differdiff --git a/docs/assets/sql-editor-admin-mode.webp b/docs/assets/sql-editor-admin-mode.webpdeleted file mode 100644index c1c4af0d0a..0000000000Binary files a/docs/assets/sql-editor-admin-mode.webp and /dev/null differdiff --git a/docs/assets/staging-env1.png b/docs/assets/staging-env1.pngdeleted file mode 100644index 78ed9d44c2..0000000000Binary files a/docs/assets/staging-env1.png and /dev/null differdiff --git a/docs/assets/versioncontrol.webp b/docs/assets/versioncontrol.webpdeleted file mode 100644index a59afdd5be..0000000000Binary files a/docs/assets/versioncontrol.webp and /dev/null differdiff --git a/docs/design/README.md b/docs/design/README.mddeleted file mode 100644index 9e9b59a7f8..0000000000--- a/docs/design/README.md+++ /dev/null@@ -1,3 +0,0 @@-# Bytebase Design Docs--This folder contains Bytebase design docs and related assets.diff --git a/docs/design/assets/code-structure.png b/docs/design/assets/code-structure.pngdeleted file mode 100644index cc984811d1..0000000000Binary files a/docs/design/assets/code-structure.png and /dev/null differdiff --git a/docs/design/assets/gh-ost-general-flow.png b/docs/design/assets/gh-ost-general-flow.pngdeleted file mode 100644index 77613a2a22..0000000000Binary files a/docs/design/assets/gh-ost-general-flow.png and /dev/null differdiff --git a/docs/design/assets/gh-ost-operation-modes.png b/docs/design/assets/gh-ost-operation-modes.pngdeleted file mode 100644index 415e0fb9dc..0000000000Binary files a/docs/design/assets/gh-ost-operation-modes.png and /dev/null differdiff --git a/docs/design/assets/sql-review-overview.webp b/docs/design/assets/sql-review-overview.webpdeleted file mode 100644index 344ef92425..0000000000Binary files a/docs/design/assets/sql-review-overview.webp and /dev/null differdiff --git a/docs/design/db-plugin-development-guide.md b/docs/design/db-plugin-development-guide.mddeleted file mode 100644index e65c904bfd..0000000000--- a/docs/design/db-plugin-development-guide.md+++ /dev/null@@ -1,15 +0,0 @@-# DB Plugin Development Guide--This document introduces how to develop a database plugin for Bytebase.--## Concepts--Internally, Bytebase creates a table in database to record migration history.--## Develop a plugin-1. Under `plugin/db`, create a go package named driver's name.-1. Implement `github.com/bytebase/bytebase/backend/plugin/db#Driver` interface.-1. \[Optional\] There are some common implementations in package `github.com/bytebase/bytebase/backend/plugin/db/util`. To use these utils, additional adapters are needed usually.-- For instance, `util#ExecuteMigration` is a helper function to implement `db.Driver#ExecuteMigration`. And this function needs a `util.MigrationExecutor` adapter.-1. Register plugin. In `init()` function, call `github.com/bytebase/bytebase/backend/plugin/db#Register` to register plugin factory with specific db type.diff --git a/docs/design/gh-ost-integration.md b/docs/design/gh-ost-integration.mddeleted file mode 100644index 4433a1521e..0000000000--- a/docs/design/gh-ost-integration.md+++ /dev/null@@ -1,469 +0,0 @@-# gh-ost integration--## Overview--Currently, Bytebase runs DDL statements directly on databases. With this feature, users can choose to use gh-ost to migrate MySQL versions 5.6 or greater.--### gh-ost: a brief introduction (quoted from gh-ost docs)--> gh-ost is a triggerless online schema migration solution for MySQL. It is testable and provides pausability, dynamic control/reconfiguration, auditing, and many operational perks.--gh-ost has three operation modes. It's recommended to connect to replica and migrate on primary (master). See the picture below.----Here's how gh-ost migrates.----You can find usage in this [cheatsheet](https://github.com/github/gh-ost/blob/master/doc/cheatsheet.md). Below is an example.--```Bash-gh-ost \---max-load=Threads_running=25 \---critical-load=Threads_running=1000 \---chunk-size=1000 \---throttle-control-replicas="myreplica.1.com,myreplica.2.com" \---max-lag-millis=1500 \---user="gh-ost" \---password="123456" \---host=replica.with.rbr.com \---database="my_schema" \---table="my_table" \---verbose \---alter="engine=innodb" \---switch-to-rbr \---allow-master-master \---cut-over=default \---exact-rowcount \---concurrent-rowcount \---default-retries=120 \---panic-flag-file=/tmp/ghost.panic.flag \---postpone-cut-over-flag-file=/tmp/ghost.postpone.flag \-[--execute]-```--gh-ost uses the same user and password discovering the replication topology if `master-user` and `master-password` are not provided. It's the user's responsibility to set up a dedicated user with the necessary privileges for replication and gh-ost.--If gh-ost crashes halfway, we drop the two tables created by gh-ost.--- `_yourtablename_gho`-- `_yourtablename_ghc`--After migration, we will have `yourtablename` and `_yourtablename_del`. The latter is the original table. We will ask the user to drop the original table.--Below is the output of running gh-ost on my local machine.--```Plaintext--> % ./gh-ost --user="replica" --password="replica" --host=127.0.0.1 --port=3307 --database="db" --table="person" --alter="engine=innodb" --execute --verbose --assume-rbr-2022-03-07 09:49:39 INFO starting gh-ost 1.1.4-2022-03-07 09:49:39 INFO Migrating `db`.`person`-2022-03-07 09:49:39 INFO inspector connection validated on 127.0.0.1:3307-2022-03-07 09:49:39 INFO User has REPLICATION CLIENT, REPLICATION SLAVE privileges, and has ALL privileges on `db`.*-2022-03-07 09:49:39 INFO binary logs validated on 127.0.0.1:3307-2022-03-07 09:49:39 INFO Inspector initiated on MacBook-Air-2.local:3307, version 8.0.27-2022-03-07 09:49:39 INFO Table found. Engine=InnoDB-2022-03-07 09:49:39 INFO Estimated number of rows via EXPLAIN: 2-2022-03-07 09:49:39 INFO Recursively searching for replication master-2022-03-07 09:49:39 INFO Master found to be 127.0.0.1:3306-2022-03-07 09:49:39 INFO log_slave_updates validated on 127.0.0.1:3307-2022-03-07 09:49:39 INFO streamer connection validated on 127.0.0.1:3307-[2022/03/07 09:49:39] [info] binlogsyncer.go:133 create BinlogSyncer with config {99999 mysql 127.0.0.1 3307 replica false false <nil> false UTC true 0 0s 0s 0 false}-2022-03-07 09:49:39 INFO Connecting binlog streamer at binlog.000001:67556-[2022/03/07 09:49:39] [info] binlogsyncer.go:354 begin to sync binlog from position (binlog.000001, 67556)-[2022/03/07 09:49:39] [info] binlogsyncer.go:203 register slave for master server 127.0.0.1:3307-[2022/03/07 09:49:39] [info] binlogsyncer.go:723 rotate to (binlog.000001, 67556)-2022-03-07 09:49:39 INFO rotate to next log from binlog.000001:0 to binlog.000001-2022-03-07 09:49:39 INFO applier connection validated on 127.0.0.1:3306-2022-03-07 09:49:39 INFO applier connection validated on 127.0.0.1:3306-2022-03-07 09:49:39 INFO will use time_zone='SYSTEM' on applier-2022-03-07 09:49:39 INFO Examining table structure on applier-2022-03-07 09:49:39 INFO Applier initiated on MacBook-Air-2.local:3306, version 8.0.27-2022-03-07 09:49:39 INFO Dropping table `db`.`_person_ghc`-2022-03-07 09:49:39 INFO Table dropped-2022-03-07 09:49:39 INFO Creating changelog table `db`.`_person_ghc`-2022-03-07 09:49:39 INFO Changelog table created-2022-03-07 09:49:39 INFO Creating ghost table `db`.`_person_gho`-2022-03-07 09:49:39 INFO Ghost table created-2022-03-07 09:49:39 INFO Altering ghost table `db`.`_person_gho`-2022-03-07 09:49:39 INFO Ghost table altered-2022-03-07 09:49:39 INFO Waiting for ghost table to be migrated. Current lag is 0s-2022-03-07 09:49:39 INFO Intercepted changelog state GhostTableMigrated-2022-03-07 09:49:39 INFO Handled changelog state GhostTableMigrated-2022-03-07 09:49:39 INFO Chosen shared unique key is PRIMARY-2022-03-07 09:49:39 INFO Shared columns are id,name,city-2022-03-07 09:49:39 INFO Listening on unix socket file: /tmp/gh-ost.db.person.sock-2022-03-07 09:49:39 INFO Migration min values: [1]-2022-03-07 09:49:39 INFO Migration max values: [2]-2022-03-07 09:49:39 INFO Waiting for first throttle metrics to be collected-2022-03-07 09:49:39 INFO First throttle metrics collected-# Migrating `db`.`person`; Ghost table is `db`.`_person_gho`-# Migrating MacBook-Air-2.local:3306; inspecting MacBook-Air-2.local:3307; executing on MacBook-Air-2.local-# Migration started at Mon Mar 07 09:49:39 +0800 2022-# chunk-size: 1000; max-lag-millis: 1500ms; dml-batch-size: 10; max-load: ; critical-load: ; nice-ratio: 0.000000-# throttle-additional-flag-file: /tmp/gh-ost.throttle-# Serving on unix socket: /tmp/gh-ost.db.person.sock-Copy: 0/2 0.0%; Applied: 0; Backlog: 0/1000; Time: 0s(total), 0s(copy); streamer: binlog.000001:69738; Lag: 0.01s, HeartbeatLag: 0.01s, State: migrating; ETA: N/A-Copy: 0/2 0.0%; Applied: 0; Backlog: 0/1000; Time: 1s(total), 1s(copy); streamer: binlog.000001:74240; Lag: 0.01s, HeartbeatLag: 0.01s, State: migrating; ETA: N/A-2022-03-07 09:49:41 INFO Row copy complete-Copy: 2/2 100.0%; Applied: 0; Backlog: 0/1000; Time: 1s(total), 1s(copy); streamer: binlog.000001:75062; Lag: 0.01s, HeartbeatLag: 0.02s, State: migrating; ETA: due-2022-03-07 09:49:41 INFO Grabbing voluntary lock: gh-ost.94.lock-2022-03-07 09:49:41 INFO Setting LOCK timeout as 6 seconds-2022-03-07 09:49:41 INFO Looking for magic cut-over table-2022-03-07 09:49:41 INFO Creating magic cut-over table `db`.`_person_del`-2022-03-07 09:49:41 INFO Magic cut-over table created-2022-03-07 09:49:41 INFO Locking `db`.`person`, `db`.`_person_del`-2022-03-07 09:49:41 INFO Tables locked-2022-03-07 09:49:41 INFO Session locking original & magic tables is 94-2022-03-07 09:49:41 INFO Writing changelog state: AllEventsUpToLockProcessed:1646617781016685000-2022-03-07 09:49:41 INFO Waiting for events up to lock-2022-03-07 09:49:41 INFO Intercepted changelog state AllEventsUpToLockProcessed-2022-03-07 09:49:41 INFO Handled changelog state AllEventsUpToLockProcessed-Copy: 2/2 100.0%; Applied: 0; Backlog: 1/1000; Time: 2s(total), 1s(copy); streamer: binlog.000001:80636; Lag: 0.01s, HeartbeatLag: 0.01s, State: migrating; ETA: due-2022-03-07 09:49:42 INFO Waiting for events up to lock: got AllEventsUpToLockProcessed:1646617781016685000-2022-03-07 09:49:42 INFO Done waiting for events up to lock; duration=989.566ms-# Migrating `db`.`person`; Ghost table is `db`.`_person_gho`-# Migrating MacBook-Air-2.local:3306; inspecting MacBook-Air-2.local:3307; executing on MacBook-Air-2.local-# Migration started at Mon Mar 07 09:49:39 +0800 2022-# chunk-size: 1000; max-lag-millis: 1500ms; dml-batch-size: 10; max-load: ; critical-load: ; nice-ratio: 0.000000-# throttle-additional-flag-file: /tmp/gh-ost.throttle-# Serving on unix socket: /tmp/gh-ost.db.person.sock-Copy: 2/2 100.0%; Applied: 0; Backlog: 0/1000; Time: 2s(total), 1s(copy); streamer: binlog.000001:81343; Lag: 0.01s, HeartbeatLag: 0.02s, State: migrating; ETA: due-2022-03-07 09:49:42 INFO Setting RENAME timeout as 3 seconds-2022-03-07 09:49:42 INFO Session renaming tables is 96-2022-03-07 09:49:42 INFO Issuing and expecting this to block: rename /* gh-ost */ table `db`.`person` to `db`.`_person_del`, `db`.`_person_gho` to `db`.`person`-2022-03-07 09:49:42 INFO Found atomic RENAME to be blocking, as expected. Double checking the lock is still in place (though I don't strictly have to)-2022-03-07 09:49:42 INFO Checking session lock: gh-ost.94.lock-2022-03-07 09:49:42 INFO Connection holding lock on original table still exists-2022-03-07 09:49:42 INFO Will now proceed to drop magic table and unlock tables-2022-03-07 09:49:42 INFO Dropping magic cut-over table-2022-03-07 09:49:42 INFO Releasing lock from `db`.`person`, `db`.`_person_del`-2022-03-07 09:49:42 INFO Tables unlocked-2022-03-07 09:49:42 INFO Tables renamed-2022-03-07 09:49:42 INFO Lock & rename duration: 1.003875334s. During this time, queries on `person` were blocked-[2022/03/07 09:49:42] [info] binlogsyncer.go:164 syncer is closing...-[2022/03/07 09:49:42] [error] binlogstreamer.go:77 close sync with err: sync is been closing...-[2022/03/07 09:49:42] [info] binlogsyncer.go:179 syncer is closed-2022-03-07 09:49:42 INFO Closed streamer connection. err=<nil>-2022-03-07 09:49:42 INFO Dropping table `db`.`_person_ghc`-2022-03-07 09:49:42 INFO Table dropped-2022-03-07 09:49:42 INFO Am not dropping old table because I want this operation to be as live as possible. If you insist I should do it, please add `--ok-to-drop-table` next time. But I prefer you do not. To drop the old table, issue:-2022-03-07 09:49:42 INFO -- drop table `db`.`_person_del`-2022-03-07 09:49:42 INFO Done migrating `db`.`person`-2022-03-07 09:49:42 INFO Removing socket file: /tmp/gh-ost.db.person.sock-2022-03-07 09:49:42 INFO Tearing down inspector-2022-03-07 09:49:42 INFO Tearing down applier-2022-03-07 09:49:42 INFO Tearing down streamer-2022-03-07 09:49:42 INFO Tearing down throttler-# Done-```--In the output, you can see the main components of gh-ost.--**Migrator** is the schema migration manager.--**Inspector** reads data from the read-MySQL-server (typically a replica but can be the master). It gets initial status and structure and later follows up on progress and changelog.--**Streamer** reads data from binary logs and streams it on.--**Applier** connects and writes the applier-server where migration happens. Applier is the one to write row data and apply binlog events onto the ghost table.--**Throttler** collects metrics related to throttling and makes the informed decision whether throttling should take place. Here throttling means to pause.--#### Requirements and limitations--- `gh-ost` currently requires MySQL versions 5.6 or greater.-- You will need to have one server serving Row Based Replication (RBR) format binary logs. Right now `FULL` row image is supported. `MINIMAL` to be supported soon. `gh-ost` prefers to work with replicas. You may still have your primary configured with Statement Based Replication (SBR).-- If you are using a replica, the table must have an identical schema between the primary and replica.-- Foreign key constraints are not supported.-- Triggers are not supported.-- `gh-ost` requires an account with these privileges:- - `ALTER, CREATE, DELETE, DROP, INDEX, INSERT, LOCK TABLES, SELECT, TRIGGER, UPDATE` on the database (schema) where your migrated table is, or of course, on `*.*`- - either of:- - `SUPER, REPLICATION SLAVE` on *.*, or:- - `REPLICATION CLIENT, REPLICATION SLAVE` on *.*--The `SUPER` privilege is required for `STOP SLAVE, START SLAVE` operations. These are used to:-- Switch your `binlog_format` to `ROW` if it is not ROW, and you explicitly specified `--switch-to-rbr`.- - If your replication is already in RBR (binlog_format=ROW), you can specify --assume-rbr to avoid the STOP SLAVE/START SLAVE operations, and no need for SUPER.-- Running --test-on-replica: before the cut-over phase, gh-ost stops replication so that you can compare the two tables and satisfy that the migration is sound.--Different cloud providers require different flags.-- Google Cloud SQL works, `--gcp` flag required.-- Aliyun RDS works, `--aliyun-rds` flag required.-- Azure Database for MySQL works, `--azure` flag required.--### Goals--We will enhance this feature gradually following the plan listed below in Milestone.-For the first iteration, we will implement--- Use gh-ost to execute the migration- - Support "connect to primary, migrate on primary" only--### Milestone--1.- - Support "connect to primary, migrate on primary".- - Support non-tenant mode.- - Support on-premises MySQL databases.- - Divide gh-ost execution into stages. Proceed upon user's approval.- - Support gh-ost status feedback(ETA, configurations, etc.)-1.- - Improve migration logic to support rerun tasks.- - Support workspace-level settings for gh-ost- - Support to reconfigure gh-ost on the go.-1. Support cloud MySQL databases.-1. Support tenant mode.-1. Support "connect to replica".--## User workflow--Users can set a workspace-level gh-ost configuration, which will be the default.--In the UI workflow, the user can select to use gh-ost and supply statements.--In the VCS workflow, user commit `{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.ghost.sql` to trigger gh-ost to execute migration. We use the suffix to tell if it is a gh-ost migration. The content is a vanilla SQL statement.--Users can change the gh-ost configuration in the related issue tab.--## High-level design--We will only support "connect to primary and migrate on primary" for now.--In the future, Bytebase will support detecting primary and replicas. We may support "connect to replica" then.--### Privileges--We will use the account `bytebase@%` in gh-ost, so `bytebase@%` will require two more privileges, `REPLICATION CLIENT, REPLICATION SLAVE`. We will ask the user to grant these privileges in the documentation.--### Reconfigure gh-ost on the go--We will support [reconfigure](https://github.com/github/gh-ost/blob/master/doc/interactive-commands.md) gh-ost settings on the go.--We will support the following parameters.--- `chunk-size`-- `dml-batch-size`-- `max-lag-millis`--### Vendor--gh-ost needs to know who the cloud provider is to run correctly. We will add a new field in `Instance` to store cloud provider type. The user should set this field.--```Go-type Vendor string-const (- AWS Vendor = "AWS"- GCP Vendor = "GCP"- Aliyun Vendor = "ALIYUN"- Azure Vendor = "AZURE"- SelfHost Vendor = "SELF_HOST"-)-type Instance struct {- // omit other fields here- // Domain specific fields- Vendor Vendor `jsonapi:"attr,vendor"`-}-```--#### Or we speculate--Another approach is to infer cloud providers by inspecting usernames because cloud providers typically will have some default accounts to manage databases. References are below.--- [GCP](https://cloud.google.com/sql/docs/mysql/users)-- [aliyunrds](https://help.aliyun.com/document_detail/161152.html)-- [azure](https://docs.microsoft.com/en-us/azure/mysql/howto-create-users)-- [aws](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.MySQL.CommonDBATasks.html) (Stored procedures)--We will take the first approach, and this section is left here for information.--### gh-ost execution stages--We will divide gh-ost execution into different tasks. Each task needs to be approved by the user to proceed. These tasks are described in detail in the following sections.--1. Pre-migration check. We run gh-ost with a no-op flag to check the user's input.-2. In-migration,- 1. After approval, gh-ost performs the migration and syncs the ghost table with the original table.- 2. There is a cut-over phase when the ghost table is in sync with the original table. We will only allow gh-ost to do the cut-over if user-approved.-3. After migration, the final task is to delete the original table if the user approves.--### Pre-migration validation--gh-ost has many requirements and limitations. We want to check whether gh-ost is good to go before the actual migration. To validate it, we run gh-ost with a no-op flag. If there is any error, we will return the error to the user and let the user handle it. The error includes but is not limited to the following.--- SQL statement not legal-- `_tablename_ghc` present-- `_tablename_gho` present-- binlog format is not row based.--The above discussion entails a new task check run type below.--```Go-const TaskCheckDatabaseSchemaUpdateGhost = "bb.task-check.database.schema.update.ghost"-type TaskCheckDatabaseSchemaUpdateGhostPayload struct {- Statement string `json:"statement,omitempty"`- InstanceID int `json:"instanceId,omitempty"`- DatabaseName string `json:"databaseName,omitempty"`- TableName string `json:"tableName,omitempty"`-}-```--### In-migration progress--gh-ost can report its migration progress. It's essential to show the user the progress because, typically, it will take hours or even days to complete when migrating on large tables. We periodically update the progress in `TaskRunResultPayload.Detail`.--### Approve, run, approve, cut-over--We will have two tasks for the actual migration. The first task runs gh-ost and syncs the ghost table with the original table. Once synced, the first task will be `DONE`, and the second task will be `PENDING_APPROVAL`. The second task is the cut-over, which locks the tables and atomically switches table names. The first task blocks the second task.--These two tasks need to access the same `Migrator`. Unfortunately, the way we schedule tasks now is not capable of it. Fortunately, we can leverage the Unix socket file that the gh-ost migrator listens on. When the ghost table catches up with the original table, the "run" task will switch to `DONE`, and the "cut-over" task will be `PENDING_APPROVAL`. The "cut-over" task sends `"cut-over"` to the socket file to execute cut-over.--The socket file is in `/tmp` directory, so the operating system will clean it up and we won't bother removing it. The socket file name will be `./tmp/gh-ost.{{TASK_ID}}.{{DATABASE_ID}}.{{DATABASE_NAME}}.{{TABLE_NAME}}.sock`.--We will have task checks for both tasks. For the "run" task, we have `TaskCheckDatabaseSchemaUpdateGhost` mentioned above. For the "cut-over" task, we will have a task check to check whether it is good to cut-over now (in sync, network lags good, etc.)--```Go-const TaskCheckDatabaseSchemaUpdateGhostCutover = "bb.task-check.database.schema.update.ghost.cutover"-type TaskCheckDatabaseSchemaUpdateGhostCutoverPayload struct {-}-```--### Crash recovery--If it crashes halfway when migrating on `tablename`, we will end up with the original `tablename`, and `_tablename_gho`, `_tablename_ghc`. Our task check for gh-ost pre-migration validation will fail if `_tablename_gho` or `_tablename_ghc` is present. But if the user insists on running, we would drop `_tablename_gho` and `_tablename_ghc` for the user, rerun gh-ost.--However, we need to refactor pre-migration validation and migration status because the current logic doesn't allow migration to have the same version, and a rerun will lead to failure. We can refactor to reuse the same version to keep it idempotent.--Another approach is to abandon the previous version and start a new issue with a new version. The benefit is that we don't have to support rerun, so it's less complex.--For the first iteration, we just let it fail.--### After Migration--After the migration is finished, we will have `tablename` and `_tablename_del`. The latter is the original table. We are too scared to delete the original table for the user, so we'll generate a task to delete the table if approved by the user.--### Task dependency--Tasks in the same stage run one by one for now. With gh-ost integration, we introduce task dependency. As mentioned above, the "cut-over" task depends on the "run" task. A task can only be running if all of its dependencies are finished. Tasks that are not blocked by dependencies can run in parallel.--To store the dependency relationship, we can add a field in Task.--```Go-type Task struct {- // BlockedBy stores TaskIDs- // Task cannot be running if not all of the BlockedBy tasks are done- BlockedBy []int-}-```--However, we can only know the `TaskID` of a `Task` after insertion, so we must update `Task` after all tasks in the same stage are inserted into the database.--### MigrationContext--We will introduce a new issue type for gh-ost. It is how we tell the difference between gh-ost and direct DDL.--And a new task payload type and task executor for each execution task.--```Go-// issue related--const IssueDatabaseSchemaUpdateGhost IssueType = "bb.issue.database.schema.update.ghost"--type UpdateSchemaGhostDetail struct {- DatabaseID int `json:"databaseId"`- DatabaseName string `json:"databaseName"`- Statement string `json:"statement"`- EarliestAllowedTs int64 `jsonapi:"attr,earliestAllowedTs"`-}--type UpdateSchemaGhostContext struct {- DetailList []*UpdateSchemaGhostDetail `json:"detailList`- VCSPushEvent *vcs.PushEvent-}--// task related--const TaskDatabaseSchemaUpdateGhostSync TaskType = "bb.task.database.schema.update.ghost.sync"-type TaskDatabaseSchemaUpdateGhostSyncPayload struct {- Statement string `json:"statement,omitempty"`- SchemaVersion string `json:"schemaVersion,omitempty"`- VCSPushEvent *vcs.PushEvent `json:"pushEvent,omitempty"`- // SocketFileName is the socket file that gh-ost listens on.- // The name follows this template,- // `./tmp/gh-ost.{{ISSUE_ID}}.{{TASK_ID}}.{{DATABASE_ID}}.{{DATABASE_NAME}}.{{TABLE_NAME}}.{{TIMESTAMP}}.sock`- SocketFileName string `json:"socketFileName,omitempty"`- // more to come-}--const TaskDatabaseSchemaUpdateGhostCutover = "bb.task.database.schema.update.ghost.cutover"-type TaskDatabaseSchemaUpdateGhostCutoverPayload struct {-}--const TaskDatabaseSchemaUpdateGhostDropOriginalTable = "bb.task.database.schema.update.ghost.drop-original-table"-type TaskDatabaseSchemaUpdateGhostDropOriginalTablePayload struct {- DatabaseName string `json:"databaseName,omitempty"`- TableName string `json:"tableName,omitempty"`-}-```--### gh-ost executor--#### How migration works now--Here's how Bytebase executes migration now.--1. `server/task_scheduler.go` schedules a migration task.-2. `server/task_executor_schema_update.go` `func RunOnce()`-3. `server/task_executor.go` `func runMigration()`-4. `driver.ExecuteMigration()`-5. `util.ExecuteMigration()`--`util.ExecuteMigration` basically does the following,--```Go-func ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- preMigration()- defer postMigration()- Execute(statement)-}-```--#### Use gh-ost to execute migration--Since `Execute(statement)` merely executes the DDL statement, it should be interchangeable with gh-ost performing the migration.--We will refactor `ExecuteMigration` and export `beginMigration` and `endMigration`, so with gh-ost tasks, it will be the following.--```Go-// task_executor_schema_update_ghost.go--type SchemaUpdateGhostTaskExecutor struct {- l *zap.Logger-}--func (exec *SchemaUpdateGhostTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {- PreMigration()- ghostExecuteMigration()-}--// task_executor_schema_update_ghost_cutover.go-type SchemaUpdateGhostCutoverTaskExecutor struct {- l *zap.Logger-}--func (exec *SchemaUpdateGhostCutoverTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {- allowCutOver()-}--// task_executor_schema_update_ghost_drop_original_table.go--type SchemaUpdateGhostDropOriginalTableTaskExecutor struct {- l *zap.Logger-}--func (exec *SchemaUpdateGhostTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {- dropOriginalTable()- PostMigration()-}-```diff --git a/docs/design/pipeline.md b/docs/design/pipeline.mddeleted file mode 100644index e06ea9128d..0000000000--- a/docs/design/pipeline.md+++ /dev/null@@ -1,80 +0,0 @@-# Overview--Pipeline, Stage, Task are the backbones of execution.--A PIPELINE consists of multiple STAGES. A STAGE consists of multiple TASKS.--# Comparison to other systems--## Comparison with Tekton--- PIPELINE = Tekton Pipeline-- STAGE = N/A-- TASK = Tekton Task-- N/A = Tekton Step--## Comparison with GitLab:--- PIPELINE = GitLab Pipeline-- STAGE = GitLab Stage-- TASK = GitLab Job-- N/A = GitLab Script Step--## Comparison with GitHub:--- PIPELINE = GitHub Workflow-- STAGE = N/A-- TASK = GitHub Job-- N/A = GitHub Step--## Comparison with Octopus:--- PIPELINE = Octopus Lifecycle-- STAGE = Octopus Phase + Task-- TASK = Octopus Step--## Comparison with Jenkins:--- PIPELINE = Jenkins Pipeline-- STAGE = Jenkins Stage-- TASK = Jenkins Step (but it's also called task from its doc)--## Comparison with Spinnaker:--- PIPELINE = Spinnaker Pipeline-- STAGE = Spinnaker Stage-- TASK = Spinnaker Task--# General design consideration--- Other mainstream products either have 3 or 4 layers.- We choose 3 layers omitting the most granular layer - Step. For now only GitLab has 4 layer systems,- and its step is mostly used to model a lightweight step similar to shell script step. This seems like- an overkill for our case. On the other hand, 3 layer design such as Octopus seems to be sufficient.--- All products agree on the smallest querable execution unit (having a dedicated API resource endpoint):- Tekton Task/GitLab Job/GitHub Job/Octopus Step.- Thus, we also choose Task as our smallest querable execution unit.--- We also have a Stage concept which is similar to GitLab Stage/Octopus Phase, in that it's a- container to group multiple tasks. Stage is usually used to model a stage in the development- lifecycle (dev, testing, staging, prod).--- Only Pipeline and Task have status, while Stage doesn't. Stage's status derives from its- containing Tasks.--- Pipeline status is 1-to-1 mapping to the Issue status. We introduce Pipepline for decoupling- pipeline logic (workflow orchestration etc) from issue logic (collabration etc). And it- helps testing (we can mock the entire pipeline implemenation) and also allows Pipeline to- be reused in other situation. On the other hand, we want to reduce the complexity of- introducing this extra layer, thus we always try to make a fixed 1-to-1 mapping for their- respective fields. Client code could combine Pipeline status and its running step status (substatus)- to achieve more granular behavior.--To wrap up, we finally arrive the same conclusion as spinnaker.--# Domain specific design consideration--- We require a stage to associate with an environment. In the future, we will introduce environment tiers which define rules such as requiring manual approval.--- We require a task to associate with an database instance. This limits the task usage to database operations instead of general purpose task management. Since Bytebase is dealing with database domain, this tradeoff is fine. On the other hand, a task may or may not contain a database since tasks such as creating new database, syncing the entire instance schema are not database specific.diff --git a/docs/design/pitr-mysql.md b/docs/design/pitr-mysql.mddeleted file mode 100644index 7dc2adba3b..0000000000--- a/docs/design/pitr-mysql.md+++ /dev/null@@ -1,240 +0,0 @@-# Point-in-time Recovery--*Note: implementation details in this design doc focus exclusively on MySQL, while the general design should also apply to PostgreSQL.*--# Terminology-A *physical backup* consists of raw copies of the directories and files that store database contents. This type of backup is suitable for large, important databases that need to be quickly recovered when problems occur.--A *logical backup* is a logical snapshot of a database, represented by a full logical dump of SQL statements. [This reference](https://dev.mysql.com/doc/refman/8.0/en/backup-types.html) highlights the difference between logical backup and physical backup.--*Incremental backup* is the changes to the database since the last full backup, represented as the binlog in MySQL. Incremental backup can also be called data changes. Incremental backup applies to logical backups.--*Point-in-time Recovery* is the process of making a database's state current up to a given time by restoring the database from a logical backup and applying incremental backup data changes up to the given time.--A *database* is a collection of tables represented as is in MySQL. A *database instance* (instance for short) is the server process that runs the database management system. In MySQL, it’s similar to a `mysqld` process.---# Overview--Currently, Bytebase users can set up a backup policy, take full logical backups automatically following the backup policy schedule, and restore the backup to a new database. There are two problems we would like to address in this design.--1. Point-in-time Recovery.-2. In-place recovery.--We are introducing Point-in-time Recovery (PITR). Consider the scenario that the user made a mistake and dropped a table at 8:00 am, only to find that the last full backup was produced at 2:00 am. If they restore to the previous backup snapshot, new data changes would be lost in the latest 6 hours. With PITR, we can restore the database state to any point between the checkpoints at the granularity of a single database transaction or a timestamp.--We are also introducing In-place Recovery. Without it, users have to change the data source name (DSN) and the database connection string in the software, which is a pain point because it requires--1. Coordination between developers, DBAs, and even network engineers,-2. Source code modification and software redeployment.--We target database-level recovery with logical backup because the database is the minimal isolation unit within a database instance (an instance of a database server), a natural, logical unit mapping to the business application unit. Logical mistakes usually happen to a single database. Users would like to recover a single database without impacting other databases.--## Requirements--- MySQL 8.0 and 5.7.-- The database should use the InnoDB storage engine.-- Enable binlog and choose row-based binlog format.-- Databases for Point-in-time Recovery are not involved in [XA Transactions](https://dev.mysql.com/doc/refman/8.0/en/xa.html).-- The remaining disk storage should be enough. Bytebase will estimate the database dump size, and make sure that there is always at lease 1GB more disk space.--Note that when statement binlog format is used, the `mysqlbinlog` tool could misbehave with regard to the `--database` option as described [in the docs](https://dev.mysql.com/doc/refman/8.0/en/mysqlbinlog.html#option_mysqlbinlog_database). In short, using statement logging has a chance to miss some binary log events in the specified database.---# Critical User Journeys--This section describes the common critical user journeys about why and how the users may use the Point-in-time Recovery feature to recover their data.--## OMG Moments--Occasionally, catastrophic events can happen to the databases and result in service downtime. Here are some cases where the users would like to recover the database to a specific point in time.--- **Drop Database**: the database is dropped accidentally by mistake.-- **Schema Migration Failure**: A column is dropped, or its type is updated incorrectly. The table needs to be rolled back to the state before the migration. In the long term, we could polish the feature to provide the ability to revert the migration with minimal cost. Still, currently, we could leverage PITR to do the lift, with the limitation of losing incoming data after the migration.-- **Buggy Application**: Bugs happen, and they may corrupt your data. The chances are that the user rolls out a new release of their service, only to find a bug in the application code that deletes essential data. It is best to roll back the service and recover the database to the state just before the release.--## Database Recovery--When OMG moments happen, the user would like to recover the database to the latest correct state as soon as possible. This is where the Point-in-time Recovery feature kicks in.--As long as the instance fulfills all the [requirements](#requirements) and enables a backup policy in the Bytebase environment that contains this instance, the user is lucky enough to have a PITR option. The user could then choose those databases they want to recover, and select the point of time, then Bytebase will recover the databases to precisely the state of that point of time.--What’s more convenient is that if the user used Bytebase to do the wrong schema migration, then Bytebase will record the exact time before the schema migration and provide a one-click Point-in-time Recovery experience.---# Design--## Point-in-time Recovery Process--### Full Backup--Full backup follows what `mysqldump` does with `--source-data` flag. `SHOW MASTER STATUS` gives the coordinate (MySQL binlog file name and position) of a backup. This provides us with the starting position to apply binary logs in the PITR recovery step. Because the `SHOW MASTER STATUS` statement is not transactional, we have to put [`FLUSH TABLES tbl_names... WITH READ LOCK`](https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-tables-with-read-lock-with-list) to block writes to figure out the precise binary log coordinate in the transaction of taking database backup. As a side-effect, writes will be blocked for a short period between steps 1 and 4. By the way, we have to make sure the tables are unlocked regardless of any failure.--1. `FLUSH TABLES tbl_names... WITH READ LOCK`. Bytebase will set a timeout to release the lock if things go wrong.-2. `SHOW MASTER STATUS`. Bytebase will record the binary log coordinates and timestamp.-3. Start a transaction. This [will implicitly unlock tables](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html) that were locked in the same session.-4. Dump all the schema and data for a database.-5. Commit or abort the transaction.--Step 1 is different steps from a typical automatic database backup that could affect database performance. But since it only affects a single database for a short period of time, it is acceptable in most cases.--Step 4 should write the binlog file name and position (a.k.a binlog coordinates) obtained in step 2 in the same logical backup file.--An example setup of a backup policy is to back up the database every day at 2 am when the traffic is low and continuously store the data changes across the whole day. If the backup interval is one day, then there should be a series of backup start points in the view of the timeline.--The logical backup and data changes, i.e., binlog, should be kept in safe and durable storage, e.g., AWS S3 or NFS. Note that users should not manually manage the storage, introducing inconsistency between the metadata in Bytebase and storage contents.--Currently, we keep the logical backup and binlog together in the local disk where Bytebase resides. We may integrate with cloud storage in the long term.--The partial backup dump should be discarded if Bytebase encounters an unrecoverable error during the full backup process. The system should report a failed backup, and the user could choose to start another backup task manually. The partially dumped logical backup file will be automatically deleted by Bytebase.--To check the integrity of the logical dump, Bytebase will save file size in the backup metadata. When using a logical backup to recover, we should first validate the file size of the dump file and the metadata matches.--#### Why bother?--The full backup process seems very sophisticated. Why don't we just dump the logical backup and use `SHOW MASTER STATUS` to get the binlog coordinates? Well, let's look at an example.--If we start to dump a logical backup called bk at time t, and the backup SQL runs for 10s and finishes at t+10. Then we get the binlog coordinates at t+10 and save it together with the backup metadata. When we want to do a PITR to the database state at t+20, we would restore the logical backup bk and replay the binlog from t+10 to t+20.--Here is the problem: the logical backup is a [consistent read](https://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html) of the database, which means that no matter how long it takes to run the SQL, **the backup content is similar to a snapshot of the database at time t**.--Now let's reconsider the binlog replay. After the logical backup bk is restored, the database is at the state of t. If we want to incrementally restore to t+20, we should replay the binlog from **t to t+20** instead of t+10 to t+20 as is described above. In short, this "simpler implementation" is actually buggy.--The current design of full backup process in [this section](#full-backup) ensures that:--1. No data is inserted between we dump a logical backup with the consistent read semantic and get the binlog coordinates.-2. The locking time is minimal so that the backup process has the minimal impact on other workloads in the same database.--## Incremental Backup--Once the backup is enabled for a database, Bytebase will periodically download binlog from the MySQL server via `mysqlbinlog` with parameter [`--read-from-remote-server`](https://dev.mysql.com/doc/refman/8.0/en/mysqlbinlog.html#option_mysqlbinlog_read-from-remote-server), which reads data via the [binlog network stream](https://dev.mysql.com/doc/internals/en/binlog-network-stream.html). The binlog downloading process is described below.--1. Check the local existing binlog files.-2. Obtain a listing of the binary log files on the MySQL server with SHOW BINARY LOGS.-3. Download the previous except the current binlog files on the MySQL server that does not exist locally.--The process above should be executed every minute. When a download task fails, Bytebase should delete the corresponding binlog file. The downloading process must be idempotent.--To accomplish the tasks described above, Bytebase will embed the newest version of `mysqlbinlog` binary, which is also used in the recovery process.--When the backup is enabled for a specific database, Bytebase will check where the PITR requirements are met and automatically upgrade to PITR and download the binlog files.--Take a look at an example command below. The `--ssl` parameters should be used [following the doc](https://dev.mysql.com/doc/refman/5.7/en/mysqlbinlog.html#option_mysqlbinlog_ssl) if required:--`mysqlbinlog mysql-bin.000001 --ssl=0 --read-from-remote-server --host=x --user=x --password=x --raw --result-file=/bytebase/binlog/`--## Find the point-in-time T--The user should be able to navigate the database history to search for SQL queries to determine the exact point in time to recover. As is described in the [OMG Moments](#omg-moments), when the user meets a schema migration failure, Bytebase should locate the binlog position just before the corresponding migration happens.--Bytebase will support a binlog search api accepting a timestamp and returns several numbers of events around it, containing the data changes and binlog positions. The user should choose a proper binlog position from the UI so that Bytebase can recover the database to the corresponding state.--MySQL binlog contains information about the ALTER TABLE statement. When a schema migration happens in Bytebase, we should search the binlog and find the position of the schema migration. If the user wants to revert the schema migration, this position should be the target position of a later PITR. The user can revert it with a simple button click.--## Recovery--When the point-in-time t1 is determined, Bytebase will take a series of actions to accomplish the task. The recovery plan is as follows.--1. Locate the logical backup just before t1, which is called bk and represents a database snapshot at t0.-2. Create a temporary database called pitr, with the naming convention described below.-3. Restore logical backup bk to the pitr database, after which the pitr database should be a snapshot at t0 of the original database.-4. Apply data changes from t0 to t1.-5. Validate the pitr database to make sure everything is as expected.-6. Abort or execute the cutover.- 1. Abort the recovery will delete the pitr database.- 2. Execute the cutover: if the original database exists, rename the original database to old, and rename the pitr database to the original; if not exists, we just create the pitr table using the user-provided name.--The timeline involved above could be roughly represented as:-(bk (t0), data changes, t1, data changes)--The pitr database naming convention in step 2 is appending _pitr_${UNIX_TIMESTAMP} to the end of the original database name. We must check that the pitr database name does not contain more than 64 characters, which is [the limit of MySQL](https://dev.mysql.com/doc/refman/8.0/en/identifier-length.html).--Step 6b uses a special MySQL syntax [`RENAME TABLE current_db.tbl_name TO other_db.tbl_name`](https://dev.mysql.com/doc/refman/8.0/en/rename-table.html), which effectively moves tables between databases. At last, Bytebase will delete the pitr database, which will be empty. The original database, if it exists, will be deleted if the user manually approves the issue Bytebase automatically generates.--After the recovery process described above, Bytebase will ask for the user’s manual approval to delete the old database.--To restore binlog from the original to the pitr table as is described in step 4, Bytebase will use the [`--rewrite-db`](https://dev.mysql.com/doc/refman/8.0/en/mysqlbinlog.html#option_mysqlbinlog_rewrite-db) option. An example will be `mysqlbinlog --rewrite-db='dbtarget->dbtarget_pitr' --database=dbtarget_pitr binlog.00001`. The `--database` option filters changed database names, so should not use the original database name.--The database session used to accomplish this recovery task should disable binlog. The binlog is used as incremental backups of the database, and the recovery operation itself will also introduce data changes, which are actually a duplicate of the recovered data changes. We should prevent the duplicate from going into the incremental backups, i.e., the binlog.--After the recovery process, the user has the original database named old to investigate for problems or just delete to reclaim storage space. The original database is recovered to the point in time.--Before the cutover stage, Bytebase will do several checks to prevent potential damage:-- Check that no connection exists on the original database--## Crash-If the recovery process crashes before completion, we should mark the recovery as failed. The user should start a new recovery process.---# API and Schema--Bytebase should make some changes to the API and schema design to implement the PITR feature.--## Backup PITR Information--When taking a backup of a database, now we also need to store the current position in the data change stream when the logical backup is dumped. In MySQL, this position refers to binary log file name and position. In PostgreSQL, it’s the WAL lsn. To use a single model, we store a JSON encoded string that could be encoded and parsed, respectively.--To provide a search option with the timestamp and binlog position, we will encode both of them, where the timestamp is the time at which the statement began executing on the MySQL server and decoded from the [binlog event header](https://dev.mysql.com/doc/internals/en/event-header-fields.html). The timestamp is represented as the UNIX timestamp, i.e., the number of seconds since 1970 (UTC).--An example of the PITR information will be:--```json-{- "binlog_info": {- "binlog_name": "binlog.000001",- "binlog_position": 1234,- "ts": 1650957790,- },- "file_size": 10240-}-```--where the `ts` field is a UNIX timestamp in seconds, indicating the binlog event time in binlog.000001 at the position 1234.--We will add a field in api.Backup:--```go-type Backup struct {- ...- // Payload contains arbitrary string message with following cases- // 1. contains the starting position of incremental backup when this backup snapshot is taken.- // This field is not returned to the frontend.- Payload string-}-```--We will add a column in table backup:--```sql-CREATE TABLE backup (- ...- payload TEXT NOT NULL-);-```--When the user performs a PITR recovery, Bytebase will check the api.Backup and try to find the PITR information. If the PITR information is not empty, Bytebase will perform a binlog replay after recovering the logical backup using the [recovery process described above](#recovery).---# Data Retention Policy--As time goes by, the logical backup and incremental backup will take up infinite storage space, and a data retention policy should be defined to solve this problem.--Bytebase will currently implement a default data retention policy of 7 days. We may later make this configurable as an improvement.---# Monitoring--Steps 3 and 4 could take some time, and Bytebase should export the progress via api.Task, which could be obtained from an api.Issue.---# Third-Party Integration--Bytebase should provide event webhooks for user system integration. For example, we could send the logical backup success/failure events to a user-defined URL.---# Test Plan--To test the Point-in-time Recovery is working as expected, we will write several unit test cases following the [Critical User Journeys](#critical-user-journeys) described above. The test cases should cover major path and corner cases as possible.--- Normal cases should perform PITR in the target database.-- Advanced cases should perform PITR in the database which is restored from a PITR operation.diff --git a/docs/design/source-code-tour.snb.md b/docs/design/source-code-tour.snb.mddeleted file mode 100644index 22fe44fc6d..0000000000--- a/docs/design/source-code-tour.snb.md+++ /dev/null@@ -1,148 +0,0 @@-# Source Code Tour--This is [best viewed on Sourcegraph](https://sourcegraph.com/github.com/bytebase/bytebase/-/blob/docs/design/source-code-tour.snb.md).--The code snippets in this file correspond to search queries and can be displayed by clicking the button to the right of each query. For example, here is a snippet that shows off the greeting banner:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/bin/server/cmd/root.go?L46-54--## Introduction--Bytebase is a database change and version control tool. It helps DevOps team to handle database CI/CD for DDL (aka schema migration) and DML. A typical application consists of the code/stateless and data/stateful part, GitLab/GitHub deals with the code change and deployment (the stateless part), while Bytebase deals with the database change and deployment (the stateful part).----## Architecture Overview----Bytebase codebase is a monorepo, the repo contains multiple binaries:--1. Main Bytebase application.-1. Bytebase CLI `bb`.--The main Bytebase application builds a single binary bundling frontend (Vue), backend (Golang) and database (PostgreSQL) together. Starting Bytebase is simple:--```bash-$ ./bytebase-```--### Bundling frontend--Bytebase uses [Go's embedding](https://pkg.go.dev/embed) to bundle the frontend. It also uses [Go's build tag](https://pkg.go.dev/go/build#hdr-Build_Constraints) to only embed for the release build. As for the development build, we need hot reloading and don't want to go through the full build cycle:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/server_frontend_embed.go--### Bundling PostgreSQL--Bytebase stores metadata in PostgreSQL. The Bytebase release binary includes the PostgreSQL tarball and installs PostgreSQL upon first launch:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/resources/postgres/postgres.go?L93-105--The embedded PostgreSQL is handy during development and easy for user to get started. Alternatively, user can specify an external [--pg](https://www.bytebase.com/docs/get-started/install/external-postgres) to store the metadata there.--## Modular Design--### Plugin--Bytebase employs a plugin system. The core covers the domain specific models and the business logic around them. The rest is implemented as plugins.--Bytebase supports MySQL, PostgreSQL, TiDB, ClickHouse and Snowflake. Each implements the `db.Driver` plugin interface:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/plugin/db/driver.go?L382-422--Bytebase also integrates GitLab and GitHub to support GitOps workflow. Each implements the `vcs.Provider` plugin interface:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/plugin/vcs/vcs.go?L126-218--To make sure that plugin does not unexpectedly depend on the core, Bytebase injects a dependency gate using Go's blank import and build tag:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/api/api_dependency_gate.go?L1-18--### Namespacing--To keep a modular design, the codebase uses [reverse domain name notation](https://en.wikipedia.org/wiki/Reverse_domain_name_notation) extensively. Below defines the `Activity` types:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/api/activity.go?L10-66--All Bytebase built-in types use `bb.` namespace. This design allows 3rd party plugins to register their own types later.--## Life of a Schema Migration Change--The rough sequence:--1. Bytebase registers the schema migration handler on startup.-1. Client requests the server to create a pipeline containing the schema migration task.-1. The task check scheduler performs various pre-condition checks against the task in the active pipeline.-1. The task scheduler schedules the task that has met the pre-conditions, which in turns invokes the schema migration handler.-1. The schema migration handler invokes the particular db driver to perform the migration and records the migration history.--### Pipeline model--At the Bytebase core, there is an execution engine consisting of `Pipeline`, `Stage`, `Task` and `Task Run`.----A pipeline contains multiple stages, and each stage contain multiple tasks. This is how Bytebase creates a Pipeline:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/issue.go?L371-401--`Task` is the basic execution unit and each `Task Run` represents one particular execution. Upon startup, Bytebase registers the task type with a task executor. Below registers the schema change task executor:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/server.go?L207--The task executor implements the `TaskExecutor` interface:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_executor.go?L20-34--The schema change task executor internally runs the schema migration:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_executor.go?L303-313--Bytebase records very detailed migration histories. The history is stored on the targeting database instance. This is the history schema for MySQL:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/plugin/db/mysql/mysql_migration_schema.sql?L5-44--This detailed history schema info enables Bytebase to implement powerful features such as [Drift Detection](https://www.bytebase.com/docs/change-database/drift-detection), [Tenant Database Batch Change](https://www.bytebase.com/docs/change-database/batch-change/#change-databases-from-multiple-tenants).--### How a task check is scheduled--Tasks may need to meet some pre-conditions before being scheduled. For example:--1. The task needs to be [approved](https://www.bytebase.com/docs/administration/environment-policy/rollout-policy).-1. The SQL statement must conform to [defined policy](https://www.bytebase.com/docs/sql-review/review-rules).--This pre-condition is modeled as `Task Check`. Task checks are created before when the corresponding task becomes the next to-be-scheduled task in the pipeline:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/pipeline.go?L9-37--Task checks can also be created upon receiving the `POST /pipeline/:pipelineID/task/:taskID/check` request:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task.go?L217-236--The task check scheduler periodically inspects all created task checks and schedules them:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_check_scheduler.go?L60-90--Each task check implements the `TaskCheckExecutor` interface:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_check_executor.go?L9-13--The most comprehensive check is the SQL advisor check, it relies on the SQL advisor plugin (which itself relies on the SQL parser plugin) to catch potential issues of the schema migration.--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_check_executor_statement_advisor_composite.go?L70-75--### How a task is scheduled--The background task scheduler periodically inspects each active pipeline, finds its next task:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_scheduler.go?L74-95--The task will be scheduled if it has met all pre-conditions:--https://sourcegraph.com/github.com/bytebase/bytebase@d55481/-/blob/server/task_scheduler.go?L301-319--## Further Readings--- [Pipeline Design](https://sourcegraph.com/github.com/bytebase/bytebase/-/blob/docs/design/pipeline.md)-- [Docs](https://bytebase.com/docs)diff --git a/docs/design/sql-review-source-code-tour.snb.md b/docs/design/sql-review-source-code-tour.snb.mddeleted file mode 100644index a7e340139d..0000000000--- a/docs/design/sql-review-source-code-tour.snb.md+++ /dev/null@@ -1,86 +0,0 @@-# SQL Review Source Code Tour--This is best viewed on [Sourcegraph](https://sourcegraph.com/github.com/bytebase/bytebase/-/blob/docs/design/sql-review-source-code-tour.snb.md).--## Introduction--Bytebase provides the SQL review feature to check out SQL anti-pattern and give some advice.--## Overview----The inputs for SQL review are SQL review policy, SQL statement, and catalog (schema info). The output is an advice list.--## The SQL Review Policy--The SQL review policy contains policy name and a set of SQL review rules.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/sql_review.go?L124-128--The SQL review rule contains Type, Level, and rule-specific Payload.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/sql_review.go?L143-150--The Type specifies the rule. The Level defines the error level for this rule, Error, Warning or Disabled.--## The SQL Advisor--We implement each rule as a SQL advisor in Bytebase. The SQL advisor is SQL dialect specific and we need to use different SQL parsers for each SQL dialect.--The SQL advisor is implemented as a plugin in the Bytebase backend. A particular advisor needs to implement a Check function.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/advisor.go?L201-204--Because of the plugin architecture, each SQL advisor needs to call Register to register its advisor type.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/advisor.go?L211-231--Also, we define a SQL advisor mapping with tuple <SQL review type, SQL dialect>.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/sql_review.go?L323-331--We have implemented some MySQL dialects (MySQL and TiDB) and PostgreSQL advisors. Below, we present the implementation of the MySQL table naming convention advisor.--### The MySQL TableNamingConvention Advisor--This advisor checks the table naming convention. Let’s implement the Check function.--First, we should parse the SQL statement.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/mysql/advisor_naming_table.go?L27-32--Then, we need to get the error level and payload.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/mysql/advisor_naming_table.go?L34-41--The TableNamingConvention needs the naming format and maximum length which stores in the rule payload.--Next, we should check the new table names in SQL statement. If any of them break this rule, we should emit a corresponding advice. To achieve this, we should visit the AST(Abstract Syntax Tree) to find out all new table names.--So we need to cover CREATE TABLE, ALTER TABLE RENAME, and RENAME TABLE statements.--We use TiDB parser as the MySQL dialect parser. And we implement the ast.Visitor interface to visit the TiDB parser AST.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/mysql/advisor_naming_table.go?L71-92--The advisor checks all new table names based on the rule.--https://sourcegraph.com/github.com/bytebase/bytebase@72e8995/-/blob/plugin/advisor/mysql/advisor_naming_table.go?L94-113---## The Catalog--The catalog is the schema information for a database. For some rules, we need some information from the catalog. e.g. if we have a SQL `ALTER TABLE t RENAME INDEX uk to uk_name;` and want to check the columns in this index, we cannot get this information from this SQL statement. So we need a catalog to retrieve the column info.---## How to Implement a SQL Advisor--Since all SQL advisors have a nearly identical skeleton, we have implemented a code generator located at `/plugin/advisor/generator`. The generator only supports MySQL dialect for now with PostgreSQL support coming later.--https://sourcegraph.com/github.com/bytebase/bytebase@12faead/-/blob/backend/plugin/advisor/generator/README.md--## Further Readings--- [Source Code Tour](https://sourcegraph.com/github.com/bytebase/bytebase/-/blob/docs/design/source-code-tour.snb.md)-- [SQL Review User Doc](https://bytebase.com/docs/sql-review/overview)diff --git a/docs/design/tenancy.md b/docs/design/tenancy.mddeleted file mode 100644index 5504addfa7..0000000000--- a/docs/design/tenancy.md+++ /dev/null@@ -1,340 +0,0 @@-# Tenant Database Management--2021.11.30--## Terminology-**Multi-tenancy v.s. Multi-single-tenancy**: multi-single-tenancy is an architecture where a single instance of the software and supporting infrastructure serve a single customer. Multi-tenant is an architecture where a single instance of the software and its supporting infrastructure serves multiple customers. Each customer shares the software application and also shares a single database. Each tenant’s data is isolated and remains invisible to other tenants.--**Database Instance v.s. Database**: an instance is an installation of the database server executable which runs as an operating system service. A database is a systematic collection of data that stores data in tables. A database instance operates one or more databases.--## Overview-Tenancy support is intended to ease the schema management across a set of tenants, from applying the same change across the fleet to tracking the progress. There are two main use cases:--- A customer is building a multi-single-tenant SaaS application with one database per tenant model. A schema change should be rolled out to each individual database for each of their tenants.-- A customer is managing a geographically distributed database fleet for a highly-available Cloud service, with one database/instance in each location. This becomes the standard for [Cloud application architecture](https://arxiv.org/abs/2105.00560).--The design should also be compatible with popular software deployment products such as [Octopus](https://octopus.com/docs/tenants). There is a correlation between Cloud software deployment and database schema change. For example, schema change for a new feature is usually deployed before the software referencing the new schema is released. Bytebase can help these products complete the full story of Cloud software development and deployment.--## Design-### Labels-Labels are used as queryable key-value pair annotations for resources such as databases. They provide the ability to query (filter and group) resources. Here are some common use cases for labels:-- Locations: for example, 'region:us-central1'.-- Tenant name: for example, 'company:bytebase'.--The labels applied to a resource have the following requirements:-- Each resource can have multiple labels, up to a maximum of 4. We start with a low number which can be increased later.-- Each label must be a structured key-value pair.-- Keys and values cannot be empty, and have a maximum length of 63 characters. Keys should only have alphanumeric characters ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.). Dots are used for namespace prefixes, e.g. “location”. Namespace prefix is required.-- The key portion of a label must be unique for a resource. However, the same key or key:value label can be applied to different resources so that labels are not unique identifiers for resources.-- Labels follow the CRUD resource model.-- Labels keys are defined at workspace level by workspace owners. Project owners are only allowed to use these predefined label keys. We define it at workspace level for convenience and can be expanded later when we have more hierarchical use cases later (environment, project, etc). Note, we don't allow users to define label keys at all at first but provide several predefined label keys. Initially, workspace owners also need to pre-define label values before values are used as database labels, because many labels such as locations need tight controls by DBAs and this can simplify some of the user journeys without re-typing values every single time.-- There are system reserved labels (see Appendix).-- Labels must be re-applied when a database is created or moved to a different project.--More specifically, labels will enable the following support:-- Classify tenants by labels. One tenant can have multiple databases for different purposes so tenants are not exactly tenant databases.-- Find tenants by searching with labels.-- Filter and group by tenants at project database overview page, e.g. 1) first filter by 'environment:prod' then group by 'region', 2) group by 'environment' then 'company' in two dimensions.-- Deploy to multiple tenants at the same time. We can introduce a concept called **deployment configuration** to specify stages and ordering, e.g. 'environment:canary' should come before 'environment:prod'. Details are in a later section.--We call it a [label](https://dictionary.cambridge.org/dictionary/english/label) instead of a [tag](https://dictionary.cambridge.org/dictionary/english/tag) because labels are structured descriptions (key:value with predefined keys) of resources. [AWS](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) and [Azure](https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/tag-resources?tabs=json) name it tags for cloud resources. [GCP](https://cloud.google.com/compute/docs/labeling-resources) and [Kubernetes](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) name it labels for resources. We'd like to be close to Kubernetes style as we're both in the devops category.--### Tenant Mode Project Setting-We'll introduce a project level setting called **Tenant Mode**. When enabled, all the deployments will use tenant deployment described below. Any newly created databases or databases transferred over should have labels attached. The project overview page will look differently in the tenant view.--### Deployment Configuration-Bytebase uses issues to track schema deployment. Internally, issues are converted to pipelines with multiple stages and tasks to update schemas asynchronously. We can introduce Deployment Configuration that maps to tenant deployment. In the current design, we expect all tenants to use the same set of database names from different database instances. The deployment configuration will classify the deployment schedule of these tenants instead of the tenant database because one tenant may have different databases on the same instance for different purposes. This means the database name should be used together with deployment configuration for tenant database scheme updates.--Deployment specification follows [Kubernetes' Labels and Selectors](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) style. A deployment configuration includes multiple deployments meaning different stages in the pipeline. The change will be applied to tenants that match the label selector. The requirements follow `AND` operator for matchExpressions. We don't use k8s' matchLabels because this can be expressed by `In` operation in matchExpression. For `OR` operation requirements, e.g. deployment updating two regions us-central1 and us-central2, `In` operator in LabelSelectorRequirement should already cover most use cases. Otherwise, multiple deployments are needed using some boolean expression..--Tenant databases matching the query in a stage should not show up in the following stages because they have been updated already. Deployment configurations are not retroactive meaning updating configuration will not update existing deployments in the issue. We will only support one deployment configuration at first.--```go-type DeploymentConfig struct {- deployments []Deployment-}--type Deployment struct {- spec DeploymentSpec-}--type DeploymentSpec struct {- selector LabelSelector-}--type LabelSelector struct {- // matchExpressions is a list of label selector requirements. The requirements are ANDed.- matchExpressions LabelSelectorRequirement-}--type LabelSelectorRequirement {- // key is the label key that the selector applies to.- key string-- // operator represents a key's relationship to a set of values. Valid operators are In, Exists.- // Note: NotIn and DoesNotExist are not supported initially.- operator string-- // values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.- values []string-}-```-Here are some examples of deployment configurations.--Example 1: Deploy to tenants based on environments.-```yaml-deployment_config:- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: test- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: staging- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: prod-```-Example 2: Deploy to canary company tenants, then all company tenants.-```yaml-deployment_config:- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: canary- matchExpressions:- key: company- operator: Exists- deployments:- spec:- selector:- matchExpressions:- key: company- operator: Exists-```-Example 3: Slow rollout to all regions over four days.-```yaml-deployment_config:- deployments:- spec:- selector:- matchExpressions:- key: region- operator: In- values: us-west1- deployments:- spec:- selector:- matchExpressions:- key: region- operator: In- values: us-west2, us-central, us-central2- deployments:- spec:- selector:- matchExpressions:- key: region- operator: In- values: europe-west1, europe-west2- deployments:- spec:- selector:- matchExpressions:- key: region- operator: Exists-```-Example 4: This illustrates the compatibility with Octopus deployment model in the Appendix section.-```yaml-deployment_config:- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: development- matchExpressions:- key: tenant- operator: In- values: internal- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: test- matchExpressions:- key: tenant- operator: In- values: internal- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: staging- matchExpressions:- key: tenant- operator: In- values: "Companion Care", "Pet HealthCenter"- deployments:- spec:- selector:- matchExpressions:- key: environment- operator: In- values: production- matchExpressions:- key: tenant- operator: In- values: "Capital Animal Hospital", "Companion Care", "Pet HealthCenter"-```--### Schema Change Workflow-We should move issue [pipeline generation](https://github.com/bytebase/bytebase/blob/main/frontend/src/plugins/issue/DatabaseSchemaUpdateTemplate.ts#L17) from frontend to [backend](https://github.com/bytebase/bytebase/blob/main/server/issue.go#L406). We'd like the backend to take more responsibility for complexity. This also allows the backend to figure out the pipeline based on project tenant mode and deployment configuration.--#### UI-Tenant mode projects should show databases in tenant view (TBD). Schema altering should be applied to all tenants given a database name.--#### VCS-Since we will still take the database name that's plugged to deployment configuration, the [file path template](https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template) will not change.-```-{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql-```--#### Other Workflows-- Database Create: this creates a new database of an instance with labels in addition. This new database should look like a clone (same schema, no data) of existing tenants, if we look at region turn-up process. The workflow should look like schema change except we append the schema of an existing tenant database to the create database statement.-- Database Schema Baseline (transfer project): this creates a schema baseline when an existing instance is added to Bytebase system. When an instance is added, its databases are added to a default project. When any database is transferred to a tenant mode project, it should only be allowed when its schema is the same as any other tenant databases and its schema version should be set consistently similar to Database Create workflow above.--### Permissions-- Available label keys: workspace owners can read/write; developers can read.-- Tenant Mode project settings: follow existing project permissions model.-- Labels: project owners can read/write; project developers can read.-- Deployment configurations: project owners can read/write; project developers can read.--### Storage-#### Available label keys-```sql-CREATE TABLE label_key (- id INTEGER PRIMARY KEY AUTOINCREMENT,- row_status TEXT NOT NULL CHECK (- row_status IN ('NORMAL', 'ARCHIVED')- ) DEFAULT 'NORMAL',- creator_id INTEGER NOT NULL REFERENCES principal (id),- created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- updater_id INTEGER NOT NULL REFERENCES principal (id),- updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- key TEXT NOT NULL-);---- key's are unique within the label_key table.-CREATE UNIQUE INDEX idx_label_key_key ON label_key(key);--CREATE TABLE label_value (- id INTEGER PRIMARY KEY AUTOINCREMENT,- row_status TEXT NOT NULL CHECK (- row_status IN ('NORMAL', 'ARCHIVED')- ) DEFAULT 'NORMAL',- creator_id INTEGER NOT NULL REFERENCES principal (id),- created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- updater_id INTEGER NOT NULL REFERENCES principal (id),- updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- key TEXT NOT NULL,- value TEXT NOT NULL,- FOREIGN KEY(key) REFERENCES label_key(key)-);---- key/value's are unique within the label_value table.-CREATE UNIQUE INDEX idx_label_value_key_value ON label_value(key, value);-```--#### Labels-We need some JOINs between project and label tables to find databases that match the label patterns in deployment configurations. This label has a [foreign key](https://www.sqlite.org/foreignkeys.html) to label_value table so that database labels can only use pre-defined keys and values. PRAGMA foreign_keys should be turned on.--```sql-CREATE TABLE db_label (- id INTEGER PRIMARY KEY AUTOINCREMENT,- row_status TEXT NOT NULL CHECK (- row_status IN ('NORMAL', 'ARCHIVED')- ) DEFAULT 'NORMAL',- creator_id INTEGER NOT NULL REFERENCES principal (id),- created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- updater_id INTEGER NOT NULL REFERENCES principal (id),- updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- database_id INTEGER NOT NULL REFERENCES db (id),- key TEXT NOT NULL,- value TEXT NOT NULL,- FOREIGN KEY(key, value) REFERENCES label_value(key, value)-);---- database_id/key's are unique within the db_label table.-CREATE UNIQUE INDEX idx_db_label_database_id_key ON db_label(database_id, key);-```--#### Deployment Configurations-```sql-CREATE TABLE deployment_config (- id INTEGER PRIMARY KEY AUTOINCREMENT,- row_status TEXT NOT NULL CHECK (- row_status IN ('NORMAL', 'ARCHIVED')- ) DEFAULT 'NORMAL',- creator_id INTEGER NOT NULL REFERENCES principal (id),- created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- updater_id INTEGER NOT NULL REFERENCES principal (id),- updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),- project_id INTEGER NOT NULL REFERENCES project (id),- name TEXT NOT NULL,- config TEXT NOT NULL-);--CREATE UNIQUE INDEX idx_deployment_config_project_id_name ON deployment_config(project_id, name);-```--#### Tenant Mode-This will be a new ENUM field on the existing [project table](https://github.com/bytebase/bytebase/blob/main/store/migration/10001##init_schema.sql#L202).--### Tenancy with different database names--There are use cases that customers put different tenant databases onto the same or a few instances. Since database names are unique within an instance, tenants will have different database names. There are two approaches to solve the problem by reusing most of the infrastructure above.--- Database naming template: most users have tenant names as part of database names such as `db1_customer1`, `db1_customer2`, `db2_customer1`, `db2_customer2`. We can allow users to provide a database name template e.g. `{{DB_NAME}}_{{TENANT}}` or `{{DB_NAME}}_{{LOCATION}}` to pin a collection of tenant databases with the same `{{DB_NAME}}` prefix. This name template is a project level setting which is allowed only for projects in tenant mode.-- Namespace: this is a database level setting similar to [k8s namespaces](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/). For example, all tenant databases with the same prefix `db1` are in the same namespace. Deployments and deployment configurations are tighted to namespaces.--We choose the first option because it is easy to understand, solving most use cases with minimal changes. More importantly, it's compatible with the second option if we want to support the rest use cases latter e.g. migrating existing tenant databases to Bytebase platform.--### API-- Available Label Keys: workspace level:Create(), Delete(), List(). Note: Create() and Delete() methods are not provided at first as described in the Label Design section.-- Labels: labels should be a field of database object.-- Deployment Configuration: project level Create(), Update(), Delete(), List().--## Appendix-### Reserved label keys-We have some reserved/built-in keys to simplify the onboarding and be consistent with other products in case of any future integrations.--| Name | Description |-| -------------- | ------------------------------------------------------------------ |-| location | The location of a database such as region, zone, datacenter names. |-| tenant | The tenant name of a customer. |-| environment | The environment name mapped from instance environment. |--Note, environment labels are reserved labels mapped from database instances' environments. This label is immutable and always returned from database label listing. It must be present and its value must match exactly with instance environment on setting the database labels. Since tenants are identified by labels in the deployment config, we need an environment labels to identify tenants from different environment in a schema update deployment. If we expose the environment label concept in the deployment config, it should look consistent in the label API.---### Octopus Tenant SaaS Deployment-https://octopus.com/docs/tenants/guides/multi-tenant-saas-application/creating-project-releasediff --git a/docs/testing.md b/docs/testing.mddeleted file mode 100644index 8a38a7730c..0000000000--- a/docs/testing.md+++ /dev/null@@ -1,68 +0,0 @@-# Testing--[Official Go test reference](https://pkg.go.dev/cmd/go#hdr-Testing_flags)--## Backend--Backend testing includes both unit testing and integration testing. Because manual testing is less efficient, all new features or code changes need defense from automated testing. Without it, no one knows when things will break.--All the Go integration tests is at [tests directory](https://github.com/bytebase/bytebase/tree/main/tests).--### Prerequisites--#### Prepare MySQL binaries--We embed MySQL binaries for testing. Run following command to download MySQL distributions first.--```shell-# Run this from the repo root-go generate -tags mysql ./...-```--#### Increase kernel shared memory for PostgreSQL--You may encounter following error while running the test--```shell-2022-11-29 11:07:36.391 CST [34173] FATAL: could not create shared memory segment: Cannot allocate memory-2022-11-29 11:07:36.391 CST [34173] DETAIL: Failed system call was shmget(key=41006308, size=56, 03600).-2022-11-29 11:07:36.391 CST [34173] HINT: This error usually means that PostgreSQL's request for a shared memory segment exceeded your kernel's SHMALL parameter. You might need to reconfigure the kernel with larger SHMALL.-The PostgreSQL documentation contains more information about shared memory configuration.-```--You need to increase kernels shared memory ([detailed explanation](https://dansketcher.com/2021/03/30/shmmax-error-on-big-sur)).--```shell-sudo sysctl -w kern.sysv.shmmax=12582912-sudo sysctl -w kern.sysv.shmall=12582912-```--### Run tests--#### Configure alias--```shell-alias t="go test -tags=mysql -v -run "-alias ta='t "" ./...'-```--#### Run all backend tests--```shell-# This will run all tests in current directory and its sub-directories-ta-```--#### Run integration tests--```shell-cd tests-# This will run all tests in current directory.-t ''-# This will run tests regex matching TestName in current directory.-t TestName-# This will run tests regex matching TestName in current directory and its sub-directories.-t TestName ./...-```--For every PR, there is GitHub action to run all integration test. If there is any failure, you can use keyword `--- FAIL:` to find the failed test and run the test on local workstation to troubleshoot issues.diff --git a/docs/writing-guide.md b/docs/writing-guide.mddeleted file mode 100644index 5a2cfa3d44..0000000000--- a/docs/writing-guide.md+++ /dev/null@@ -1,125 +0,0 @@-# Writing Guide--We produce content in both English and Chinese. We need to pay attention to the formatting in order to deliver a good reading experience.--# Pure English Article--Use English letters and 半角 symbols.--# Pure Chinese Article--Use Chinese characters and 全角 symbols, pure Chinese article is rare since many terms are English only.--# Mixed English and Chinese--Most aritcles fall into this category. The formatting gets tricky because we need to choose between 半角 and 全角. In general, we follow [中文文案排版指北](https://github.com/sparanoid/chinese-copywriting-guidelines/blob/master/README.zh-Hans.md), with the following exceptions:--1. For parentheses, use `半角英文括号()` instead of `全角括号()`.--# Example--> ❌ Github是一个代码版本控制系统(Version Control System),它的吉祥物是一只章鱼猫,英文叫 “Octocat”.->-> ✅ GitHub 是一个代码版本控制系统 (Version Control System),它的吉祥物是一只章鱼猫,英文叫「Octocat」。--Let's go over the issues one by one:--1. Case. Respect other brands.- > ❌ `Github`- >- > ✅ `GitHub`-1. Single whitespace between English and Chinese- > ❌ `GitHub是一个`- >- > ✅ `GitHub 是一个`-1. Parentheses- > ❌ `(Version Control System)`- >- > ✅ `(Version Control System)`-1. Comma- > ❌ `,`- >- > ✅ `,`-1. Quotation mark- > ❌ `“Octocat”`- >- > ✅ `「Octocat」`-1. Period- > ❌ `.`- >- > ✅ `。`--# Technical Writing Style Guide--We mainly follow [Google's style guide](https://developers.google.com/style)--1. Bold for UI Label. Skip 'button','label' and etc if it's obvious.--> ✅ Click **Settings**->-> ❌ Click **Settings** button->-> ❌ Click “Settings”->-> ❌ Click `Settings`->-> ❌ Click Settings button---2. Bold and initial capitalized for concept, roles, and etc.--> ✅ **Project** is the container to group logically related **Databases**, **Issues** and **Users** together.->-> ❌ `Project` is the container to group logically related `Databases`, `Issues` and `Users` together.---3. Quote for file name, file path, database name, instance name, and etc.--> ✅ The `Employee` project is created.->-> ❌ The **Employee** project is created.->-> ❌ The ”Employee” project is created.---4. Spell the number when it’s less than or equal to ten.--> ✅ one instance->-> ✅ two databases->-> ❌ 1 instance->-> ❌ 2 databases--5. Specify roles and plans at the top of each article if applicable. Use `<hint-block type="info">` component to wrap the sentence up.--> ✅-> This feature is only available for-> - **Workspace Admin** role-> - **Team** or **Enterprise** plan--6. For a task-based heading, start with a bare infinitive.--> ✅ Create an instance->-> ❌ Creating an instance--7. For a conceptual or non-task-based heading, use a noun phrase that doesn't start with an -ing verb.--> ✅ Migration to Google Cloud->-> ❌ Migrating to Google Cloud--8. Don't introduce a procedure with a partial sentence completed by the numbered steps.--> ✅ To customize the buttons, follow these steps:->-> ✅ Customize the buttons:->-> ❌ To customize the buttons:--# Readings--- [Docs for Developers](https://docsfordevelopers.com)-- [A Framework for Writing Better Documentation](https://documentation.divio.com/structure)diff --git a/proto/gen/grpc-doc/index.html b/proto/gen/grpc-doc/index.htmlindex 501beade23..d85386bde1 100644--- a/proto/gen/grpc-doc/index.html+++ b/proto/gen/grpc-doc/index.html@@ -20,7 +20,7 @@description: 'Bytebase API Reference',ogDescription: 'Bytebase API Reference',ogTitle: 'Bytebase API Reference',- ogImage: 'https://raw.githubusercontent.com/tianzhou/bytebase/main/docs/assets/banner.webp',+ ogImage: 'https://raw.githubusercontent.com/bytebase/bytebase/main/docs/assets/banner.webp',twitterCard: 'summary_large_image',}}