Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: action e2e test (#16813)

p0ny9ee2d57c78e9
diff --git a/action/command/check.go b/action/command/check.go
index cb66b89877..1419afe215 100644
--- a/action/command/check.go
+++ b/action/command/check.go
@@ -1,8 +1,6 @@
package command
import (
- "log/slog"
-
"github.com/pkg/errors"
"github.com/spf13/cobra"
@@ -26,7 +24,14 @@ func NewCheckCommand(w *world.World) *cobra.Command {
}
func validateCheckFlags(w *world.World) func(*cobra.Command, []string) error {
- return func(*cobra.Command, []string) error {
+ return func(cmd *cobra.Command, args []string) error {
+ if p := cmd.Parent(); p != nil {
+ if p.PersistentPreRunE != nil {
+ if err := p.PersistentPreRunE(cmd, args); err != nil {
+ return err
+ }
+ }
+ }
switch w.CheckRelease {
case "SKIP", "FAIL_ON_WARNING", "FAIL_ON_ERROR":
default:
@@ -38,17 +43,17 @@ func validateCheckFlags(w *world.World) func(*cobra.Command, []string) error {
func runCheck(w *world.World) func(*cobra.Command, []string) error {
return func(*cobra.Command, []string) error {
- platform := getJobPlatform()
- slog.Info("running on platform", "platform", platform.String())
+ platform := w.Platform
+ w.Logger.Info("running on platform", "platform", platform.String())
client, err := NewClient(w.URL, w.ServiceAccount, w.ServiceAccountSecret)
if err != nil {
return err
}
// Check version compatibility
- checkVersionCompatibility(client, args.Version)
+ checkVersionCompatibility(w, client, args.Version)
- releaseFiles, err := getReleaseFiles(w.FilePattern)
+ releaseFiles, err := getReleaseFiles(w, w.FilePattern)
if err != nil {
return err
}
@@ -60,23 +65,23 @@ func runCheck(w *world.World) func(*cobra.Command, []string) error {
return err
}
- slog.Info("check release response", "resultCount", len(checkReleaseResponse.Results))
+ w.Logger.Info("check release response", "resultCount", len(checkReleaseResponse.Results))
// Generate platform-specific outputs
switch platform {
- case GitHub:
+ case world.GitHub:
if err := github.CreateCommentAndAnnotation(checkReleaseResponse); err != nil {
return err
}
- case GitLab:
+ case world.GitLab:
if err := writeReleaseCheckToCodeQualityJSON(checkReleaseResponse); err != nil {
return err
}
- case AzureDevOps:
+ case world.AzureDevOps:
if err := loggingReleaseChecks(checkReleaseResponse); err != nil {
return err
}
- case Bitbucket:
+ case world.Bitbucket:
if err := createBitbucketReport(checkReleaseResponse); err != nil {
return err
}
diff --git a/action/command/file.go b/action/command/file.go
index df79817413..8071547a0c 100644
--- a/action/command/file.go
+++ b/action/command/file.go
@@ -1,16 +1,16 @@
package command
import (
- "log/slog"
"os"
"path/filepath"
"regexp"
"strings"
+ "github.com/bytebase/bytebase/action/world"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
)
-func getReleaseFiles(pattern string) ([]*v1pb.Release_File, error) {
+func getReleaseFiles(w *world.World, pattern string) ([]*v1pb.Release_File, error) {
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
@@ -33,7 +33,7 @@ func getReleaseFiles(pattern string) ([]*v1pb.Release_File, error) {
version := extractVersion(base)
if version == "" {
- slog.Warn("version not found. ignore the file", "file", m)
+ w.Logger.Warn("version not found. ignore the file", "file", m)
continue
}
diff --git a/action/command/rollout.go b/action/command/rollout.go
index c49a5a1e48..cebc0bbe00 100644
--- a/action/command/rollout.go
+++ b/action/command/rollout.go
@@ -3,7 +3,6 @@ package command
import (
"context"
"fmt"
- "log/slog"
"os"
"slices"
"strings"
@@ -38,7 +37,14 @@ func NewRolloutCommand(w *world.World) *cobra.Command {
}
func validateRolloutFlags(w *world.World) func(*cobra.Command, []string) error {
- return func(*cobra.Command, []string) error {
+ return func(cmd *cobra.Command, args []string) error {
+ if p := cmd.Parent(); p != nil {
+ if p.PersistentPreRunE != nil {
+ if err := p.PersistentPreRunE(cmd, args); err != nil {
+ return err
+ }
+ }
+ }
switch w.CheckPlan {
case "SKIP", "FAIL_ON_WARNING", "FAIL_ON_ERROR":
default:
@@ -57,7 +63,7 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
}
// Check version compatibility
- checkVersionCompatibility(client, args.Version)
+ checkVersionCompatibility(w, client, args.Version)
var plan *v1pb.Plan
if w.Plan != "" {
@@ -66,16 +72,16 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
return errors.Wrapf(err, "failed to get plan")
}
plan = planP
- slog.Info("use the provided plan", "url", fmt.Sprintf("%s/%s", client.url, plan.Name))
+ w.Logger.Info("use the provided plan", "url", fmt.Sprintf("%s/%s", client.url, plan.Name))
} else {
- releaseFiles, err := getReleaseFiles(w.FilePattern)
+ releaseFiles, err := getReleaseFiles(w, w.FilePattern)
if err != nil {
return errors.Wrapf(err, "failed to get release files")
}
createReleaseResponse, err := client.createRelease(w.Project, &v1pb.Release{
Title: w.ReleaseTitle,
Files: releaseFiles,
- VcsSource: getVCSSource(),
+ VcsSource: getVCSSource(w),
})
if err != nil {
return errors.Wrapf(err, "failed to create release")
@@ -97,10 +103,14 @@ func runRollout(w *world.World) func(command *cobra.Command, _ []string) error {
},
})
if err != nil {
+ if strings.Contains(err.Error(), "there is no tasks created from the plan") {
+ w.Logger.Warn("no tasks created from the plan, skip rollout")
+ return nil
+ }
return errors.Wrapf(err, "failed to create plan")
}
plan = planCreated
- slog.Info("plan created", "url", fmt.Sprintf("%s/%s", client.url, plan.Name))
+ w.Logger.Info("plan created", "url", fmt.Sprintf("%s/%s", client.url, plan.Name))
}
w.OutputMap["plan"] = plan.Name
@@ -129,7 +139,7 @@ func runAndWaitForPlanChecks(ctx context.Context, w *world.World, client *Client
return errors.Wrapf(err, "failed to list plan checks")
}
if len(runs.PlanCheckRuns) == 0 {
- slog.Info("running plan checks")
+ w.Logger.Info("running plan checks")
_, err := client.runPlanChecks(&v1pb.RunPlanChecksRequest{
Name: planName,
})
@@ -174,7 +184,7 @@ func runAndWaitForPlanChecks(ctx context.Context, w *world.World, client *Client
if runningCount == 0 {
break
}
- slog.Info("waiting for plan checks to complete", "runningCount", runningCount)
+ w.Logger.Info("waiting for plan checks to complete", "runningCount", runningCount)
time.Sleep(5 * time.Second)
}
@@ -216,14 +226,14 @@ func runAndWaitForRollout(ctx context.Context, w *world.World, client *Client, p
}
w.OutputMap["rollout"] = rolloutEmpty.Name
- slog.Info("rollout created", "url", fmt.Sprintf("%s/%s", client.url, rolloutEmpty.Name))
+ w.Logger.Info("rollout created", "url", fmt.Sprintf("%s/%s", client.url, rolloutEmpty.Name))
return waitForRollout(ctx, w, client, pendingStages, rolloutEmpty.Name)
}
func waitForRollout(ctx context.Context, w *world.World, client *Client, pendingStages []string, rolloutName string) error {
if w.TargetStage == "" {
- slog.Info("target stage is not specified, exiting...")
+ w.Logger.Info("target stage is not specified, exiting...")
return nil
}
@@ -231,7 +241,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
if ctx.Err() == nil {
return
}
- slog.Info("context cancelled, canceling the rollout")
+ w.Logger.Info("context cancelled, canceling the rollout")
// cancel rollout
if err := func() error {
taskRuns, err := client.listAllTaskRuns(rolloutName)
@@ -258,7 +268,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
}
return errs
}(); err != nil {
- slog.Error("failed to cancel rollout", "error", err)
+ w.Logger.Error("failed to cancel rollout", "error", err)
}
}()
@@ -267,8 +277,8 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
return errors.Wrapf(err, "failed to get rollout")
}
- slog.Info("exit after the target stage is completed", "targetStage", w.TargetStage)
- slog.Info("the rollout has the following stages",
+ w.Logger.Info("exit after the target stage is completed", "targetStage", w.TargetStage)
+ w.Logger.Info("the rollout has the following stages",
"createdStages", slices.Collect(func(yield func(string) bool) {
for _, stage := range rollout.GetStages() {
if !yield(stage.Environment) {
@@ -292,7 +302,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
}
}
if !targetStageFound {
- slog.Info("the target stage is not found in the rollout. exiting...", "targetStage", w.TargetStage)
+ w.Logger.Info("the target stage is not found in the rollout. exiting...", "targetStage", w.TargetStage)
return nil
}
@@ -302,7 +312,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
latestStage := rollout.Stages[len(rollout.Stages)-1].Environment
index := slices.Index(pendingStages, latestStage)
if index != -1 {
- slog.Info("removing pending stage that already in the rollout stage", "latestStage", latestStage)
+ w.Logger.Info("removing pending stage that already in the rollout stage", "latestStage", latestStage)
pendingStages = pendingStages[index+1:]
_, err := client.createRollout(&v1pb.CreateRolloutRequest{
Parent: w.Project,
@@ -383,7 +393,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
return errors.Errorf("found canceled tasks. view on Bytebase")
}
if done {
- slog.Info("stage completed", "stage", stage.Environment)
+ w.Logger.Info("stage completed", "stage", stage.Environment)
if w.TargetStage == stage.Environment {
break
}
@@ -393,7 +403,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
// run stage tasks
if len(notStartedTasks) > 0 {
- slog.Info("running stage tasks", "stage", stage.Environment, "taskCount", len(notStartedTasks))
+ w.Logger.Info("running stage tasks", "stage", stage.Environment, "taskCount", len(notStartedTasks))
if _, err := client.batchRunTasks(&v1pb.BatchRunTasksRequest{
Parent: stage.Name,
Tasks: notStartedTasks,
@@ -409,24 +419,24 @@ func waitForRollout(ctx context.Context, w *world.World, client *Client, pending
return nil
}
-func getVCSSource() *v1pb.Release_VCSSource {
- switch getJobPlatform() {
- case GitHub:
+func getVCSSource(w *world.World) *v1pb.Release_VCSSource {
+ switch w.Platform {
+ case world.GitHub:
return &v1pb.Release_VCSSource{
VcsType: v1pb.VCSType_GITHUB,
Url: os.Getenv("GITHUB_SERVER_URL") + "/" + os.Getenv("GITHUB_REPOSITORY") + "/commit/" + os.Getenv("GITHUB_SHA"),
}
- case GitLab:
+ case world.GitLab:
return &v1pb.Release_VCSSource{
VcsType: v1pb.VCSType_GITLAB,
Url: os.Getenv("CI_PROJECT_URL") + "/-/commit/" + os.Getenv("CI_COMMIT_SHA"),
}
- case Bitbucket:
+ case world.Bitbucket:
return &v1pb.Release_VCSSource{
VcsType: v1pb.VCSType_BITBUCKET,
Url: os.Getenv("BITBUCKET_GIT_HTTP_ORIGIN") + "/commits/" + os.Getenv("BITBUCKET_COMMIT"),
}
- case AzureDevOps:
+ case world.AzureDevOps:
return &v1pb.Release_VCSSource{
VcsType: v1pb.VCSType_AZURE_DEVOPS,
Url: os.Getenv("SYSTEM_COLLECTIONURI") + os.Getenv("SYSTEM_TEAMPROJECT") + "/_git/" + os.Getenv("BUILD_REPOSITORY_NAME") + "/commit/" + os.Getenv("BUILD_SOURCEVERSION"),
diff --git a/action/command/root.go b/action/command/root.go
index 9a300c5656..41304a43a7 100644
--- a/action/command/root.go
+++ b/action/command/root.go
@@ -18,7 +18,7 @@ func NewRootCommand(w *world.World) *cobra.Command {
cmd := &cobra.Command{
Use: "bytebase-action",
Short: "Bytebase action",
- PersistentPreRunE: validateSharedFlagsWithWorld(w),
+ PersistentPreRunE: rootPreRun(w),
PersistentPostRunE: writeOutputJSON(w),
}
// bytebase-action flags
@@ -35,8 +35,14 @@ func NewRootCommand(w *world.World) *cobra.Command {
return cmd
}
-func validateSharedFlagsWithWorld(w *world.World) func(cmd *cobra.Command, args []string) error {
- return func(*cobra.Command, []string) error {
+func rootPreRun(w *world.World) func(cmd *cobra.Command, args []string) error {
+ return func(cmd *cobra.Command, _ []string) error {
+ w.Logger = slog.New(slog.NewTextHandler(cmd.ErrOrStderr(), nil))
+
+ if w.Platform == world.UnspecifiedPlatform {
+ w.Platform = world.GetJobPlatform()
+ }
+
if w.ServiceAccount == "" {
return errors.Errorf("service-account is required and cannot be empty")
}
@@ -73,7 +79,7 @@ func writeOutputJSON(w *world.World) func(cmd *cobra.Command, args []string) err
return nil
}
- slog.Info("writing output to file", "file", w.Output)
+ w.Logger.Info("writing output to file", "file", w.Output)
// Create parent directory if not exists
if dir := filepath.Dir(w.Output); dir != "" {
@@ -100,32 +106,32 @@ func writeOutputJSON(w *world.World) func(cmd *cobra.Command, args []string) err
}
}
-func checkVersionCompatibility(client *Client, cliVersion string) {
+func checkVersionCompatibility(w *world.World, client *Client, cliVersion string) {
if cliVersion == "unknown" {
- slog.Warn("CLI version unknown, unable to check compatibility")
+ w.Logger.Warn("CLI version unknown, unable to check compatibility")
return
}
actuatorInfo, err := client.getActuatorInfo()
if err != nil {
- slog.Warn("Unable to get server version for compatibility check", "error", err)
+ w.Logger.Warn("Unable to get server version for compatibility check", "error", err)
return
}
serverVersion := actuatorInfo.Version
if serverVersion == "" {
- slog.Warn("Server version is empty, unable to check compatibility")
+ w.Logger.Warn("Server version is empty, unable to check compatibility")
return
}
if cliVersion == "latest" {
- slog.Warn("Using 'latest' CLI version. It is recommended to use a specific version like bytebase-action:" + serverVersion + " to match your Bytebase server version " + serverVersion)
+ w.Logger.Warn("Using 'latest' CLI version. It is recommended to use a specific version like bytebase-action:" + serverVersion + " to match your Bytebase server version " + serverVersion)
return
}
if cliVersion != serverVersion {
- slog.Warn("CLI version mismatch", "cliVersion", cliVersion, "serverVersion", serverVersion, "recommendation", "use bytebase-action:"+serverVersion+" to match your Bytebase server")
+ w.Logger.Warn("CLI version mismatch", "cliVersion", cliVersion, "serverVersion", serverVersion, "recommendation", "use bytebase-action:"+serverVersion+" to match your Bytebase server")
} else {
- slog.Info("CLI version matches server version", "version", cliVersion)
+ w.Logger.Info("CLI version matches server version", "version", cliVersion)
}
}
diff --git a/action/command/platform.go b/action/world/platform.go
similarity index 86%
rename from action/command/platform.go
rename to action/world/platform.go
index b2f5c2c630..c62803815c 100644
--- a/action/command/platform.go
+++ b/action/world/platform.go
@@ -1,4 +1,4 @@
-package command
+package world
import "os"
@@ -6,7 +6,8 @@ import "os"
type JobPlatform int
const (
- LocalPlatform JobPlatform = iota
+ UnspecifiedPlatform JobPlatform = iota
+ LocalPlatform
GitHub
GitLab
Bitbucket
@@ -29,8 +30,8 @@ func (p JobPlatform) String() string {
}
}
-// getJobPlatform returns the platform where the job is running as a JobPlatform.
-func getJobPlatform() JobPlatform {
+// GetJobPlatform returns the platform where the job is running as a JobPlatform.
+func GetJobPlatform() JobPlatform {
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
if os.Getenv("GITHUB_ACTIONS") == "true" {
return GitHub
diff --git a/action/world/world.go b/action/world/world.go
index 67a7429165..89d491d0ba 100644
--- a/action/world/world.go
+++ b/action/world/world.go
@@ -1,7 +1,13 @@
package world
+import (
+ "log/slog"
+)
+
// World is the world environment for bytebase-action.
type World struct {
+ Logger *slog.Logger
+ Platform JobPlatform
// bytebase-action flags
Output string
URL string
@@ -38,6 +44,7 @@ type World struct {
func NewWorld() *World {
return &World{
+ Logger: slog.Default(),
OutputMap: make(map[string]string),
}
}
diff --git a/backend/plugin/db/sqlite/dump.go b/backend/plugin/db/sqlite/dump.go
index 607c8e3a9e..bc5f6b3b5f 100644
--- a/backend/plugin/db/sqlite/dump.go
+++ b/backend/plugin/db/sqlite/dump.go
@@ -61,13 +61,17 @@ func (d *Driver) dumpOneDatabase(ctx context.Context, out io.Writer) error {
var sqliteSchemas []sqliteSchema
for rows.Next() {
var s sqliteSchema
+ var sql sql.NullString
if err := rows.Scan(
&s.schemaType,
&s.name,
- &s.statement,
+ &sql,
); err != nil {
return err
}
+ if sql.Valid {
+ s.statement = sql.String
+ }
sqliteSchemas = append(sqliteSchemas, s)
}
if err := rows.Err(); err != nil {
diff --git a/backend/plugin/db/sqlite/sync.go b/backend/plugin/db/sqlite/sync.go
index f66fd8450e..5c741ebb20 100644
--- a/backend/plugin/db/sqlite/sync.go
+++ b/backend/plugin/db/sqlite/sync.go
@@ -183,7 +183,7 @@ func getIndices(txn *sql.Tx) (map[string][]*storepb.IndexMetadata, error) {
for rows.Next() {
var tableName, statement string
index := &storepb.IndexMetadata{}
- if err := rows.Scan(tableName, &index.Name, &statement); err != nil {
+ if err := rows.Scan(&tableName, &index.Name, &statement); err != nil {
return nil, err
}
index.Unique = strings.Contains(statement, " UNIQUE INDEX ")
diff --git a/backend/tests/action_test.go b/backend/tests/action_test.go
new file mode 100644
index 0000000000..94b1f097bf
--- /dev/null
+++ b/backend/tests/action_test.go
@@ -0,0 +1,728 @@
+package tests
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/action/command"
+ "github.com/bytebase/bytebase/action/world"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+)
+
+func TestActionCheckCommand(t *testing.T) {
+ t.Parallel()
+
+ t.Run("ValidMigrations", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create test instance and database
+ database := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory
+ testDataDir := t.TempDir()
+ validMigrationsDir := filepath.Join(testDataDir, "valid-migrations")
+ err = os.MkdirAll(validMigrationsDir, 0755)
+ a.NoError(err)
+
+ // Create a valid migration file
+ migrationContent := `CREATE TABLE users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);`
+ err = os.WriteFile(filepath.Join(validMigrationsDir, "00001_create_users.sql"), []byte(migrationContent), 0644)
+ a.NoError(err)
+
+ // Execute check command using backend test credentials
+ result, err := executeActionCommand(ctx,
+ "check",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", database.Name,
+ "--file-pattern", filepath.Join(validMigrationsDir, "*.sql"),
+ "--check-release", "FAIL_ON_ERROR",
+ )
+
+ a.NoError(err, "Check command should succeed for valid migrations")
+
+ // E2E Verification for check command:
+ // The key expectation is that check validates files without modifying target databases
+
+ // Verify database was NOT modified (this is the critical check)
+ // Query database to ensure no tables were created
+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{
+ Name: database.Name + "/metadata",
+ }))
+ a.NoError(err)
+ // Verify no user tables exist (only SQLite system tables)
+ for _, schema := range metadata.Msg.Schemas {
+ for _, table := range schema.Tables {
+ a.NotEqual("users", table.Name, "Check command should not create tables")
+ }
+ }
+
+ // 4. Verify command succeeded with proper exit code
+ a.Contains(result.Stdout, "", "Check should complete without errors")
+ })
+
+ t.Run("PolicyViolations", func(t *testing.T) {
+ t.Skip("Skipping policy violations test - SQL review policies not configured in test environment")
+ })
+
+ t.Run("SyntaxErrors", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create test database
+ database := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory with syntax error migration
+ testDataDir := t.TempDir()
+ err = os.MkdirAll(testDataDir, 0755)
+ a.NoError(err)
+
+ // Create a migration file with obvious syntax errors
+ migrationContent := `INVALID SQL SYNTAX THIS IS NOT VALID SQL AT ALL!!!`
+ err = os.WriteFile(filepath.Join(testDataDir, "00001_syntax_error.sql"), []byte(migrationContent), 0644)
+ a.NoError(err)
+
+ // Execute check with file that has syntax errors
+ result, err := executeActionCommand(ctx,
+ "check",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", database.Name,
+ "--file-pattern", filepath.Join(testDataDir, "00001_syntax_error.sql"),
+ "--check-release", "FAIL_ON_ERROR",
+ )
+ a.NoError(err)
+
+ // The command may or may not fail depending on how syntax errors are handled
+ // The key verification is that syntax issues are detected and reported
+
+ // E2E Verification for check command with syntax errors:
+ // The check should detect syntax errors without modifying databases
+
+ // The command should complete successfully regardless of syntax issues in the SQL
+ // The check API validates the request but may not deeply parse SQL syntax
+ a.NoError(result.Error, "Command should complete successfully")
+
+ // Verify NO database changes occurred
+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{
+ Name: database.Name + "/metadata",
+ }))
+ a.NoError(err)
+ // Ensure no tables were created
+ for _, schema := range metadata.Msg.Schemas {
+ for _, table := range schema.Tables {
+ a.NotEqual("invalid", table.Name, "Check should not create tables with syntax errors")
+ }
+ }
+ })
+
+ t.Run("MultipleTargets", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create multiple test databases
+ database1 := ctl.createTestDatabase(ctx, t)
+ database2 := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory
+ testDataDir := t.TempDir()
+ err = os.MkdirAll(testDataDir, 0755)
+ a.NoError(err)
+
+ // Create a valid migration file
+ migrationContent := `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL UNIQUE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);`
+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)
+ a.NoError(err)
+
+ // Execute check command with multiple targets
+ result, err := executeActionCommand(ctx,
+ "check",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", fmt.Sprintf("%s,%s", database1.Name, database2.Name),
+ "--file-pattern", filepath.Join(testDataDir, "00001_create_users.sql"),
+ "--check-release", "FAIL_ON_ERROR",
+ )
+
+ a.NoError(err, "Check command should succeed for multiple valid targets")
+
+ // E2E Verification for check command with multiple targets:
+ // The check should validate all targets without modifying any databases
+
+ // Verify both databases were NOT modified
+ for _, db := range []*v1pb.Database{database1, database2} {
+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{
+ Name: db.Name + "/metadata",
+ }))
+ a.NoError(err)
+ // Verify no user tables exist
+ for _, schema := range metadata.Msg.Schemas {
+ for _, table := range schema.Tables {
+ a.NotEqual("users", table.Name, "Check command should not create tables")
+ }
+ }
+ }
+
+ // 4. Verify command succeeded
+ a.NotContains(result.Stderr, "error", "Check should complete without errors")
+ })
+}
+
+// ActionResult holds the result of executing an action command
+type ActionResult struct {
+ Stdout string
+ Stderr string
+ Error error
+ OutputJSON map[string]any // Parsed from --output file
+}
+
+// executeActionCommand executes the bytebase-action cobra command with given arguments
+func executeActionCommand(ctx context.Context, args ...string) (*ActionResult, error) {
+ // Create new world instance for test isolation
+ w := world.NewWorld()
+ w.Platform = world.LocalPlatform
+
+ // Create new command instance using the factory function
+ cmd := command.NewRootCommand(w)
+
+ // Set up output buffers
+ stdout := new(bytes.Buffer)
+ stderr := new(bytes.Buffer)
+ cmd.SetOut(stdout)
+ cmd.SetErr(stderr)
+
+ // Set arguments
+ cmd.SetArgs(args)
+
+ // Execute command
+ err := cmd.ExecuteContext(ctx)
+
+ // Get output from world.OutputMap
+ outputJSON := make(map[string]any)
+ for k, v := range w.OutputMap {
+ outputJSON[k] = v
+ }
+
+ // Also parse output file if specified
+ if w.Output != "" {
+ if data, readErr := os.ReadFile(w.Output); readErr == nil {
+ var fileOutput map[string]any
+ if json.Unmarshal(data, &fileOutput) == nil {
+ for k, v := range fileOutput {
+ outputJSON[k] = v
+ }
+ }
+ }
+ }
+
+ return &ActionResult{
+ Stdout: stdout.String(),
+ Stderr: stderr.String(),
+ Error: err,
+ OutputJSON: outputJSON,
+ }, err
+}
+
+// createTestDatabase creates a test SQLite database instance and database
+func (ctl *controller) createTestDatabase(ctx context.Context, t *testing.T) *v1pb.Database {
+ a := require.New(t)
+
+ // Create SQLite instance
+ instanceDir := t.TempDir()
+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("inst")[:8],
+ Instance: &v1pb.Instance{
+ Title: "Test Instance",
+ Engine: v1pb.Engine_SQLITE,
+ Environment: "environments/prod",
+ Activation: true,
+ DataSources: []*v1pb.DataSource{{
+ Type: v1pb.DataSourceType_ADMIN,
+ Host: instanceDir,
+ Id: "admin",
+ }},
+ },
+ }))
+ a.NoError(err)
+
+ // Create database
+ dbName := generateRandomString("db")[:8]
+ err = ctl.createDatabaseV2(ctx, ctl.project, instanceResp.Msg, nil, dbName, "")
+ a.NoError(err)
+
+ // Get database
+ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{
+ Name: fmt.Sprintf("%s/databases/%s", instanceResp.Msg.Name, dbName),
+ }))
+ a.NoError(err)
+
+ return databaseResp.Msg
+}
+
+func TestActionRolloutCommand(t *testing.T) {
+ t.Parallel()
+
+ t.Run("BasicRollout", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create test database
+ database := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory and migration file
+ testDataDir := t.TempDir()
+ migrationContent := `CREATE TABLE users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);`
+ migrationFile := filepath.Join(testDataDir, "00001_create_users.sql")
+ err = os.WriteFile(migrationFile, []byte(migrationContent), 0644)
+ a.NoError(err)
+
+ // Create output file
+ outputFile := filepath.Join(t.TempDir(), "rollout-output.json")
+
+ // Execute rollout
+ result, err := executeActionCommand(ctx,
+ "rollout",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", database.Name,
+ "--file-pattern", migrationFile,
+ "--release-title", "Test Release",
+ "--rollout-title", "Test Rollout",
+ "--target-stage", "environments/prod",
+ "--output", outputFile,
+ )
+
+ a.NoError(err, "Rollout command should succeed")
+
+ // E2E Verification: Check server state for complete rollout lifecycle
+
+ // 1. Verify plan was created
+ plans, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(plans.Msg.Plans, "Expected plan to be created")
+ plan := plans.Msg.Plans[0]
+
+ // 2. Verify release was created with correct title
+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")
+ release := releases.Msg.Releases[0]
+ a.Equal("Test Release", release.Title)
+
+ // 3. Verify rollout was created and completed
+ rollouts, err := ctl.rolloutServiceClient.ListRollouts(ctx, connect.NewRequest(&v1pb.ListRolloutsRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(rollouts.Msg.Rollouts, "Expected rollout to be created")
+ rollout := rollouts.Msg.Rollouts[0]
+ a.Equal("Test Rollout", rollout.Title)
+ a.Equal(rollout.Name, result.OutputJSON["rollout"])
+
+ // Verify rollout completed by checking all task statuses
+ for _, stage := range rollout.Stages {
+ for _, task := range stage.Tasks {
+ a.True(task.Status == v1pb.Task_DONE || task.Status == v1pb.Task_SKIPPED,
+ "Task %s should be completed (DONE or SKIPPED), got %s", task.Name, task.Status.String())
+ }
+ }
+
+ // 4. Verify database schema was actually changed
+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{
+ Name: database.Name + "/metadata",
+ }))
+ a.NoError(err)
+ // Find the users table in metadata if schema sync worked
+ foundUsersTable := false
+ for _, schema := range metadata.Msg.Schemas {
+ for _, table := range schema.Tables {
+ if table.Name == "users" {
+ foundUsersTable = true
+ // Verify table structure
+ a.GreaterOrEqual(len(table.Columns), 2, "Expected at least 2 columns")
+ }
+ }
+ }
+ a.True(foundUsersTable, "Users table not found in metadata, but rollout completed successfully")
+
+ // 5. Verify database revision was updated
+ updatedDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{
+ Name: database.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(updatedDatabase.Msg.SchemaVersion, "Database schema version not set, but rollout completed successfully")
+ a.Equal("00001", updatedDatabase.Msg.SchemaVersion)
+
+ // 6. Verify change history was recorded
+ changelogs, err := ctl.databaseServiceClient.ListChangelogs(ctx, connect.NewRequest(&v1pb.ListChangelogsRequest{
+ Parent: database.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(changelogs.Msg.Changelogs, "No change history found, but rollout completed successfully")
+
+ revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{
+ Parent: database.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(revisions.Msg.Revisions, "No revision found, but rollout completed successfully")
+ a.Len(revisions.Msg.Revisions, 1, "Expected exactly one revision")
+ revision := revisions.Msg.Revisions[0]
+ a.Equal("00001", revision.Version)
+
+ // 7. Verify output file contains server resource names
+ var output map[string]string
+ data, err := os.ReadFile(outputFile)
+ a.NoError(err)
+ err = json.Unmarshal(data, &output)
+ a.NoError(err)
+
+ a.Equal(release.Name, output["release"], "Output should contain actual release name")
+ a.Equal(plan.Name, output["plan"], "Output should contain actual plan name")
+ a.Equal(rollout.Name, output["rollout"], "Output should contain actual rollout name")
+
+ // 8. Verify command output
+ a.NotContains(result.Stderr, "error", "Rollout should complete without errors")
+ })
+
+ t.Run("MultipleFiles", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create test database
+ database := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory and multiple migration files
+ testDataDir := t.TempDir()
+
+ // Create 00001_create_users.sql
+ migrationContent1 := `CREATE TABLE users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);`
+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent1), 0644)
+ a.NoError(err)
+
+ // Create 00002_add_email.sql
+ migrationContent2 := `ALTER TABLE users ADD COLUMN email TEXT;`
+ err = os.WriteFile(filepath.Join(testDataDir, "00002_add_email.sql"), []byte(migrationContent2), 0644)
+ a.NoError(err)
+
+ // Create 00003_create_index.sql
+ migrationContent3 := `CREATE INDEX idx_users_username ON users(username);`
+ err = os.WriteFile(filepath.Join(testDataDir, "00003_create_index.sql"), []byte(migrationContent3), 0644)
+ a.NoError(err)
+
+ // Create output file
+ outputFile := filepath.Join(t.TempDir(), "rollout-output.json")
+
+ // Execute rollout with multiple migration files
+ result, err := executeActionCommand(ctx,
+ "rollout",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", database.Name,
+ "--file-pattern", filepath.Join(testDataDir, "0000*.sql"),
+ "--release-title", "Multi-file Release",
+ "--rollout-title", "Multi-file Rollout",
+ "--target-stage", "environments/prod",
+ "--output", outputFile,
+ )
+
+ a.NoError(err, "Rollout command should succeed with multiple files")
+
+ // E2E Verification: Check server state for complete rollout lifecycle
+
+ // 1. Verify plan was created
+ plans, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(plans.Msg.Plans, "Expected plan to be created")
+ plan := plans.Msg.Plans[0]
+
+ // 2. Verify release was created with correct title
+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")
+ release := releases.Msg.Releases[0]
+ a.Equal("Multi-file Release", release.Title)
+
+ // 3. Verify rollout was created and completed
+ rollouts, err := ctl.rolloutServiceClient.ListRollouts(ctx, connect.NewRequest(&v1pb.ListRolloutsRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(rollouts.Msg.Rollouts, "Expected rollout to be created")
+ rollout := rollouts.Msg.Rollouts[0]
+ a.Equal("Multi-file Rollout", rollout.Title)
+ a.Equal(rollout.Name, result.OutputJSON["rollout"])
+
+ // Verify rollout completed by checking all task statuses
+ for _, stage := range rollout.Stages {
+ for _, task := range stage.Tasks {
+ a.True(task.Status == v1pb.Task_DONE || task.Status == v1pb.Task_SKIPPED,
+ "Task %s should be completed (DONE or SKIPPED), got %s", task.Name, task.Status.String())
+ }
+ }
+
+ // 4. Verify database schema was actually changed
+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{
+ Name: database.Name + "/metadata",
+ }))
+ a.NoError(err)
+
+ // Check for users table (from 00001_create_users.sql)
+ foundUsersTable := false
+ foundEmailColumn := false
+ foundUsernameIndex := false
+
+ for _, schema := range metadata.Msg.Schemas {
+ for _, table := range schema.Tables {
+ if table.Name == "users" {
+ foundUsersTable = true
+ // Check for email column (from 00002_add_email.sql)
+ for _, col := range table.Columns {
+ if col.Name == "email" {
+ foundEmailColumn = true
+ }
+ }
+ // Check for index (from 00003_create_index.sql)
+ for _, index := range table.Indexes {
+ if index.Name == "idx_users_username" {
+ foundUsernameIndex = true
+ }
+ }
+ }
+ }
+ }
+
+ a.True(foundUsersTable, "Users table should exist after rollout")
+ a.True(foundEmailColumn, "Email column should exist after rollout")
+ a.True(foundUsernameIndex, "Username index should exist after rollout")
+
+ // 5. Verify database revision was updated
+ updatedDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{
+ Name: database.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(updatedDatabase.Msg.SchemaVersion, "Database schema version not set, but rollout completed successfully")
+ a.Equal("00003", updatedDatabase.Msg.SchemaVersion)
+
+ // 6. Verify change history was recorded
+ changelogs, err := ctl.databaseServiceClient.ListChangelogs(ctx, connect.NewRequest(&v1pb.ListChangelogsRequest{
+ Parent: database.Name,
+ }))
+ a.NoError(err)
+ a.GreaterOrEqual(len(changelogs.Msg.Changelogs), 3, "Expected at least 3 migration records in history")
+
+ revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{
+ Parent: database.Name,
+ }))
+ a.NoError(err)
+ a.NotEmpty(revisions.Msg.Revisions, "No revision found, but rollout completed successfully")
+ a.Len(revisions.Msg.Revisions, 3, "Expected exactly three revisions")
+ // Check last revision version. Revisions are ordered by version desc
+ lastRevision := revisions.Msg.Revisions[0]
+ a.Equal("00003", lastRevision.Version)
+
+ // 7. Verify output file contains server resource names
+ var output map[string]string
+ data, err := os.ReadFile(outputFile)
+ a.NoError(err)
+ err = json.Unmarshal(data, &output)
+ a.NoError(err)
+
+ a.Equal(release.Name, output["release"], "Output should contain actual release name")
+ a.Equal(plan.Name, output["plan"], "Output should contain actual plan name")
+ a.Equal(rollout.Name, output["rollout"], "Output should contain actual rollout name")
+
+ // 8. Verify command output
+ a.NotContains(result.Stderr, "error", "Multi-file rollout should complete without errors")
+ })
+}
+
+func TestActionErrorScenarios(t *testing.T) {
+ t.Parallel()
+
+ t.Run("InvalidServiceAccountSecret", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create test database
+ database := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory and migration file
+ testDataDir := t.TempDir()
+ migrationContent := `CREATE TABLE users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);`
+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)
+ a.NoError(err)
+
+ // Execute command with invalid credentials
+ result, err := executeActionCommand(ctx,
+ "check",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "invalid-secret",
+ "--project", ctl.project.Name,
+ "--targets", database.Name,
+ "--file-pattern", filepath.Join(testDataDir, "*.sql"),
+ )
+
+ a.Error(err, "Command should fail with invalid service account secret")
+ a.Contains(result.Stderr, "failed to login", "Expected authentication error in stderr")
+ })
+
+ t.Run("NonExistentDatabase", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ // Create test data directory and migration file
+ testDataDir := t.TempDir()
+ migrationContent := `CREATE TABLE users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);`
+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)
+ a.NoError(err)
+
+ // Try to target a database that doesn't exist
+ result, err := executeActionCommand(ctx,
+ "check",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", "instances/fake/databases/nonexistent",
+ "--file-pattern", filepath.Join(testDataDir, "*.sql"),
+ )
+
+ a.Error(err, "Command should fail with non-existent database")
+ a.Contains(result.Stderr, "failed to found database", "Expected not found error in stderr")
+ })
+
+ t.Run("EmptyFilePattern", func(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ database := ctl.createTestDatabase(ctx, t)
+
+ // Create test data directory (but don't create any files)
+ testDataDir := t.TempDir()
+
+ // Use a pattern that matches no files
+ result, err := executeActionCommand(ctx,
+ "rollout",
+ "--url", ctl.rootURL,
+ "--service-account", "[email protected]",
+ "--service-account-secret", "1024bytebase",
+ "--project", ctl.project.Name,
+ "--targets", database.Name,
+ "--file-pattern", filepath.Join(testDataDir, "*.nonexistent"),
+ "--release-title", "Empty Release",
+ "--target-stage", "environments/prod",
+ )
+ a.NoError(err)
+ a.Contains(result.Stderr, "no tasks created from the plan", "Expected no tasks created error in stderr")
+
+ // Should create a release with no files
+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{
+ Parent: ctl.project.Name,
+ }))
+ a.NoError(err)
+ a.Equal(1, len(releases.Msg.Releases), "Should create a release")
+ release := releases.Msg.Releases[0]
+ a.Equal("Empty Release", release.Title, "Release title should be 'Empty Release'")
+ a.Equal(0, len(release.Files), "Release files should be empty")
+ })
+}