Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(semantic): restructure migration file structure (#1003)
Danny Xuc4f3c60b70c6
diff --git a/bin/server/cmd/profile_dev.go b/bin/server/cmd/profile_dev.goindex 26d4e53795..708b081725 100644--- a/bin/server/cmd/profile_dev.go+++ b/bin/server/cmd/profile_dev.go@@ -4,34 +4,36 @@package cmdimport (+ "fmt""time""github.com/blang/semver/v4"+ "github.com/bytebase/bytebase/common")func activeProfile(dataDir string, port, datastorePort int, isDemo bool) Profile {return Profile{- mode: "dev",+ mode: common.ReleaseModeDev,port: port,datastorePort: datastorePort,pgUser: "bbdev",dataDir: dataDir,- demoDataDir: "demo/test",+ demoDataDir: fmt.Sprintf("demo/%s", common.ReleaseModeDev),backupRunnerInterval: 10 * time.Second,- schemaVersion: semver.MustParse("1.1.0"),+ schemaVersion: semver.MustParse("1.1.2"),}}// GetTestProfile will return a profile for testing.func GetTestProfile(dataDir string, port, datastorePort int) Profile {return Profile{- mode: "dev",+ mode: common.ReleaseModeDev,port: port,datastorePort: datastorePort,pgUser: "bbtest",dataDir: dataDir,- demoDataDir: "demo/test",+ demoDataDir: fmt.Sprintf("demo/%s", common.ReleaseModeDev),backupRunnerInterval: 10 * time.Second,- schemaVersion: semver.MustParse("1.1.0"),+ schemaVersion: semver.MustParse("1.1.2"),}}diff --git a/bin/server/cmd/profile_release.go b/bin/server/cmd/profile_release.goindex 86cc868c4d..b959b62156 100644--- a/bin/server/cmd/profile_release.go+++ b/bin/server/cmd/profile_release.go@@ -12,16 +12,16 @@ import (func activeProfile(dataDir string, port, datastorePort int, isDemo bool) Profile {demoDataDir := ""if isDemo {- demoDataDir = "demo/release"+ demoDataDir = fmt.Sprintf("demo/%s", common.ReleaseModeRelease)}return Profile{- mode: "release",+ mode: common.ReleaseModeRelease,port: port,datastorePort: datastorePort,pgUser: "bb",dataDir: dataDir,demoDataDir: demoDataDir,backupRunnerInterval: 10 * time.Minute,- schemaVersion: semver.MustParse("1.0.0"),+ schemaVersion: semver.MustParse("1.0.1"),}}diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.goindex 6ae60dae18..761b498128 100644--- a/bin/server/cmd/root.go+++ b/bin/server/cmd/root.go@@ -134,7 +134,7 @@ func init() {// Profile is the configuration to start main server.type Profile struct {// mode can be "release" or "dev"- mode string+ mode common.ReleaseMode// port is the binding port for server.port int// datastorePort is the binding port for database instance for storing Bytebase data.@@ -347,7 +347,7 @@ func (m *Main) Run(ctx context.Context) error {Host: common.GetPostgresSocketDir(),Port: fmt.Sprintf("%d", m.profile.datastorePort),}- db := store.NewDB(m.l, connCfg, m.profile.demoDataDir, readonly, version, m.profile.schemaVersion)+ db := store.NewDB(m.l, connCfg, m.profile.demoDataDir, readonly, version, m.profile.schemaVersion, m.profile.mode)if err := db.Open(ctx); err != nil {return fmt.Errorf("cannot open db: %w", err)}diff --git a/common/config.go b/common/config.gonew file mode 100644index 0000000000..992d2ec449--- /dev/null+++ b/common/config.go@@ -0,0 +1,11 @@+package common++// ReleaseMode is the mode for release, such as dev or release.+type ReleaseMode string++const (+ // ReleaseModeRelease is the release mode.+ ReleaseModeRelease ReleaseMode = "release"+ // ReleaseModeDev is the dev mode.+ ReleaseModeDev ReleaseMode = "dev"+)diff --git a/enterprise/config/config.go b/enterprise/config/config.goindex 7c66303b57..599fcb2dbd 100644--- a/enterprise/config/config.go+++ b/enterprise/config/config.go@@ -5,6 +5,7 @@ import ("fmt""io/fs"+ "github.com/bytebase/bytebase/common""go.uber.org/zap")@@ -39,8 +40,8 @@ const ()// NewConfig will create a new enterprise config instance.-func NewConfig(l *zap.Logger, dataDir string, mode string) (*Config, error) {- l.Info("get project env", zap.String("env", mode))+func NewConfig(l *zap.Logger, dataDir string, mode common.ReleaseMode) (*Config, error) {+ l.Info("get project env", zap.String("env", string(mode)))filename := fmt.Sprintf("keys/%s.pub.pem", mode)licensePubKey, err := fs.ReadFile(keysFS, fmt.Sprintf("keys/%s.pub.pem", mode))diff --git a/enterprise/service/license.go b/enterprise/service/license.goindex 104a65141e..1ab97678be 100644--- a/enterprise/service/license.go+++ b/enterprise/service/license.go@@ -28,7 +28,7 @@ type Claims struct {}// NewLicenseService will create a new enterprise license service.-func NewLicenseService(l *zap.Logger, dataDir string, mode string) (*LicenseService, error) {+func NewLicenseService(l *zap.Logger, dataDir string, mode common.ReleaseMode) (*LicenseService, error) {config, err := config.NewConfig(l, dataDir, mode)if err != nil {return nil, errdiff --git a/server/jwt.go b/server/jwt.goindex 0bbd5f756b..51246c3878 100644--- a/server/jwt.go+++ b/server/jwt.go@@ -58,7 +58,7 @@ func getPrincipalIDContextKey() string {}// GenerateTokensAndSetCookies generates jwt token and saves it to the http-only cookie.-func GenerateTokensAndSetCookies(c echo.Context, user *api.Principal, mode string, secret string) error {+func GenerateTokensAndSetCookies(c echo.Context, user *api.Principal, mode common.ReleaseMode, secret string) error {accessToken, err := generateAccessToken(user, mode, secret)if err != nil {return fmt.Errorf("failed to generate access token: %w", err)@@ -78,12 +78,12 @@ func GenerateTokensAndSetCookies(c echo.Context, user *api.Principal, mode strinreturn nil}-func generateAccessToken(user *api.Principal, mode string, secret string) (string, error) {+func generateAccessToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {expirationTime := time.Now().Add(accessTokenDuration)return generateToken(user, fmt.Sprintf(accessTokenAudienceFmt, mode), expirationTime, []byte(secret))}-func generateRefreshToken(user *api.Principal, mode string, secret string) (string, error) {+func generateRefreshToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {expirationTime := time.Now().Add(refreshTokenDuration)return generateToken(user, fmt.Sprintf(refreshTokenAudienceFmt, mode), expirationTime, []byte(secret))}@@ -165,7 +165,7 @@ func removeUserCookie(c echo.Context) {// JWTMiddleware validates the access token.// If the access token is about to expire or has expired and the request has a valid refresh token, it// will try to generate new access token and refresh token.-func JWTMiddleware(l *zap.Logger, principalStore *store.Store, next echo.HandlerFunc, mode string, secret string) echo.HandlerFunc {+func JWTMiddleware(l *zap.Logger, principalStore *store.Store, next echo.HandlerFunc, mode common.ReleaseMode, secret string) echo.HandlerFunc {return func(c echo.Context) error {// Skips auth, actuator, planif common.HasPrefixes(c.Path(), "/api/auth", "/api/actuator", "/api/plan") {diff --git a/server/server.go b/server/server.goindex ea5ca72e52..ace84f923a 100644--- a/server/server.go+++ b/server/server.go@@ -69,7 +69,7 @@ type Server struct {l *zap.Loggerlvl *zap.AtomicLevelversion string- mode string+ mode common.ReleaseModehost stringport intfrontendHost string@@ -96,7 +96,7 @@ var casbinDBAPolicy stringvar casbinDeveloperPolicy string// NewServer creates a server.-func NewServer(logger *zap.Logger, storeInstance *store.Store, loggerLevel *zap.AtomicLevel, version string, host string, port int, frontendHost string, frontendPort, datastorePort int, mode string, dataDir string, backupRunnerInterval time.Duration, secret string, readonly bool, demo bool, debug bool) *Server {+func NewServer(logger *zap.Logger, storeInstance *store.Store, loggerLevel *zap.AtomicLevel, version string, host string, port int, frontendHost string, frontendPort, datastorePort int, mode common.ReleaseMode, dataDir string, backupRunnerInterval time.Duration, secret string, readonly bool, demo bool, debug bool) *Server {e := echo.New()e.Debug = debuge.HideBanner = truediff --git a/store/demo/test/10000__reset.sql b/store/demo/dev/10000__reset.sqlsimilarity index 100%rename from store/demo/test/10000__reset.sqlrename to store/demo/dev/10000__reset.sqldiff --git a/store/demo/test/10001__principal.sql b/store/demo/dev/10001__principal.sqlsimilarity index 100%rename from store/demo/test/10001__principal.sqlrename to store/demo/dev/10001__principal.sqldiff --git a/store/demo/test/10010__workspace.sql b/store/demo/dev/10010__workspace.sqlsimilarity index 100%rename from store/demo/test/10010__workspace.sqlrename to store/demo/dev/10010__workspace.sqldiff --git a/store/demo/test/10020__member.sql b/store/demo/dev/10020__member.sqlsimilarity index 100%rename from store/demo/test/10020__member.sqlrename to store/demo/dev/10020__member.sqldiff --git a/store/demo/test/10030__project.sql b/store/demo/dev/10030__project.sqlsimilarity index 100%rename from store/demo/test/10030__project.sqlrename to store/demo/dev/10030__project.sqldiff --git a/store/demo/test/10040__project_member.sql b/store/demo/dev/10040__project_member.sqlsimilarity index 100%rename from store/demo/test/10040__project_member.sqlrename to store/demo/dev/10040__project_member.sqldiff --git a/store/demo/test/10041__project_webhook.sql b/store/demo/dev/10041__project_webhook.sqlsimilarity index 100%rename from store/demo/test/10041__project_webhook.sqlrename to store/demo/dev/10041__project_webhook.sqldiff --git a/store/demo/test/10050__environment.sql b/store/demo/dev/10050__environment.sqlsimilarity index 100%rename from store/demo/test/10050__environment.sqlrename to store/demo/dev/10050__environment.sqldiff --git a/store/demo/test/10051__policy.sql b/store/demo/dev/10051__policy.sqlsimilarity index 100%rename from store/demo/test/10051__policy.sqlrename to store/demo/dev/10051__policy.sqldiff --git a/store/demo/test/10060__instance.sql b/store/demo/dev/10060__instance.sqlsimilarity index 100%rename from store/demo/test/10060__instance.sqlrename to store/demo/dev/10060__instance.sqldiff --git a/store/demo/test/10061__instance_user.sql b/store/demo/dev/10061__instance_user.sqlsimilarity index 100%rename from store/demo/test/10061__instance_user.sqlrename to store/demo/dev/10061__instance_user.sqldiff --git a/store/demo/test/10070__db.sql b/store/demo/dev/10070__db.sqlsimilarity index 100%rename from store/demo/test/10070__db.sqlrename to store/demo/dev/10070__db.sqldiff --git a/store/demo/test/10071__tbl.sql b/store/demo/dev/10071__tbl.sqlsimilarity index 100%rename from store/demo/test/10071__tbl.sqlrename to store/demo/dev/10071__tbl.sqldiff --git a/store/demo/test/10072__col.sql b/store/demo/dev/10072__col.sqlsimilarity index 100%rename from store/demo/test/10072__col.sqlrename to store/demo/dev/10072__col.sqldiff --git a/store/demo/test/10073__idx.sql b/store/demo/dev/10073__idx.sqlsimilarity index 100%rename from store/demo/test/10073__idx.sqlrename to store/demo/dev/10073__idx.sqldiff --git a/store/demo/test/10074__backup.sql b/store/demo/dev/10074__backup.sqlsimilarity index 100%rename from store/demo/test/10074__backup.sqlrename to store/demo/dev/10074__backup.sqldiff --git a/store/demo/test/10080__data_source.sql b/store/demo/dev/10080__data_source.sqlsimilarity index 100%rename from store/demo/test/10080__data_source.sqlrename to store/demo/dev/10080__data_source.sqldiff --git a/store/demo/test/10090__pipeline.sql b/store/demo/dev/10090__pipeline.sqlsimilarity index 100%rename from store/demo/test/10090__pipeline.sqlrename to store/demo/dev/10090__pipeline.sqldiff --git a/store/demo/test/10100__stage.sql b/store/demo/dev/10100__stage.sqlsimilarity index 100%rename from store/demo/test/10100__stage.sqlrename to store/demo/dev/10100__stage.sqldiff --git a/store/demo/test/10110__task.sql b/store/demo/dev/10110__task.sqlsimilarity index 100%rename from store/demo/test/10110__task.sqlrename to store/demo/dev/10110__task.sqldiff --git a/store/demo/test/10120__task_run.sql b/store/demo/dev/10120__task_run.sqlsimilarity index 100%rename from store/demo/test/10120__task_run.sqlrename to store/demo/dev/10120__task_run.sqldiff --git a/store/demo/test/10121__task_check_run.sql b/store/demo/dev/10121__task_check_run.sqlsimilarity index 100%rename from store/demo/test/10121__task_check_run.sqlrename to store/demo/dev/10121__task_check_run.sqldiff --git a/store/demo/test/10130__issue.sql b/store/demo/dev/10130__issue.sqlsimilarity index 100%rename from store/demo/test/10130__issue.sqlrename to store/demo/dev/10130__issue.sqldiff --git a/store/demo/test/10131__issue_subscriber.sql b/store/demo/dev/10131__issue_subscriber.sqlsimilarity index 100%rename from store/demo/test/10131__issue_subscriber.sqlrename to store/demo/dev/10131__issue_subscriber.sqldiff --git a/store/demo/test/10140__activity.sql b/store/demo/dev/10140__activity.sqlsimilarity index 100%rename from store/demo/test/10140__activity.sqlrename to store/demo/dev/10140__activity.sqldiff --git a/store/demo/test/10150__inbox.sql b/store/demo/dev/10150__inbox.sqlsimilarity index 100%rename from store/demo/test/10150__inbox.sqlrename to store/demo/dev/10150__inbox.sqldiff --git a/store/demo/test/10160__bookmark.sql b/store/demo/dev/10160__bookmark.sqlsimilarity index 100%rename from store/demo/test/10160__bookmark.sqlrename to store/demo/dev/10160__bookmark.sqldiff --git a/store/demo/test/10170__vcs.sql b/store/demo/dev/10170__vcs.sqlsimilarity index 100%rename from store/demo/test/10170__vcs.sqlrename to store/demo/dev/10170__vcs.sqldiff --git a/store/demo/test/10180__repository.sql b/store/demo/dev/10180__repository.sqlsimilarity index 100%rename from store/demo/test/10180__repository.sqlrename to store/demo/dev/10180__repository.sqldiff --git a/store/demo/test/10190__anomaly.sql b/store/demo/dev/10190__anomaly.sqlsimilarity index 100%rename from store/demo/test/10190__anomaly.sqlrename to store/demo/dev/10190__anomaly.sqldiff --git a/store/demo/test/10200__label.sql b/store/demo/dev/10200__label.sqlsimilarity index 100%rename from store/demo/test/10200__label.sqlrename to store/demo/dev/10200__label.sqldiff --git a/store/demo/test/10210__deployment_config.sql b/store/demo/dev/10210__deployment_config.sqlsimilarity index 100%rename from store/demo/test/10210__deployment_config.sqlrename to store/demo/dev/10210__deployment_config.sqldiff --git a/store/demo/test/10220__sheet.sql b/store/demo/dev/10220__sheet.sqlsimilarity index 100%rename from store/demo/test/10220__sheet.sqlrename to store/demo/dev/10220__sheet.sqldiff --git a/store/demo/test/README.md b/store/demo/dev/README.mdsimilarity index 100%rename from store/demo/test/README.mdrename to store/demo/dev/README.mddiff --git a/store/migration/1.1.0/0000_github_com.sql b/store/migration/dev/1.1/0000__github_com.sqlsimilarity index 100%rename from store/migration/1.1.0/0000_github_com.sqlrename to store/migration/dev/1.1/0000__github_com.sqldiff --git a/store/migration/1.1.0/0001_sheet_vcs.sql b/store/migration/dev/1.1/0001__sheet_vcs.sqlsimilarity index 100%rename from store/migration/1.1.0/0001_sheet_vcs.sqlrename to store/migration/dev/1.1/0001__sheet_vcs.sqldiff --git a/store/migration/1.1.0/0002_task_dag.sql b/store/migration/dev/1.1/0002__task_dag.sqlsimilarity index 100%rename from store/migration/1.1.0/0002_task_dag.sqlrename to store/migration/dev/1.1/0002__task_dag.sqldiff --git a/store/migration/1.1.0/latest.sql b/store/migration/dev/LATEST.sqlsimilarity index 100%rename from store/migration/1.1.0/latest.sqlrename to store/migration/dev/LATEST.sqldiff --git a/store/migration/1.0.0/latest_data.sql b/store/migration/dev/LATEST_DATA.sqlsimilarity index 100%rename from store/migration/1.0.0/latest_data.sqlrename to store/migration/dev/LATEST_DATA.sqldiff --git a/store/migration/1.0.0/latest.sql b/store/migration/release/1.0/0000__initial_schema.sqlsimilarity index 100%rename from store/migration/1.0.0/latest.sqlrename to store/migration/release/1.0/0000__initial_schema.sqldiff --git a/store/migration/1.1.0/latest_data.sql b/store/migration/release/1.0/0001__initial_data.sqlsimilarity index 100%rename from store/migration/1.1.0/latest_data.sqlrename to store/migration/release/1.0/0001__initial_data.sqldiff --git a/store/migration/release/LATEST.sql b/store/migration/release/LATEST.sqlnew file mode 100644index 0000000000..04b5bf07f7--- /dev/null+++ b/store/migration/release/LATEST.sql@@ -0,0 +1,1047 @@+-- Type+CREATE TYPE row_status AS ENUM ('NORMAL', 'ARCHIVED');++-- updated_ts trigger.+CREATE OR REPLACE FUNCTION trigger_update_updated_ts()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_ts = extract(epoch from now());+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++-- principal+CREATE TABLE principal (+ id SERIAL 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()),+ type TEXT NOT NULL CHECK (type IN ('END_USER', 'SYSTEM_BOT')),+ name TEXT NOT NULL,+ email TEXT NOT NULL,+ password_hash TEXT NOT NULL+);++CREATE UNIQUE INDEX idx_principal_unique_email ON principal(email);++CREATE TRIGGER update_principal_updated_ts+BEFORE+UPDATE+ ON principal FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Default bytebase system account id is 1+INSERT INTO+ principal (+ id,+ creator_id,+ updater_id,+ type,+ name,+ email,+ password_hash+ )+VALUES+ (+ 1,+ 1,+ 1,+ 'SYSTEM_BOT',+ 'Bytebase',+ '[email protected]',+ ''+ );++ALTER SEQUENCE principal_id_seq RESTART WITH 101;++-- Setting+CREATE TABLE setting (+ id SERIAL 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()),+ name TEXT NOT NULL,+ value TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT ''+);++CREATE UNIQUE INDEX idx_setting_unique_name ON setting(name);++ALTER SEQUENCE setting_id_seq RESTART WITH 101;++CREATE TRIGGER update_setting_updated_ts+BEFORE+UPDATE+ ON setting FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Member+-- We separate the concept from Principal because if we support multiple workspace in the future, each workspace can have different member for the same principal+CREATE TABLE member (+ id SERIAL 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()),+ status TEXT NOT NULL CHECK (status IN ('INVITED', 'ACTIVE')),+ role TEXT NOT NULL CHECK (role IN ('OWNER', 'DBA', 'DEVELOPER')),+ principal_id INTEGER NOT NULL REFERENCES principal (id)+);++CREATE UNIQUE INDEX idx_member_unique_principal_id ON member(principal_id);++ALTER SEQUENCE member_id_seq RESTART WITH 101;++CREATE TRIGGER update_member_updated_ts+BEFORE+UPDATE+ ON member FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Environment+CREATE TABLE environment (+ id SERIAL 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()),+ name TEXT NOT NULL,+ "order" INTEGER NOT NULL CHECK ("order" >= 0)+);++CREATE UNIQUE INDEX idx_environment_unique_name ON environment(name);++ALTER SEQUENCE environment_id_seq RESTART WITH 101;++CREATE TRIGGER update_environment_updated_ts+BEFORE+UPDATE+ ON environment FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Policy+-- policy stores the policies for each environment.+-- Policies are associated with environments. Since we may have policies not associated with environment later, we name the table policy.+CREATE TABLE policy (+ id SERIAL 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()),+ environment_id INTEGER NOT NULL REFERENCES environment (id),+ type TEXT NOT NULL CHECK (type LIKE 'bb.policy.%'),+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_policy_environment_id ON policy(environment_id);++CREATE UNIQUE INDEX idx_policy_unique_environment_id_type ON policy(environment_id, type);++ALTER SEQUENCE policy_id_seq RESTART WITH 101;++CREATE TRIGGER update_policy_updated_ts+BEFORE+UPDATE+ ON policy FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Project+CREATE TABLE project (+ id SERIAL 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()),+ name TEXT NOT NULL,+ key TEXT NOT NULL,+ workflow_type TEXT NOT NULL CHECK (workflow_type IN ('UI', 'VCS')),+ visibility TEXT NOT NULL CHECK (visibility IN ('PUBLIC', 'PRIVATE')),+ tenant_mode TEXT NOT NULL CHECK (tenant_mode IN ('DISABLED', 'TENANT')) DEFAULT 'DISABLED',+ -- db_name_template is only used when a project is in tenant mode.+ -- Empty value means {{DB_NAME}}.+ db_name_template TEXT NOT NULL,+ role_provider TEXT NOT NULL CHECK (role_provider IN ('BYTEBASE', 'GITLAB_SELF_HOST')) DEFAULT 'BYTEBASE'+);++CREATE UNIQUE INDEX idx_project_unique_key ON project(key);++INSERT INTO+ project (+ id,+ creator_id,+ updater_id,+ name,+ key,+ workflow_type,+ visibility,+ tenant_mode,+ db_name_template+ )+VALUES+ (+ 1,+ 1,+ 1,+ 'Default',+ 'DEFAULT',+ 'UI',+ 'PUBLIC',+ 'DISABLED',+ ''+ );++ALTER SEQUENCE project_id_seq RESTART WITH 101;++CREATE TRIGGER update_project_updated_ts+BEFORE+UPDATE+ ON project FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Project member+CREATE TABLE project_member (+ id SERIAL 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()),+ project_id INTEGER NOT NULL REFERENCES project (id),+ role TEXT NOT NULL CHECK (role IN ('OWNER', 'DEVELOPER')),+ principal_id INTEGER NOT NULL REFERENCES principal (id),+ role_provider TEXT NOT NULL CHECK (role_provider IN ('BYTEBASE', 'GITLAB_SELF_HOST')) DEFAULT 'BYTEBASE',+ -- payload is determined by the type of role_provider+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE UNIQUE INDEX idx_project_member_unique_project_id_role_provider_principal_id ON project_member(project_id, role_provider, principal_id);++ALTER SEQUENCE project_member_id_seq RESTART WITH 101;++CREATE TRIGGER update_project_member_updated_ts+BEFORE+UPDATE+ ON project_member FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Project Hook+CREATE TABLE project_webhook (+ id SERIAL 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()),+ project_id INTEGER NOT NULL REFERENCES project (id),+ type TEXT NOT NULL CHECK (type LIKE 'bb.plugin.webhook.%'),+ name TEXT NOT NULL,+ url TEXT NOT NULL,+ activity_list TEXT ARRAY NOT NULL+);++CREATE INDEX idx_project_webhook_project_id ON project_webhook(project_id);++CREATE UNIQUE INDEX idx_project_webhook_unique_project_id_url ON project_webhook(project_id, url);++ALTER SEQUENCE project_webhook_id_seq RESTART WITH 101;++CREATE TRIGGER update_project_webhook_updated_ts+BEFORE+UPDATE+ ON project_webhook FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Instance+CREATE TABLE instance (+ id SERIAL 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()),+ environment_id INTEGER NOT NULL REFERENCES environment (id),+ name TEXT NOT NULL,+ engine TEXT NOT NULL CHECK (engine IN ('MYSQL', 'POSTGRES', 'TIDB', 'CLICKHOUSE', 'SNOWFLAKE', 'SQLITE')),+ engine_version TEXT NOT NULL DEFAULT '',+ host TEXT NOT NULL,+ port TEXT NOT NULL,+ external_link TEXT NOT NULL DEFAULT ''+);++ALTER SEQUENCE instance_id_seq RESTART WITH 101;++CREATE TRIGGER update_instance_updated_ts+BEFORE+UPDATE+ ON instance FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Instance user stores the users for a particular instance+CREATE TABLE instance_user (+ id SERIAL 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()),+ instance_id INTEGER NOT NULL REFERENCES instance (id),+ name TEXT NOT NULL,+ "grant" TEXT NOT NULL+);++ALTER SEQUENCE instance_user_id_seq RESTART WITH 101;++CREATE UNIQUE INDEX idx_instance_user_unique_instance_id_name ON instance_user(instance_id, name);++CREATE TRIGGER update_instance_user_updated_ts+BEFORE+UPDATE+ ON instance_user FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- db stores the databases for a particular instance+-- data is synced periodically from the instance+CREATE TABLE db (+ id SERIAL 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()),+ instance_id INTEGER NOT NULL REFERENCES instance (id),+ project_id INTEGER NOT NULL REFERENCES project (id),+ -- If db is restored from a backup, then we will record that backup id. We can thus trace up to the original db.+ source_backup_id INTEGER,+ sync_status TEXT NOT NULL CHECK (sync_status IN ('OK', 'NOT_FOUND')),+ last_successful_sync_ts BIGINT NOT NULL,+ schema_version TEXT NOT NULL,+ name TEXT NOT NULL,+ character_set TEXT NOT NULL,+ "collation" TEXT NOT NULL+);++CREATE INDEX idx_db_instance_id ON db(instance_id);++CREATE UNIQUE INDEX idx_db_unique_instance_id_name ON db(instance_id, name);++ALTER SEQUENCE db_id_seq RESTART WITH 101;++CREATE TRIGGER update_db_updated_ts+BEFORE+UPDATE+ ON db FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- tbl stores the table for a particular database+-- data is synced periodically from the instance+CREATE TABLE tbl (+ id SERIAL 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()),+ database_id INTEGER NOT NULL REFERENCES db (id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ type TEXT NOT NULL,+ engine TEXT NOT NULL,+ "collation" TEXT NOT NULL,+ row_count BIGINT NOT NULL,+ data_size BIGINT NOT NULL,+ index_size BIGINT NOT NULL,+ data_free BIGINT NOT NULL,+ create_options TEXT NOT NULL,+ comment TEXT NOT NULL+);++CREATE INDEX idx_tbl_database_id ON tbl(database_id);++CREATE UNIQUE INDEX idx_tbl_unique_database_id_name ON tbl(database_id, name);++ALTER SEQUENCE tbl_id_seq RESTART WITH 101;++CREATE TRIGGER update_tbl_updated_ts+BEFORE+UPDATE+ ON tbl FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- col stores the column for a particular table from a particular database+-- data is synced periodically from the instance+CREATE TABLE col (+ id SERIAL 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()),+ database_id INTEGER NOT NULL REFERENCES db (id),+ table_id INTEGER NOT NULL REFERENCES tbl (id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ position INTEGER NOT NULL,+ "default" TEXT,+ nullable BOOLEAN NOT NULL,+ type TEXT NOT NULL,+ character_set TEXT NOT NULL,+ "collation" TEXT NOT NULL,+ comment TEXT NOT NULL+);++CREATE INDEX idx_col_database_id_table_id ON col(database_id, table_id);++CREATE UNIQUE INDEX idx_col_unique_database_id_table_id_name ON col(database_id, table_id, name);++ALTER SEQUENCE col_id_seq RESTART WITH 101;++CREATE TRIGGER update_col_updated_ts+BEFORE+UPDATE+ ON col FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- idx stores the index for a particular table from a particular database+-- data is synced periodically from the instance+CREATE TABLE idx (+ id SERIAL 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()),+ database_id INTEGER NOT NULL REFERENCES db (id),+ table_id INTEGER NOT NULL REFERENCES tbl (id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ expression TEXT NOT NULL,+ position INTEGER NOT NULL,+ type TEXT NOT NULL,+ "unique" BOOLEAN NOT NULL,+ visible BOOLEAN NOT NULL,+ comment TEXT NOT NULL+);++CREATE INDEX idx_idx_database_id_table_id ON idx(database_id, table_id);++CREATE UNIQUE INDEX idx_idx_unique_database_id_table_id_name_expression ON idx(database_id, table_id, name, expression);++ALTER SEQUENCE idx_id_seq RESTART WITH 101;++CREATE TRIGGER update_idx_updated_ts+BEFORE+UPDATE+ ON idx FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- vw stores the view for a particular database+-- data is synced periodically from the instance+CREATE TABLE vw (+ id SERIAL 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()),+ database_id INTEGER NOT NULL REFERENCES db (id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ definition TEXT NOT NULL,+ comment TEXT NOT NULL+);++CREATE INDEX idx_vw_database_id ON vw(database_id);++CREATE UNIQUE INDEX idx_vw_unique_database_id_name ON vw(database_id, name);++ALTER SEQUENCE vw_id_seq RESTART WITH 101;++CREATE TRIGGER update_vw_updated_ts+BEFORE+UPDATE+ ON vw FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- data_source table stores the data source for a particular database+CREATE TABLE data_source (+ id SERIAL 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()),+ instance_id INTEGER NOT NULL REFERENCES instance (id),+ database_id INTEGER NOT NULL REFERENCES db (id),+ name TEXT NOT NULL,+ type TEXT NOT NULL CHECK (type IN ('ADMIN', 'RW', 'RO')),+ username TEXT NOT NULL,+ password TEXT NOT NULL,+ ssl_key TEXT NOT NULL DEFAULT '',+ ssl_cert TEXT NOT NULL DEFAULT '',+ ssl_ca TEXT NOT NULL DEFAULT ''+);++CREATE INDEX idx_data_source_instance_id ON data_source(instance_id);++CREATE UNIQUE INDEX idx_data_source_unique_database_id_name ON data_source(database_id, name);++ALTER SEQUENCE data_source_id_seq RESTART WITH 101;++CREATE TRIGGER update_data_source_updated_ts+BEFORE+UPDATE+ ON data_source FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- backup stores the backups for a particular database.+CREATE TABLE backup (+ id SERIAL 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()),+ database_id INTEGER NOT NULL REFERENCES db (id),+ name TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('PENDING_CREATE', 'DONE', 'FAILED')),+ type TEXT NOT NULL CHECK (type IN ('MANUAL', 'AUTOMATIC')),+ storage_backend TEXT NOT NULL CHECK (storage_backend IN ('LOCAL', 'S3', 'GCS', 'OSS')),+ migration_history_version TEXT NOT NULL,+ path TEXT NOT NULL,+ comment TEXT NOT NULL DEFAULT ''+);++CREATE INDEX idx_backup_database_id ON backup(database_id);++CREATE UNIQUE INDEX idx_backup_unique_database_id_name ON backup(database_id, name);++ALTER SEQUENCE backup_id_seq RESTART WITH 101;++CREATE TRIGGER update_backup_updated_ts+BEFORE+UPDATE+ ON backup FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- backup_setting stores the backup settings for a particular database.+-- This is a strict version of cron expression using UTC timezone uniformly.+CREATE TABLE backup_setting (+ id SERIAL 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()),+ database_id INTEGER NOT NULL REFERENCES db (id),+ enabled BOOLEAN NOT NULL,+ hour INTEGER NOT NULL CHECK (hour >= 0 AND hour <= 23),+ -- day_of_week can be -1 which is wildcard (daily automatic backup).+ day_of_week INTEGER NOT NULL CHECK (day_of_week >= -1 AND day_of_week <= 6),+ -- hook_url is the callback url to be requested after a successful backup.+ hook_url TEXT NOT NULL+);++CREATE UNIQUE INDEX idx_backup_setting_unique_database_id ON backup_setting(database_id);++ALTER SEQUENCE backup_setting_id_seq RESTART WITH 101;++CREATE TRIGGER update_backup_setting_updated_ts+BEFORE+UPDATE+ ON backup_setting FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-----------------------+-- Pipeline related BEGIN+-- pipeline table+CREATE TABLE pipeline (+ id SERIAL 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()),+ name TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('OPEN', 'DONE', 'CANCELED'))+);++CREATE INDEX idx_pipeline_status ON pipeline(status);++ALTER SEQUENCE pipeline_id_seq RESTART WITH 101;++CREATE TRIGGER update_pipeline_updated_ts+BEFORE+UPDATE+ ON pipeline FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- stage table stores the stage for the pipeline+CREATE TABLE stage (+ id SERIAL 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()),+ pipeline_id INTEGER NOT NULL REFERENCES pipeline (id),+ environment_id INTEGER NOT NULL REFERENCES environment (id),+ name TEXT NOT NULL+);++CREATE INDEX idx_stage_pipeline_id ON stage(pipeline_id);++ALTER SEQUENCE stage_id_seq RESTART WITH 101;++CREATE TRIGGER update_stage_updated_ts+BEFORE+UPDATE+ ON stage FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- task table stores the task for the stage+CREATE TABLE task (+ id SERIAL 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()),+ pipeline_id INTEGER NOT NULL REFERENCES pipeline (id),+ stage_id INTEGER NOT NULL REFERENCES stage (id),+ instance_id INTEGER NOT NULL REFERENCES instance (id),+ -- Could be empty for creating database task when the task isn't yet completed successfully.+ database_id INTEGER REFERENCES db (id),+ name TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('PENDING', 'PENDING_APPROVAL', 'RUNNING', 'DONE', 'FAILED', 'CANCELED')),+ type TEXT NOT NULL CHECK (type LIKE 'bb.task.%'),+ payload JSONB NOT NULL DEFAULT '{}',+ earliest_allowed_ts BIGINT NOT NULL DEFAULT 0+);++CREATE INDEX idx_task_pipeline_id_stage_id ON task(pipeline_id, stage_id);++CREATE INDEX idx_task_status ON task(status);++CREATE INDEX idx_task_earliest_allowed_ts ON task(earliest_allowed_ts);++ALTER SEQUENCE task_id_seq RESTART WITH 101;++CREATE TRIGGER update_task_updated_ts+BEFORE+UPDATE+ ON task FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- task run table stores the task run+CREATE TABLE task_run (+ id SERIAL PRIMARY KEY,+ 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()),+ task_id INTEGER NOT NULL REFERENCES task (id),+ name TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('RUNNING', 'DONE', 'FAILED', 'CANCELED')),+ type TEXT NOT NULL CHECK (type LIKE 'bb.task.%'),+ code INTEGER NOT NULL DEFAULT 0,+ comment TEXT NOT NULL DEFAULT '',+ -- result saves the task run result in json format+ result JSONB NOT NULL DEFAULT '{}',+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_task_run_task_id ON task_run(task_id);++ALTER SEQUENCE task_run_id_seq RESTART WITH 101;++CREATE TRIGGER update_task_run_updated_ts+BEFORE+UPDATE+ ON task_run FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- task check run table stores the task check run+CREATE TABLE task_check_run (+ id SERIAL PRIMARY KEY,+ 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()),+ task_id INTEGER NOT NULL REFERENCES task (id),+ status TEXT NOT NULL CHECK (status IN ('RUNNING', 'DONE', 'FAILED', 'CANCELED')),+ type TEXT NOT NULL CHECK (type LIKE 'bb.task-check.%'),+ code INTEGER NOT NULL DEFAULT 0,+ comment TEXT NOT NULL DEFAULT '',+ -- result saves the task check run result in json format+ result JSONB NOT NULL DEFAULT '{}',+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_task_check_run_task_id ON task_check_run(task_id);++ALTER SEQUENCE task_check_run_id_seq RESTART WITH 101;++CREATE TRIGGER update_task_check_run_updated_ts+BEFORE+UPDATE+ ON task_check_run FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Pipeline related END+-----------------------+-- issue+-- Each issue links a pipeline driving the resolution.+CREATE TABLE issue (+ id SERIAL 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()),+ project_id INTEGER NOT NULL REFERENCES project (id),+ pipeline_id INTEGER NOT NULL REFERENCES pipeline (id),+ name TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('OPEN', 'DONE', 'CANCELED')),+ type TEXT NOT NULL CHECK (type LIKE 'bb.issue.%'),+ description TEXT NOT NULL DEFAULT '',+ -- While changing assignee_id, one should only change it to a non-robot DBA/owner.+ assignee_id INTEGER NOT NULL REFERENCES principal (id),+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_issue_project_id ON issue(project_id);++CREATE INDEX idx_issue_pipeline_id ON issue(pipeline_id);++CREATE INDEX idx_issue_creator_id ON issue(creator_id);++CREATE INDEX idx_issue_assignee_id ON issue(assignee_id);++CREATE INDEX idx_issue_created_ts ON issue(created_ts);++ALTER SEQUENCE issue_id_seq RESTART WITH 101;++CREATE TRIGGER update_issue_updated_ts+BEFORE+UPDATE+ ON issue FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- stores the issue subscribers. Unlike other tables, it doesn't have row_status/creator_id/created_ts/updater_id/updated_ts.+-- We use a separate table mainly because we can't leverage indexed query if the subscriber id is stored+-- as a comma separated id list in the issue table.+CREATE TABLE issue_subscriber (+ issue_id INTEGER NOT NULL REFERENCES issue (id),+ subscriber_id INTEGER NOT NULL REFERENCES principal (id),+ PRIMARY KEY (issue_id, subscriber_id)+);++CREATE INDEX idx_issue_subscriber_subscriber_id ON issue_subscriber(subscriber_id);++-- activity table stores the activity for the container such as issue+CREATE TABLE activity (+ id SERIAL 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()),+ container_id INTEGER NOT NULL CHECK (container_id > 0),+ type TEXT NOT NULL CHECK (type LIKE 'bb.%'),+ level TEXT NOT NULL CHECK (level IN ('INFO', 'WARN', 'ERROR')),+ comment TEXT NOT NULL DEFAULT '',+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_activity_container_id ON activity(container_id);++CREATE INDEX idx_activity_created_ts ON activity(created_ts);++ALTER SEQUENCE activity_id_seq RESTART WITH 101;++CREATE TRIGGER update_activity_updated_ts+BEFORE+UPDATE+ ON activity FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- inbox table stores the inbox entry for the corresponding activity.+-- Unlike other tables, it doesn't have row_status/creator_id/created_ts/updater_id/updated_ts.+-- We design in this way because:+-- 1. The table may potentially contain a lot of rows (an issue activity will generate one inbox record per issue subscriber)+-- 2. Does not provide much value besides what's contained in the related activity record.+CREATE TABLE inbox (+ id SERIAL PRIMARY KEY,+ receiver_id INTEGER NOT NULL REFERENCES principal (id),+ activity_id INTEGER NOT NULL REFERENCES activity (id),+ status TEXT NOT NULL CHECK (status IN ('UNREAD', 'READ'))+);++CREATE INDEX idx_inbox_receiver_id_activity_id ON inbox(receiver_id, activity_id);++CREATE INDEX idx_inbox_receiver_id_status ON inbox(receiver_id, status);++ALTER SEQUENCE inbox_id_seq RESTART WITH 101;++-- bookmark table stores the bookmark for the user+CREATE TABLE bookmark (+ id SERIAL 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()),+ name TEXT NOT NULL,+ link TEXT NOT NULL+);++CREATE UNIQUE INDEX idx_bookmark_unique_creator_id_link ON bookmark(creator_id, link);++ALTER SEQUENCE bookmark_id_seq RESTART WITH 101;++CREATE TRIGGER update_bookmark_updated_ts+BEFORE+UPDATE+ ON bookmark FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- vcs table stores the version control provider config+CREATE TABLE vcs (+ id SERIAL 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()),+ name TEXT NOT NULL,+ type TEXT NOT NULL CHECK (type IN ('GITLAB_SELF_HOST')),+ instance_url TEXT NOT NULL CHECK ((instance_url LIKE 'http://%' OR instance_url LIKE 'https://%') AND instance_url = rtrim(instance_url, '/')),+ api_url TEXT NOT NULL CHECK ((api_url LIKE 'http://%' OR api_url LIKE 'https://%') AND api_url = rtrim(api_url, '/')),+ application_id TEXT NOT NULL,+ secret TEXT NOT NULL+);++ALTER SEQUENCE vcs_id_seq RESTART WITH 101;++CREATE TRIGGER update_vcs_updated_ts+BEFORE+UPDATE+ ON vcs FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- repository table stores the repository setting for a project+-- A vcs is associated with many repositories.+-- A project can only link one repository (at least for now).+CREATE TABLE repository (+ id SERIAL 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()),+ vcs_id INTEGER NOT NULL REFERENCES vcs (id),+ project_id INTEGER NOT NULL REFERENCES project (id),+ -- Name from the corresponding VCS provider.+ -- For GitLab, this is the project name. e.g. project 1+ name TEXT NOT NULL,+ -- Full path from the corresponding VCS provider.+ -- For GitLab, this is the project full path. e.g. group1/project-1+ full_path TEXT NOT NULL,+ -- Web url from the corresponding VCS provider.+ -- For GitLab, this is the project web url. e.g. https://gitlab.example.com/group1/project-1+ web_url TEXT NOT NULL,+ -- Branch we are interested.+ -- For GitLab, this corresponds to webhook's push_events_branch_filter. Wildcard is supported+ branch_filter TEXT NOT NULL DEFAULT '',+ -- Base working directory we are interested.+ base_directory TEXT NOT NULL DEFAULT '',+ -- The file path template for matching the commited migration script.+ file_path_template TEXT NOT NULL DEFAULT '',+ -- The file path template for storing the latest schema auto-generated by Bytebase after migration.+ -- If empty, then Bytebase won't auto generate it.+ schema_path_template TEXT NOT NULL DEFAULT '',+ -- Repository id from the corresponding VCS provider.+ -- For GitLab, this is the project id. e.g. 123+ external_id TEXT NOT NULL,+ -- Push webhook id from the corresponding VCS provider.+ -- For GitLab, this is the project webhook id. e.g. 123+ external_webhook_id TEXT NOT NULL,+ -- Identify the host of the webhook url where the webhook event sends. We store this to identify stale webhook url whose url doesn't match the current bytebase --host.+ webhook_url_host TEXT NOT NULL,+ -- Identify the target repository receiving the webhook event. This is a random string.+ webhook_endpoint_id TEXT NOT NULL,+ -- For GitLab, webhook request contains this in the 'X-Gitlab-Token" header and we compare it with the one stored in db to validate it sends to the expected endpoint.+ webhook_secret_token TEXT NOT NULL,+ -- access_token, expires_ts, refresh_token belongs to the user linking the project to the VCS repository.+ access_token TEXT NOT NULL,+ expires_ts BIGINT NOT NULL,+ refresh_token TEXT NOT NULL+);++CREATE UNIQUE INDEX idx_repository_unique_project_id ON repository(project_id);++CREATE UNIQUE INDEX idx_repository_unique_webhook_endpoint_id ON repository(webhook_endpoint_id);++ALTER SEQUENCE repository_id_seq RESTART WITH 101;++CREATE TRIGGER update_repository_updated_ts+BEFORE+UPDATE+ ON repository FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Anomaly+-- anomaly stores various anomalies found by the scanner.+-- For now, anomaly can be associated with a particular instance or database.+CREATE TABLE anomaly (+ id SERIAL 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()),+ instance_id INTEGER NOT NULL REFERENCES instance (id),+ -- NULL if it's an instance anomaly+ database_id INTEGER NULL REFERENCES db (id),+ type TEXT NOT NULL CHECK (type LIKE 'bb.anomaly.%'),+ payload JSONB NOT NULL DEFAULT '{}'+);++CREATE INDEX idx_anomaly_instance_id_row_status_type ON anomaly(instance_id, row_status, type);+CREATE INDEX idx_anomaly_database_id_row_status_type ON anomaly(database_id, row_status, type);++ALTER SEQUENCE anomaly_id_seq RESTART WITH 101;++CREATE TRIGGER update_anomaly_updated_ts+BEFORE+UPDATE+ ON anomaly FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Label+-- label_key stores available label keys at workspace level.+CREATE TABLE label_key (+ id SERIAL 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()),+ key TEXT NOT NULL+);++-- key's are unique within the label_key table.+CREATE UNIQUE INDEX idx_label_key_unique_key ON label_key(key);++ALTER SEQUENCE label_key_id_seq RESTART WITH 101;++CREATE TRIGGER update_label_key_updated_ts+BEFORE+UPDATE+ ON label_key FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- label_value stores available label key values at workspace level.+CREATE TABLE label_value (+ id SERIAL 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()),+ key TEXT NOT NULL REFERENCES label_key(key),+ value TEXT NOT NULL+);++-- key/value's are unique within the label_value table.+CREATE UNIQUE INDEX idx_label_value_unique_key_value ON label_value(key, value);++ALTER SEQUENCE label_value_id_seq RESTART WITH 101;++CREATE TRIGGER update_label_value_updated_ts+BEFORE+UPDATE+ ON label_value FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- db_label stores labels asscociated with databases.+CREATE TABLE db_label (+ id SERIAL 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()),+ 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_unique_database_id_key ON db_label(database_id, key);++ALTER SEQUENCE db_label_id_seq RESTART WITH 101;++CREATE TRIGGER update_db_label_updated_ts+BEFORE+UPDATE+ ON db_label FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- Deployment Configuration.+-- deployment_config stores deployment configurations at project level.+CREATE TABLE deployment_config (+ id SERIAL 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()),+ project_id INTEGER NOT NULL REFERENCES project (id),+ name TEXT NOT NULL,+ config JSONB NOT NULL DEFAULT '{}'+);++CREATE UNIQUE INDEX idx_deployment_config_unique_project_id ON deployment_config(project_id);++ALTER SEQUENCE deployment_config_id_seq RESTART WITH 101;++CREATE TRIGGER update_deployment_config_updated_ts+BEFORE+UPDATE+ ON deployment_config FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();++-- sheet table stores general statements.+CREATE TABLE sheet (+ id SERIAL 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()),+ project_id INTEGER NOT NULL REFERENCES project (id),+ database_id INTEGER NULL REFERENCES db (id),+ name TEXT NOT NULL,+ statement TEXT NOT NULL,+ visibility TEXT NOT NULL CHECK (visibility IN ('PRIVATE', 'PROJECT', 'PUBLIC')) DEFAULT 'PRIVATE'+);++CREATE INDEX idx_sheet_creator_id ON sheet(creator_id);++CREATE INDEX idx_sheet_project_id_row_status ON sheet(project_id, row_status);++CREATE INDEX idx_sheet_database_id_row_status ON sheet(database_id, row_status);++ALTER SEQUENCE sheet_id_seq RESTART WITH 101;++CREATE TRIGGER update_sheet_updated_ts+BEFORE+UPDATE+ ON sheet FOR EACH ROW+EXECUTE FUNCTION trigger_update_updated_ts();diff --git a/store/migration/release/LATEST_DATA.sql b/store/migration/release/LATEST_DATA.sqlnew file mode 100644index 0000000000..b5cc1d7708--- /dev/null+++ b/store/migration/release/LATEST_DATA.sql@@ -0,0 +1,553 @@+-- Create "test" and "prod" environments+INSERT INTO+ environment (+ id,+ creator_id,+ updater_id,+ name,+ "order"+ )+VALUES+ (+ 101,+ 1,+ 1,+ 'Test',+ 0+ );++INSERT INTO+ environment (+ id,+ creator_id,+ updater_id,+ name,+ "order"+ )+VALUES+ (+ 102,+ 1,+ 1,+ 'Prod',+ 1+ );++ALTER SEQUENCE environment_id_seq RESTART WITH 103;++INSERT INTO+ policy (+ id,+ creator_id,+ updater_id,+ environment_id,+ type,+ payload+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 'bb.policy.pipeline-approval',+ '{"value":"MANUAL_APPROVAL_NEVER"}'+ );++INSERT INTO+ policy (+ id,+ creator_id,+ updater_id,+ environment_id,+ type,+ payload+ )+VALUES+ (+ 102,+ 1,+ 1,+ 102,+ 'bb.policy.pipeline-approval',+ '{"value":"MANUAL_APPROVAL_ALWAYS"}'+ );++INSERT INTO+ policy (+ id,+ creator_id,+ updater_id,+ environment_id,+ type,+ payload+ )+VALUES+ (+ 103,+ 1,+ 1,+ 102,+ 'bb.policy.backup-plan',+ '{"schedule":"WEEKLY"}'+ );++ALTER SEQUENCE policy_id_seq RESTART WITH 104;++-- Create label keys for `bb.location` and `bb.tenant`.+INSERT INTO+ label_key (+ id,+ creator_id,+ updater_id,+ key+ )+VALUES+ (+ 101,+ 1,+ 1,+ 'bb.location'+ );++INSERT INTO+ label_key (+ id,+ creator_id,+ updater_id,+ key+ )+VALUES+ (+ 102,+ 1,+ 1,+ 'bb.tenant'+ );++ALTER SEQUENCE label_key_id_seq RESTART WITH 103;++-- Create 1 "test", 1 "prod" instance (including * database and admin data source)+-- Both instances contains the connection info we expect user to setup according to https://bytebase.com/docs/install/install-with-docker#start-a-local-mysql-server-for-testing+-- Set host to 172.17.0.1 which is the default docker gateway ip.+-- Our quickstart guide suggests to run both Bytebase and MySQL using docker, and in such case, bytebase access the mysqld container via 172.17.0.1+-- "test" instance+INSERT INTO+ instance (+ id,+ creator_id,+ updater_id,+ environment_id,+ name,+ engine,+ engine_version,+ host,+ port,+ external_link+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 'Sample Test instance (Follow the "External Link" field to bring up the MySQL server)',+ 'MYSQL',+ '8.0.19',+ 'host.docker.internal',+ '3306',+ 'https://bytebase.com/docs/install/install-with-docker#start-a-local-mysql-server-for-testing'+ );++INSERT INTO+ instance (+ id,+ creator_id,+ updater_id,+ environment_id,+ name,+ engine,+ engine_version,+ host,+ port,+ external_link+ )+VALUES+ (+ 102,+ 1,+ 1,+ 102,+ 'Sample Prod instance (Follow the "External Link" field to bring up the MySQL server)',+ 'MYSQL',+ '8.0.19',+ 'host.docker.internal',+ '3306',+ 'https://bytebase.com/docs/install/install-with-docker#start-a-local-mysql-server-for-testing'+ );++ALTER SEQUENCE instance_id_seq RESTART WITH 103;++INSERT INTO+ db (+ id,+ creator_id,+ updater_id,+ instance_id,+ project_id,+ name,+ character_set,+ "collation",+ sync_status,+ last_successful_sync_ts,+ schema_version+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 1,+ '*',+ 'utf8mb4',+ 'utf8mb4_general_ci',+ 'OK',+ 0,+ ''+ );++INSERT INTO+ db (+ id,+ creator_id,+ updater_id,+ instance_id,+ project_id,+ name,+ character_set,+ "collation",+ sync_status,+ last_successful_sync_ts,+ schema_version+ )+VALUES+ (+ 102,+ 1,+ 1,+ 102,+ 1,+ '*',+ 'utf8mb4',+ 'utf8mb4_general_ci',+ 'OK',+ 0,+ ''+ );++ALTER SEQUENCE db_id_seq RESTART WITH 103;++INSERT INTO+ data_source (+ id,+ creator_id,+ updater_id,+ instance_id,+ database_id,+ name,+ TYPE,+ username,+ password+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 101,+ 'Admin data source',+ 'ADMIN',+ 'root',+ ''+ );++INSERT INTO+ data_source (+ id,+ creator_id,+ updater_id,+ instance_id,+ database_id,+ name,+ TYPE,+ username,+ password+ )+VALUES+ (+ 102,+ 1,+ 1,+ 102,+ 102,+ 'Admin data source',+ 'ADMIN',+ 'root',+ ''+ );++ALTER SEQUENCE data_source_id_seq RESTART WITH 103;++-- Create pipeline/stage/task/issue for onboarding+-- Create pipeline 101 "Hello world"+INSERT INTO+ pipeline (+ id,+ creator_id,+ updater_id,+ name,+ status+ )+VALUES+ (+ 101,+ 1,+ 1,+ 'Pipeline - Hello world',+ 'OPEN'+ );++ALTER SEQUENCE pipeline_id_seq RESTART WITH 102;++-- Create stage 101, 102 for pipeline 101+INSERT INTO+ stage (+ id,+ creator_id,+ updater_id,+ pipeline_id,+ environment_id,+ name+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 101,+ 'Test'+ );++INSERT INTO+ stage (+ id,+ creator_id,+ updater_id,+ pipeline_id,+ environment_id,+ name+ )+VALUES+ (+ 102,+ 1,+ 1,+ 101,+ 102,+ 'Prod'+ );++ALTER SEQUENCE stage_id_seq RESTART WITH 103;++-- Create task 101 for stage 101+INSERT INTO+ task (+ id,+ creator_id,+ updater_id,+ pipeline_id,+ stage_id,+ instance_id,+ database_id,+ name,+ type,+ status,+ payload+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 101,+ 101,+ NULL,+ 'Welcome',+ 'bb.task.general',+ 'RUNNING',+ '{"statement":"SELECT ''Welcome Builders'';"}'+ );++-- Create task 102 for stage 102+INSERT INTO+ task (+ id,+ creator_id,+ updater_id,+ pipeline_id,+ stage_id,+ instance_id,+ database_id,+ name,+ type,+ status,+ payload+ )+VALUES+ (+ 102,+ 1,+ 1,+ 101,+ 102,+ 102,+ NULL,+ 'Let''s go',+ 'bb.task.general',+ 'PENDING_APPROVAL',+ '{"statement":"SELECT ''Let''s go'';"}'+ );++ALTER SEQUENCE task_id_seq RESTART WITH 103;++-- Create task_run for task 101+INSERT INTO+ task_run (+ id,+ creator_id,+ updater_id,+ task_id,+ name,+ status,+ type,+ comment,+ result,+ payload+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 'Welcome',+ 'FAILED',+ 'bb.task.general',+ '',+ '{"detail":"Something is not right..."}',+ '{}'+ );++INSERT INTO+ task_run (+ id,+ creator_id,+ updater_id,+ task_id,+ name,+ status,+ type,+ comment,+ payload+ )+VALUES+ (+ 102,+ 1,+ 1,+ 101,+ 'Welcome',+ 'RUNNING',+ 'bb.task.general',+ 'Let''s give another try',+ '{}'+ );++ALTER SEQUENCE task_run_id_seq RESTART WITH 103;++-- Create issue 101 "Hello world"+INSERT INTO+ issue (+ id,+ creator_id,+ updater_id,+ project_id,+ pipeline_id,+ name,+ status,+ type,+ description,+ assignee_id+ )+VALUES+ (+ 101,+ 1,+ 1,+ 1,+ 101,+ 'Hello world!',+ 'OPEN',+ 'bb.issue.general',+ 'Welcome to Bytebase, this is the issue interface where developers and DBAs collaborate on database schema management issues such as: \n - Creating a new database\n - Creating a table\n - Creating an index\n - Adding/altering a column\n - Troubleshooting performance issue\nLet''s try some simple tasks:\n1. Bookmark this issue by clicking the star icon on the top of this page\n2. Leave a comment below to greet future comers\n3. Follow the Quickstart on the bottom left to get familiar with other features',+ 1+ );++ALTER SEQUENCE issue_id_seq RESTART WITH 102;++-- Create activity 101+INSERT INTO+ activity (+ id,+ creator_id,+ updater_id,+ container_id,+ type,+ level+ )+VALUES+ (+ 101,+ 1,+ 1,+ 101,+ 'bb.issue.create',+ 'INFO'+ );++INSERT INTO+ activity (+ id,+ creator_id,+ updater_id,+ container_id,+ type,+ level,+ comment+ )+VALUES+ (+ 102,+ 1,+ 1,+ 101,+ 'bb.issue.comment.create',+ 'INFO',+ 'Go fish!'+ );++ALTER SEQUENCE activity_id_seq RESTART WITH 103;diff --git a/store/pg_engine.go b/store/pg_engine.goindex f09fc28169..492cbef2f0 100644--- a/store/pg_engine.go+++ b/store/pg_engine.go@@ -1,7 +1,6 @@package storeimport (- "bytes""context""database/sql""embed"@@ -9,11 +8,13 @@ import ("io/fs""path/filepath""sort"+ "strconv""strings""time""github.com/blang/semver/v4"dbdriver "github.com/bytebase/bytebase/plugin/db"+ "github.com/pkg/errors"// Register postgres driver._ "github.com/bytebase/bytebase/plugin/db/pg"@@ -73,13 +74,16 @@ type DB struct {// schemaVersion is the version of Bytebase schema.schemaVersion semver.Version+ // mode is the mode of the release such as release or dev.+ mode common.ReleaseMode+// Returns the current time. Defaults to time.Now().// Can be mocked for tests.Now func() time.Time}// NewDB returns a new instance of DB associated with the given datasource name.-func NewDB(logger *zap.Logger, connCfg dbdriver.ConnectionConfig, demoDataDir string, readonly bool, serverVersion string, schemaVersion semver.Version) *DB {+func NewDB(logger *zap.Logger, connCfg dbdriver.ConnectionConfig, demoDataDir string, readonly bool, serverVersion string, schemaVersion semver.Version, mode common.ReleaseMode) *DB {db := &DB{l: logger,connCfg: connCfg,@@ -88,6 +92,7 @@ func NewDB(logger *zap.Logger, connCfg dbdriver.ConnectionConfig, demoDataDir stNow: time.Now,serverVersion: serverVersion,schemaVersion: schemaVersion,+ mode: mode,}return db}@@ -149,7 +154,7 @@ func (db *DB) Open(ctx context.Context) (err error) {return fmt.Errorf("failed to get current schema version: %w", err)}- if _, err := migrate(ctx, d, verBefore, db.schemaVersion, db.serverVersion, databaseName, db.l); err != nil {+ if _, err := migrate(ctx, d, verBefore, db.schemaVersion, db.mode, db.serverVersion, databaseName, db.l); err != nil {return fmt.Errorf("failed to migrate: %w", err)}@@ -246,8 +251,8 @@ func (db *DB) applyDataFile(name string) error {}const (- latestSchemaFile = "latest.sql"- latestDataFile = "latest_data.sql"+ latestSchemaFile = "LATEST.sql"+ latestDataFile = "LATEST_DATA.sql")// migrate sets up migration tracking and executes pending migration files.@@ -257,7 +262,7 @@ const (//// We prepend each migration file with version = xxx; Each migration// file run in a transaction to prevent partial migrations.-func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, cutoffSchemaVersion semver.Version, serverVersion, databaseName string, l *zap.Logger) (semver.Version, error) {+func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, cutoffSchemaVersion semver.Version, mode common.ReleaseMode, serverVersion, databaseName string, l *zap.Logger) (semver.Version, error) {l.Info("Apply database migration if needed...")l.Info(fmt.Sprintf("The release cutoff schema version: %s", cutoffSchemaVersion))if curVer == nil {@@ -272,12 +277,12 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, cut// Initial schema setup.if curVer == nil {- latestSchemaPath := fmt.Sprintf("migration/%s/%s", cutoffSchemaVersion.String(), latestSchemaFile)+ latestSchemaPath := fmt.Sprintf("migration/%s/%s", mode, latestSchemaFile)buf, err := migrationFS.ReadFile(latestSchemaPath)if err != nil {return semver.Version{}, fmt.Errorf("failed to read latest schema %q, error %w", latestSchemaPath, err)}- latestDataPath := fmt.Sprintf("migration/%s/%s", cutoffSchemaVersion.String(), latestDataFile)+ latestDataPath := fmt.Sprintf("migration/%s/%s", mode, latestDataFile)dataBuf, err := migrationFS.ReadFile(latestDataPath)if err != nil {return semver.Version{}, fmt.Errorf("failed to read latest data %q, error %w", latestSchemaPath, err)@@ -308,113 +313,181 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, cut}// Apply migrations- versions, err := getMigrationFileVersions()- if err != nil {- return semver.Version{}, err- }+ retVersion := *curVer- migrateVersions, messages := getMigrationVersions(versions, cutoffSchemaVersion, *curVer)- for _, message := range messages {- l.Info(message)+ releaseModes := []common.ReleaseMode{common.ReleaseModeRelease}+ if mode == common.ReleaseModeDev {+ releaseModes = append(releaseModes, common.ReleaseModeDev)}- if len(migrateVersions) == 0 {- l.Info(fmt.Sprintf("Database schema is already at version %s; skip migration.", cutoffSchemaVersion))- }+ for _, releaseMode := range releaseModes {+ names, err := fs.Glob(migrationFS, fmt.Sprintf("migration/%s/*", releaseMode))+ if err != nil {+ return semver.Version{}, err+ }- retVersion := semver.Version{}- for _, version := range migrateVersions {- // Migrate migration files.- l.Info(fmt.Sprintf("Migrating %s...", version))- names, err := fs.Glob(migrationFS, fmt.Sprintf("migration/%s/*.sql", version))+ minorVersions, messages, err := getMinorMigrationVersions(names, cutoffSchemaVersion, *curVer)if err != nil {return semver.Version{}, err}- var stmtBuf bytes.Buffer- var baseNames []string- for _, name := range names {- // Skip the latest sql file.- baseName := filepath.Base(name)- if baseName == latestSchemaFile {- continue- }- if baseName == latestDataFile {- continue- }- baseNames = append(baseNames, baseName)- buf, err := fs.ReadFile(migrationFS, name)+ for _, message := range messages {+ l.Info(message)+ }+ if len(minorVersions) == 0 {+ l.Info(fmt.Sprintf("Skip minor version migration in mode %s. No new version.", releaseMode))+ continue+ }++ for _, minorVersion := range minorVersions {+ l.Info(fmt.Sprintf("Starting minor version migration cycle from %s ...", minorVersion))+ names, err := fs.Glob(migrationFS, fmt.Sprintf("migration/%s/%d.%d/*.sql", releaseMode, minorVersion.Major, minorVersion.Minor))if err != nil {- return semver.Version{}, fmt.Errorf("failed to read migration file %q, error %w", name, err)+ return semver.Version{}, err}- if _, err := stmtBuf.Write(buf); err != nil {- return semver.Version{}, fmt.Errorf("failed to write buffer for migration file %q, error %w", name, err)+ patchVersions, err := getPatchVersions(minorVersion, cutoffSchemaVersion, *curVer, names)+ if err != nil {+ return semver.Version{}, err}- if _, err := stmtBuf.WriteString("\n\n"); err != nil {- return semver.Version{}, fmt.Errorf("failed to write newline buffer for migration file %q, error %w", name, err)++ for _, pv := range patchVersions {+ l.Info(fmt.Sprintf("Migrating %s...", pv.version))+ buf, err := fs.ReadFile(migrationFS, pv.filename)+ if err != nil {+ return semver.Version{}, fmt.Errorf("failed to read migration file %q, error %w", pv.filename, err)+ }+ if _, _, err := d.ExecuteMigration(+ ctx,+ &dbdriver.MigrationInfo{+ ReleaseVersion: serverVersion,+ UseSemanticVersion: true,+ Version: pv.version.String(),+ SemanticVersionSuffix: time.Now().Format("20060102150405"),+ 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),+ },+ string(buf),+ ); err != nil {+ return semver.Version{}, fmt.Errorf("failed to migrate schema version %q, error: %v", pv.version, err)+ }+ retVersion = pv.version}- l.Debug(fmt.Sprintf("Reading migration file %q.", name))}- if _, _, err := d.ExecuteMigration(- ctx,- &dbdriver.MigrationInfo{- ReleaseVersion: serverVersion,- UseSemanticVersion: true,- Version: version.String(),- SemanticVersionSuffix: time.Now().Format("20060102150405"),- 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.", version, serverVersion, strings.Join(baseNames, ", ")),- },- stmtBuf.String(),- ); err != nil {- return semver.Version{}, fmt.Errorf("failed to migrate schema version %q, error: %v", version, err)- }- retVersion = version}- l.Info(fmt.Sprintf("Completed database migration with version %s.", cutoffSchemaVersion))+ if retVersion.EQ(*curVer) {+ l.Info(fmt.Sprintf("Database schema is at version %s; nothing to migrate.", *curVer))+ } else {+ l.Info(fmt.Sprintf("Completed database migration from version %s to %s.", *curVer, retVersion))+ }+return retVersion, nil}-func getMigrationFileVersions() ([]semver.Version, error) {- versionNames, err := fs.Glob(migrationFS, "migration/*")- if err != nil {- return nil, err- }- var versions []semver.Version- for _, name := range versionNames {- v, err := semver.Make(strings.TrimPrefix(name, "migration/"))+type patchVersion struct {+ version semver.Version+ filename string+}++// getPatchVersions gets the patch versions above the current version in a minor version directory.+func getPatchVersions(minorVersion semver.Version, releaseCutSchemaVersion, currentVersion semver.Version, names []string) ([]patchVersion, error) {+ var patchVersions []patchVersion+ for _, name := range names {+ baseName := filepath.Base(name)+ patch, err := getPatchVersion(baseName)if err != nil {- return nil, fmt.Errorf("invalid migration file path %q, error %w", name, err)+ return nil, err}- versions = append(versions, v)+ version := minorVersion+ version.Patch = uint64(patch)+ if version.GT(releaseCutSchemaVersion) {+ continue+ }+ if version.LE(currentVersion) {+ continue+ }++ patchVersions = append(patchVersions,+ patchVersion{+ version: version,+ filename: name,+ },+ )}- // Sort the migration semantic version in ascending order.- sort.Slice(versions, func(i, j int) bool {- return versions[i].LT(versions[j])+ if len(patchVersions) == 0 {+ return nil, nil+ }+ // Sort patch version in ascending order.+ sort.Slice(patchVersions, func(i, j int) bool {+ return patchVersions[i].version.LT(patchVersions[j].version)})- return versions, nil+ return patchVersions, nil+}++func getPatchVersion(name string) (int64, error) {+ parts := strings.Split(name, "__")+ if len(parts) != 2 {+ return 0, fmt.Errorf("migration filename %q should include '__'", name)+ }+ patch, err := strconv.ParseInt(parts[0], 10, 64)+ if err != nil {+ return 0, errors.Wrapf(err, "migration filename prefix %q should be four digits integer such as '0000'", parts[0])+ }+ return patch, nil}-func getMigrationVersions(versions []semver.Version, releaseCutSchemaVersion, currentVersion semver.Version) ([]semver.Version, []string) {+// getMinorMigrationVersions gets all the versions between currentVersion (included) and releaseCutVersion(included).+func getMinorMigrationVersions(names []string, releaseCutSchemaVersion, currentVersion semver.Version) ([]semver.Version, []string, error) {+ versions, err := getMinorVersions(names)+ if err != nil {+ return nil, nil, err+ }++ // We should still include the version with the same minor version with currentVersion in case we have missed some patches.+ currentVersion.Patch = 0+var migrateVersions []semver.Versionvar messages []stringfor _, version := range versions {// If the migration version is greater than the schema version this build expects, we will skip the migration.if version.GT(releaseCutSchemaVersion) {- messages = append(messages, fmt.Sprintf("Skip this migration: %s; the corresponding migration version %s is bigger than maximum schema version %s.", version, version, releaseCutSchemaVersion))+ messages = append(messages, fmt.Sprintf("Skip migration %s; the corresponding migration version %s is bigger than maximum schema version %s.", version, version, releaseCutSchemaVersion))continue}- // If the migration version is less than or equal to the current version, we will skip the migration since it's already applied.- if version.LE(currentVersion) {- messages = append(messages, fmt.Sprintf("Skip this migration: %s; the current schema version %s is higher.", version, currentVersion))+ // If the migration version is less than to the current version, we will skip the migration since it's already applied.+ // We should still double check the current version in case there's any patch needed.+ if version.LT(currentVersion) {+ messages = append(messages, fmt.Sprintf("Skip migration %s; the current schema version %s is higher.", version, currentVersion))continue}migrateVersions = append(migrateVersions, version)}- return migrateVersions, messages+ return migrateVersions, messages, nil+}++// getMinorVersions returns the minor release versions based on file names in the release or dev directory.+func getMinorVersions(names []string) ([]semver.Version, error) {+ var versions []semver.Version+ for _, name := range names {+ baseName := filepath.Base(name)+ if baseName == latestSchemaFile || baseName == latestDataFile {+ continue+ }+ // Convert minor version to semantic version format, e.g. "1.12" will be "1.12.0".+ s := fmt.Sprintf("%s.0", baseName)+ v, err := semver.Make(s)+ if err != nil {+ return nil, fmt.Errorf("invalid migration file path %q, error %w", name, err)+ }+ versions = append(versions, v)+ }+ // Sort the migration semantic version in ascending order.+ sort.Slice(versions, func(i, j int) bool {+ return versions[i].LT(versions[j])+ })+ return versions, nil}// Close closes the database connection.diff --git a/store/pg_engine_test.go b/store/pg_engine_test.goindex 21c6841f20..7bfb599019 100644--- a/store/pg_engine_test.go+++ b/store/pg_engine_test.go@@ -3,6 +3,7 @@ package storeimport ("context""fmt"+ "io/fs""os""path""strings"@@ -16,47 +17,146 @@ import ("go.uber.org/zap")-func TestGetMigrationVersions(t *testing.T) {- versions := []semver.Version{semver.MustParse("1.0.0"), semver.MustParse("1.1.0"), semver.MustParse("1.1.1"), semver.MustParse("1.2.0"), semver.MustParse("1.3.0")}+func TestGetMinorMigrationVersions(t *testing.T) {+ names := []string{latestDataFile, latestSchemaFile, "1.0", "1.1", "1.2", "1.3", "1.4"}tests := []struct {- versions []semver.Version+ names []stringreleaseCutSchemaVersion semver.VersioncurrentVersion semver.Versionwant []semver.Version}{{- versions,- semver.MustParse("1.0.0"),- semver.MustParse("1.0.0"),- nil,+ names: names,+ releaseCutSchemaVersion: semver.MustParse("1.0.0"),+ currentVersion: semver.MustParse("1.0.0"),+ want: []semver.Version{semver.MustParse("1.0.0")},},{- versions,- semver.MustParse("1.1.1"),- semver.MustParse("1.1.1"),- nil,+ names: names,+ releaseCutSchemaVersion: semver.MustParse("1.3.3"),+ currentVersion: semver.MustParse("1.3.0"),+ want: []semver.Version{semver.MustParse("1.3.0")},},{- versions,- semver.MustParse("1.1.1"),- semver.MustParse("1.0.0"),- []semver.Version{semver.MustParse("1.1.0"), semver.MustParse("1.1.1")},+ names: names,+ releaseCutSchemaVersion: semver.MustParse("1.3.0"),+ currentVersion: semver.MustParse("1.0.3"),+ want: []semver.Version{semver.MustParse("1.0.0"), semver.MustParse("1.1.0"), semver.MustParse("1.2.0"), semver.MustParse("1.3.0")},},{- versions,- semver.MustParse("1.3.0"),- semver.MustParse("1.0.0"),- []semver.Version{semver.MustParse("1.1.0"), semver.MustParse("1.1.1"), semver.MustParse("1.2.0"), semver.MustParse("1.3.0")},+ names: names,+ releaseCutSchemaVersion: semver.MustParse("1.3.0"),+ currentVersion: semver.MustParse("1.2.2"),+ want: []semver.Version{semver.MustParse("1.2.0"), semver.MustParse("1.3.0")},},}for _, test := range tests {- migrateVersions, _ := getMigrationVersions(test.versions, test.releaseCutSchemaVersion, test.currentVersion)+ migrateVersions, _, _ := getMinorMigrationVersions(test.names, test.releaseCutSchemaVersion, test.currentVersion)require.Equal(t, test.want, migrateVersions)}}+func TestGetMinorVersions(t *testing.T) {+ tests := []struct {+ names []string+ want []semver.Version+ }{+ {+ names: []string{fmt.Sprintf("migration/dev/%s", latestDataFile), fmt.Sprintf("migration/dev/%s", latestSchemaFile), "migration/dev/1.1", "migration/dev/1.0"},+ want: []semver.Version{semver.MustParse("1.0.0"), semver.MustParse("1.1.0")},+ },+ {+ names: []string{fmt.Sprintf("migration/release/%s", latestDataFile), fmt.Sprintf("migration/dev/%s", latestSchemaFile)},+ want: nil,+ },+ }++ for _, test := range tests {+ got, _ := getMinorVersions(test.names)+ require.Equal(t, test.want, got)+ }+}++func TestGetPatchVersions(t *testing.T) {+ tests := []struct {+ names []string+ minorVersion semver.Version+ releaseCutSchemaVersion semver.Version+ currentVersion semver.Version+ want []patchVersion+ errPart string+ }{+ {+ names: []string{"0000__hello.sql", "0001__world.sql"},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.3.0"),+ currentVersion: semver.MustParse("1.2.3"),+ want: nil,+ errPart: "",+ },+ {+ names: []string{"0000__hello.sql", "0001__world.sql"},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.3.0"),+ currentVersion: semver.MustParse("1.0.0"),+ want: []patchVersion{{semver.MustParse("1.1.0"), "0000__hello.sql"}, {semver.MustParse("1.1.1"), "0001__world.sql"}},+ errPart: "",+ },+ {+ names: []string{"0000__hello.sql", "0001__world.sql"},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.1.0"),+ currentVersion: semver.MustParse("1.0.0"),+ want: []patchVersion{{semver.MustParse("1.1.0"), "0000__hello.sql"}},+ errPart: "",+ },+ {+ names: []string{"0000__hello.sql", "0001__world.sql"},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.3.0"),+ currentVersion: semver.MustParse("1.1.0"),+ want: []patchVersion{{semver.MustParse("1.1.1"), "0001__world.sql"}},+ errPart: "",+ },+ {+ names: []string{},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.3.0"),+ currentVersion: semver.MustParse("1.0.0"),+ want: nil,+ errPart: "",+ },+ {+ names: []string{"0000_hello.sql"},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.1.0"),+ currentVersion: semver.MustParse("1.0.0"),+ want: nil,+ errPart: "should include '__'",+ },+ {+ names: []string{"00a0__hello.sql"},+ minorVersion: semver.MustParse("1.1.0"),+ releaseCutSchemaVersion: semver.MustParse("1.1.0"),+ currentVersion: semver.MustParse("1.0.0"),+ want: nil,+ errPart: "should be four digits integer",+ },+ }++ for _, test := range tests {+ got, err := getPatchVersions(test.minorVersion, test.releaseCutSchemaVersion, test.currentVersion, test.names)+ if test.errPart == "" {+ require.NoError(t, err)+ } else {+ require.Contains(t, err.Error(), test.errPart)+ }+ require.Equal(t, test.want, got)+ }+}+var (pgUser = "test"pgPort = 6000@@ -91,30 +191,46 @@ func TestMigrationCompatibility(t *testing.T) {err = d.SetupMigrationIfNeeded(ctx)require.NoError(t, err)- versions, err := getMigrationFileVersions()+ // Create a database with dev latest schema.+ names, err := fs.Glob(migrationFS, fmt.Sprintf("migration/%s/*", common.ReleaseModeDev))+ require.NoError(t, err)+ versions, err := getMinorVersions(names)+ require.NoError(t, err)+ require.Len(t, versions, 1)+ names, err = fs.Glob(migrationFS, fmt.Sprintf("migration/%s/%d.%d/*.sql", common.ReleaseModeDev, versions[0].Major, versions[0].Minor))require.NoError(t, err)+ devVersion := versions[0]+ devPatches := len(names)+ if devPatches > 0 {+ devVersion.Patch = uint64(devPatches - 1)+ }+ devDatabaseName := getDatabaseName(devVersion)+ // Passing curVers = nil will create the database.+ ver, err := migrate(ctx, d, nil, devVersion, common.ReleaseModeDev, serverVersion, devDatabaseName, l)+ require.NoError(t, err)+ require.Equal(t, devVersion, ver)- // For every version, we create a database with the schema of that version and apply migrations till the latest version in the migration directory.- // For example, we can 3 versions, 1.0.0, 1.1.0, 1.2.0.- // Create a database with 1.0.0 schema, apply 1.1.0 migration, and apply 1.2.0 migration.- // Create a database with 1.1.0 schema, and apply 1.2.0 migration.- // Create a database with 1.2.0 schema. But there is no migration since it's the latest.- for i := range versions {- initialVersion := versions[i]- initialDatabaseName := getDatabaseName(initialVersion)- // Passing curVers = nil will create the database.- ver, err := migrate(ctx, d, nil, initialVersion, serverVersion, initialDatabaseName, l)+ // Create a database with release latest schema, and apply migration to dev latest.+ names, err = fs.Glob(migrationFS, fmt.Sprintf("migration/%s/*", common.ReleaseModeDev))+ require.NoError(t, err)+ versions, err = getMinorVersions(names)+ require.NoError(t, err)+ require.GreaterOrEqual(t, len(versions), 1)+ minorVersion := versions[len(versions)-1]+ names, err = fs.Glob(migrationFS, fmt.Sprintf("migration/%s/%d.%d/*.sql", common.ReleaseModeRelease, minorVersion.Major, minorVersion.Minor))+ require.NoError(t, err)+ prodVersion := minorVersion+ prodVersion.Patch = uint64(len(names))+ prodDatabaseName := getDatabaseName(prodVersion)+ // Passing curVers = nil will create the database.+ ver, err = migrate(ctx, d, nil, prodVersion, common.ReleaseModeRelease, serverVersion, prodDatabaseName, l)+ require.NoError(t, err)+ require.Equal(t, prodVersion, ver)+ // Apply migration to dev latest if there are patches.+ if devPatches > 0 {+ ver, err = migrate(ctx, d, &prodVersion, devVersion, common.ReleaseModeDev, serverVersion, prodDatabaseName, l)require.NoError(t, err)- require.Equal(t, initialVersion, ver)-- currentVersion := initialVersion- for j := i + 1; j < len(versions); j++ {- version := versions[j]- ver, err = migrate(ctx, d, ¤tVersion, version, serverVersion, initialDatabaseName, l)- require.NoError(t, err)- require.Equal(t, version, ver)- currentVersion = version- }+ require.Equal(t, devVersion, ver)}}