Skip to content

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

refactor: remove drift detection and previousSchema parameter (#18949)

Danny Xu1d9b57de712c
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 29cf7ca72e..2190d3f340 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -7562,9 +7562,6 @@ components:
description: |-
The title of the plan associated with this changelog's task run.
This field is populated by deriving the plan from task_run for display purposes.
- type:
- title: type
- $ref: '#/components/schemas/bytebase.v1.Changelog.Type'
title: Changelog
additionalProperties: false
bytebase.v1.Changelog.Status:
@@ -7575,14 +7572,6 @@ components:
- PENDING
- DONE
- FAILED
- bytebase.v1.Changelog.Type:
- type: string
- title: Type
- enum:
- - TYPE_UNSPECIFIED
- - BASELINE
- - MIGRATE
- - SDL
bytebase.v1.ChangelogView:
type: string
title: ChangelogView
@@ -10986,12 +10975,10 @@ components:
Supported filter:
- status: the changelog status, support "==" operation. check Changelog.Status for available values.
- - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
- create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
Example:
status == "DONE"
- type in ["BASELINE", "MIGRATE"]
status == "FAILED" && type == "SDL"
create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
title: ListChangelogsRequest
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index be0ed366e2..3aca04396b 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -361,7 +361,6 @@ func (s *DatabaseService) UpdateDatabase(ctx context.Context, req *connect.Reque
Status: store.ChangelogStatusDone,
SyncHistoryUID: &syncHistory,
Payload: &storepb.ChangelogPayload{
- Type: storepb.ChangelogPayload_BASELINE,
GitCommit: s.profile.GitCommit,
}}); err != nil {
return nil, errors.Wrapf(err, "failed to create changelog")
diff --git a/backend/api/v1/database_service_changelog.go b/backend/api/v1/database_service_changelog.go
index 9e9d7135c6..c5f4298546 100644
--- a/backend/api/v1/database_service_changelog.go
+++ b/backend/api/v1/database_service_changelog.go
@@ -13,7 +13,6 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/common"
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/store"
)
@@ -45,29 +44,6 @@ func parseChangelogFilter(filter string, find *store.FindChangelogMessage) error
return err
}
}
- case celoperators.In:
- variable, value := getVariableAndValueFromExpr(expr)
- if variable != "type" {
- return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupport variable %v", variable))
- }
- rawList, ok := value.([]any)
- if !ok {
- return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid list value %q for %v", value, variable))
- }
- if len(rawList) == 0 {
- return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("empty list value for filter %v", variable))
- }
- typeList := []string{}
- for _, raw := range rawList {
- typeStr, ok := raw.(string)
- if !ok {
- return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("value for type must be a string"))
- }
- v1Type := v1pb.Changelog_Type_value[typeStr]
- storeType := convertToChangelogStoreType(v1pb.Changelog_Type(v1Type))
- typeList = append(typeList, storeType.String())
- }
- find.TypeList = typeList
case celoperators.Equals:
variable, value := getVariableAndValueFromExpr(expr)
strValue, ok := value.(string)
@@ -79,10 +55,6 @@ func parseChangelogFilter(filter string, find *store.FindChangelogMessage) error
v1Status := v1pb.Changelog_Status_value[strValue]
storeStatus := convertToChangelogStoreStatus(v1pb.Changelog_Status(v1Status))
find.Status = &storeStatus
- case "type":
- v1Type := v1pb.Changelog_Type_value[strValue]
- storeType := convertToChangelogStoreType(v1pb.Changelog_Type(v1Type))
- find.TypeList = []string{storeType.String()}
default:
return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupport variable %v", variable))
}
@@ -222,8 +194,6 @@ func (s *DatabaseService) convertToChangelogs(_ context.Context, d *store.Databa
}
func (*DatabaseService) convertToChangelog(d *store.DatabaseMessage, c *store.ChangelogMessage) *v1pb.Changelog {
- changelogType := convertToChangelogType(c.Payload.GetType())
-
cl := &v1pb.Changelog{
Name: common.FormatChangelog(d.InstanceID, d.DatabaseName, c.UID),
CreateTime: timestamppb.New(c.CreatedAt),
@@ -231,7 +201,6 @@ func (*DatabaseService) convertToChangelog(d *store.DatabaseMessage, c *store.Ch
Schema: "",
SchemaSize: 0,
TaskRun: c.Payload.GetTaskRun(),
- Type: changelogType,
PlanTitle: c.PlanTitle,
}
@@ -268,35 +237,3 @@ func convertToChangelogStoreStatus(s v1pb.Changelog_Status) store.ChangelogStatu
return store.ChangelogStatusDone
}
}
-
-func convertToChangelogType(t storepb.ChangelogPayload_Type) v1pb.Changelog_Type {
- //exhaustive:enforce
- switch t {
- case storepb.ChangelogPayload_BASELINE:
- return v1pb.Changelog_BASELINE
- case storepb.ChangelogPayload_MIGRATE:
- return v1pb.Changelog_MIGRATE
- case storepb.ChangelogPayload_SDL:
- return v1pb.Changelog_SDL
- case storepb.ChangelogPayload_TYPE_UNSPECIFIED:
- return v1pb.Changelog_TYPE_UNSPECIFIED
- default:
- return v1pb.Changelog_TYPE_UNSPECIFIED
- }
-}
-
-func convertToChangelogStoreType(t v1pb.Changelog_Type) storepb.ChangelogPayload_Type {
- //exhaustive:enforce
- switch t {
- case v1pb.Changelog_BASELINE:
- return storepb.ChangelogPayload_BASELINE
- case v1pb.Changelog_MIGRATE:
- return storepb.ChangelogPayload_MIGRATE
- case v1pb.Changelog_SDL:
- return storepb.ChangelogPayload_SDL
- case v1pb.Changelog_TYPE_UNSPECIFIED:
- return storepb.ChangelogPayload_TYPE_UNSPECIFIED
- default:
- return storepb.ChangelogPayload_TYPE_UNSPECIFIED
- }
-}
diff --git a/backend/api/v1/database_service_changelog_test.go b/backend/api/v1/database_service_changelog_test.go
index 67af18030c..a8ccc4cab1 100644
--- a/backend/api/v1/database_service_changelog_test.go
+++ b/backend/api/v1/database_service_changelog_test.go
@@ -11,14 +11,13 @@ import (
func TestParseChangelogFilter(t *testing.T) {
tests := []struct {
- name string
- filter string
- wantStatus *store.ChangelogStatus
- wantTypeList []string
- wantAfter *time.Time
- wantBefore *time.Time
- wantErr bool
- errContains string
+ name string
+ filter string
+ wantStatus *store.ChangelogStatus
+ wantAfter *time.Time
+ wantBefore *time.Time
+ wantErr bool
+ errContains string
}{
{
name: "empty filter",
@@ -29,16 +28,6 @@ func TestParseChangelogFilter(t *testing.T) {
filter: `status == "DONE"`,
wantStatus: ptr(store.ChangelogStatusDone),
},
- {
- name: "type filter with equals",
- filter: `type == "MIGRATE"`,
- wantTypeList: []string{"MIGRATE"},
- },
- {
- name: "type filter with in",
- filter: `type in ["BASELINE", "MIGRATE"]`,
- wantTypeList: []string{"BASELINE", "MIGRATE"},
- },
{
name: "create_time greater than or equal",
filter: `create_time >= "2024-01-01T00:00:00Z"`,
@@ -61,12 +50,6 @@ func TestParseChangelogFilter(t *testing.T) {
wantStatus: ptr(store.ChangelogStatusDone),
wantAfter: ptr(mustParseTime(t, "2024-01-01T00:00:00Z")),
},
- {
- name: "combined type and time filter",
- filter: `type in ["BASELINE", "MIGRATE"] && create_time <= "2024-12-31T23:59:59Z"`,
- wantTypeList: []string{"BASELINE", "MIGRATE"},
- wantBefore: ptr(mustParseTime(t, "2024-12-31T23:59:59Z")),
- },
{
name: "invalid time format",
filter: `create_time >= "invalid-time"`,
@@ -111,9 +94,6 @@ func TestParseChangelogFilter(t *testing.T) {
require.NotNil(t, find.Status)
require.Equal(t, *tt.wantStatus, *find.Status)
}
- if tt.wantTypeList != nil {
- require.Equal(t, tt.wantTypeList, find.TypeList)
- }
if tt.wantAfter != nil {
require.NotNil(t, find.CreatedAtAfter)
require.Equal(t, *tt.wantAfter, *find.CreatedAtAfter)
diff --git a/backend/api/v1/release_service_check.go b/backend/api/v1/release_service_check.go
index 8ec734a7e5..5227238976 100644
--- a/backend/api/v1/release_service_check.go
+++ b/backend/api/v1/release_service_check.go
@@ -443,17 +443,9 @@ func (s *ReleaseService) checkReleaseDeclarative(ctx context.Context, files []*v
DatabaseName: database.DatabaseName,
})
if err == nil && dbMetadata != nil {
- // Get previous SDL from latest revision
- var previousUserSDL string
- if len(revisions) > 0 {
- // Get sheet statement from revision
- sheetSha256 := revisions[0].Payload.SheetSha256
- if sheetSha256 != "" {
- if sheet, err := s.store.GetSheetFull(ctx, sheetSha256); err == nil {
- previousUserSDL = sheet.Statement
- }
- }
- }
+ // Get previous SDL from the database's release field (last applied release)
+ // Returns empty string if no previous release exists (initialization scenario)
+ previousUserSDL := getPreviousSDLForDatabase(ctx, s.store, database)
// Combine all SDL files into single text
var combinedCurrentSDL strings.Builder
@@ -463,7 +455,7 @@ func (s *ReleaseService) checkReleaseDeclarative(ctx context.Context, files []*v
}
// Generate diff
- schemaDiff, err := schema.GetSDLDiff(pengine, combinedCurrentSDL.String(), previousUserSDL, dbMetadata, nil)
+ schemaDiff, err := schema.GetSDLDiff(pengine, combinedCurrentSDL.String(), previousUserSDL, dbMetadata)
if err == nil {
// Filter out bbdataarchive schema changes for Postgres
schemaDiff = schema.FilterPostgresArchiveSchema(schemaDiff)
@@ -761,3 +753,51 @@ func getStatementTypesWithPositionsForEngine(engine storepb.Engine, asts []base.
return []statementTypeWithPosition{}, nil
}
}
+
+// getPreviousSDLForDatabase retrieves the previous SDL text from the database's last applied release.
+// Returns empty string if no previous release exists or if there are any errors loading it.
+func getPreviousSDLForDatabase(ctx context.Context, s *store.Store, database *store.DatabaseMessage) string {
+ // Get the previous SDL text from the database's release field
+ if database.Metadata == nil || database.Metadata.Release == "" {
+ return ""
+ }
+
+ // Parse release name to get project ID and release ID
+ projectID, releaseID, err := common.GetProjectReleaseID(database.Metadata.Release)
+ if err != nil {
+ slog.Warn("Failed to parse release name, treating as initialization", "release", database.Metadata.Release, "error", err)
+ return ""
+ }
+
+ // Load the release
+ release, err := s.GetRelease(ctx, &store.FindReleaseMessage{
+ ProjectID: &projectID,
+ ReleaseID: &releaseID,
+ })
+ if err != nil {
+ slog.Warn("Failed to get release, treating as initialization", "project", projectID, "release", releaseID, "error", err)
+ return ""
+ }
+ if release == nil {
+ slog.Warn("Release not found, treating as initialization", "project", projectID, "release", releaseID)
+ return ""
+ }
+
+ // For SDL/declarative releases, combine all files
+ var combinedSDL strings.Builder
+ for _, file := range release.Payload.Files {
+ sheet, err := s.GetSheetFull(ctx, file.SheetSha256)
+ if err != nil {
+ slog.Warn("Failed to get sheet, treating as initialization", "sha256", file.SheetSha256, "error", err)
+ return ""
+ }
+ if sheet == nil {
+ slog.Warn("Sheet not found, treating as initialization", "sha256", file.SheetSha256)
+ return ""
+ }
+ combinedSDL.WriteString(sheet.Statement)
+ combinedSDL.WriteString("\n\n")
+ }
+
+ return combinedSDL.String()
+}
diff --git a/backend/common/error.go b/backend/common/error.go
index 716fa0cff4..0de9961b84 100644
--- a/backend/common/error.go
+++ b/backend/common/error.go
@@ -31,10 +31,8 @@ const (
MigrationSchemaMissing Code = 201
MigrationAlreadyApplied Code = 202
MigrationOutOfOrder Code = 203
- // MigrationBaselineMissing is no longer used.
- // MigrationBaselineMissing Code = 204.
- MigrationPending Code = 205
- MigrationFailed Code = 206
+ MigrationPending Code = 205
+ MigrationFailed Code = 206
// 301 task error.
TaskTimingNotAllowed Code = 301
diff --git a/backend/component/sampleinstance/manager.go b/backend/component/sampleinstance/manager.go
index b6d2e18fb8..3b0958931b 100644
--- a/backend/component/sampleinstance/manager.go
+++ b/backend/component/sampleinstance/manager.go
@@ -297,7 +297,6 @@ func (m *Manager) generateInstance(
Status: store.ChangelogStatusDone,
SyncHistoryUID: &syncHistory,
Payload: &storepb.ChangelogPayload{
- Type: storepb.ChangelogPayload_BASELINE,
GitCommit: m.profile.GitCommit,
},
}); err != nil {
diff --git a/backend/generated-go/store/changelog.pb.go b/backend/generated-go/store/changelog.pb.go
index 763a8d4c39..8ddface81d 100644
--- a/backend/generated-go/store/changelog.pb.go
+++ b/backend/generated-go/store/changelog.pb.go
@@ -21,64 +21,11 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
-type ChangelogPayload_Type int32
-
-const (
- ChangelogPayload_TYPE_UNSPECIFIED ChangelogPayload_Type = 0
- ChangelogPayload_BASELINE ChangelogPayload_Type = 1
- ChangelogPayload_MIGRATE ChangelogPayload_Type = 2
- ChangelogPayload_SDL ChangelogPayload_Type = 3
-)
-
-// Enum value maps for ChangelogPayload_Type.
-var (
- ChangelogPayload_Type_name = map[int32]string{
- 0: "TYPE_UNSPECIFIED",
- 1: "BASELINE",
- 2: "MIGRATE",
- 3: "SDL",
- }
- ChangelogPayload_Type_value = map[string]int32{
- "TYPE_UNSPECIFIED": 0,
- "BASELINE": 1,
- "MIGRATE": 2,
- "SDL": 3,
- }
-)
-
-func (x ChangelogPayload_Type) Enum() *ChangelogPayload_Type {
- p := new(ChangelogPayload_Type)
- *p = x
- return p
-}
-
-func (x ChangelogPayload_Type) String() string {
- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
-}
-
-func (ChangelogPayload_Type) Descriptor() protoreflect.EnumDescriptor {
- return file_store_changelog_proto_enumTypes[0].Descriptor()
-}
-
-func (ChangelogPayload_Type) Type() protoreflect.EnumType {
- return &file_store_changelog_proto_enumTypes[0]
-}
-
-func (x ChangelogPayload_Type) Number() protoreflect.EnumNumber {
- return protoreflect.EnumNumber(x)
-}
-
-// Deprecated: Use ChangelogPayload_Type.Descriptor instead.
-func (ChangelogPayload_Type) EnumDescriptor() ([]byte, []int) {
- return file_store_changelog_proto_rawDescGZIP(), []int{0, 0}
-}
-
type ChangelogPayload struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}/taskRuns/{taskRun}
- TaskRun string `protobuf:"bytes,1,opt,name=task_run,json=taskRun,proto3" json:"task_run,omitempty"`
- Type ChangelogPayload_Type `protobuf:"varint,5,opt,name=type,proto3,enum=bytebase.store.ChangelogPayload_Type" json:"type,omitempty"`
- GitCommit string `protobuf:"bytes,6,opt,name=git_commit,json=gitCommit,proto3" json:"git_commit,omitempty"`
+ TaskRun string `protobuf:"bytes,1,opt,name=task_run,json=taskRun,proto3" json:"task_run,omitempty"`
+ GitCommit string `protobuf:"bytes,6,opt,name=git_commit,json=gitCommit,proto3" json:"git_commit,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -120,13 +67,6 @@ func (x *ChangelogPayload) GetTaskRun() string {
return ""
}
-func (x *ChangelogPayload) GetType() ChangelogPayload_Type {
- if x != nil {
- return x.Type
- }
- return ChangelogPayload_TYPE_UNSPECIFIED
-}
-
func (x *ChangelogPayload) GetGitCommit() string {
if x != nil {
return x.GitCommit
@@ -138,17 +78,11 @@ var File_store_changelog_proto protoreflect.FileDescriptor
const file_store_changelog_proto_rawDesc = "" +
"\n" +
- "\x15store/changelog.proto\x12\x0ebytebase.store\"\xcf\x01\n" +
+ "\x15store/changelog.proto\x12\x0ebytebase.store\"R\n" +
"\x10ChangelogPayload\x12\x19\n" +
- "\btask_run\x18\x01 \x01(\tR\ataskRun\x129\n" +
- "\x04type\x18\x05 \x01(\x0e2%.bytebase.store.ChangelogPayload.TypeR\x04type\x12\x1d\n" +
+ "\btask_run\x18\x01 \x01(\tR\ataskRun\x12\x1d\n" +
"\n" +
- "git_commit\x18\x06 \x01(\tR\tgitCommit\"@\n" +
- "\x04Type\x12\x14\n" +
- "\x10TYPE_UNSPECIFIED\x10\x00\x12\f\n" +
- "\bBASELINE\x10\x01\x12\v\n" +
- "\aMIGRATE\x10\x02\x12\a\n" +
- "\x03SDL\x10\x03J\x04\b\a\x10\bB\x91\x01\n" +
+ "git_commit\x18\x06 \x01(\tR\tgitCommitJ\x04\b\a\x10\bB\x91\x01\n" +
"\x12com.bytebase.storeB\x0eChangelogProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"
var (
@@ -163,19 +97,16 @@ func file_store_changelog_proto_rawDescGZIP() []byte {
return file_store_changelog_proto_rawDescData
}
-var file_store_changelog_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_store_changelog_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_store_changelog_proto_goTypes = []any{
- (ChangelogPayload_Type)(0), // 0: bytebase.store.ChangelogPayload.Type
- (*ChangelogPayload)(nil), // 1: bytebase.store.ChangelogPayload
+ (*ChangelogPayload)(nil), // 0: bytebase.store.ChangelogPayload
}
var file_store_changelog_proto_depIdxs = []int32{
- 0, // 0: bytebase.store.ChangelogPayload.type:type_name -> bytebase.store.ChangelogPayload.Type
- 1, // [1:1] is the sub-list for method output_type
- 1, // [1:1] is the sub-list for method input_type
- 1, // [1:1] is the sub-list for extension type_name
- 1, // [1:1] is the sub-list for extension extendee
- 0, // [0:1] is the sub-list for field type_name
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
}
func init() { file_store_changelog_proto_init() }
@@ -188,14 +119,13 @@ func file_store_changelog_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_changelog_proto_rawDesc), len(file_store_changelog_proto_rawDesc)),
- NumEnums: 1,
+ NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_store_changelog_proto_goTypes,
DependencyIndexes: file_store_changelog_proto_depIdxs,
- EnumInfos: file_store_changelog_proto_enumTypes,
MessageInfos: file_store_changelog_proto_msgTypes,
}.Build()
File_store_changelog_proto = out.File
diff --git a/backend/generated-go/store/changelog_equal.pb.go b/backend/generated-go/store/changelog_equal.pb.go
index 41f9ae31c4..4dd26abfcb 100644
--- a/backend/generated-go/store/changelog_equal.pb.go
+++ b/backend/generated-go/store/changelog_equal.pb.go
@@ -13,9 +13,6 @@ func (x *ChangelogPayload) Equal(y *ChangelogPayload) bool {
if x.TaskRun != y.TaskRun {
return false
}
- if x.Type != y.Type {
- return false
- }
if x.GitCommit != y.GitCommit {
return false
}
diff --git a/backend/generated-go/v1/database_service.pb.go b/backend/generated-go/v1/database_service.pb.go
index d833ec0077..735e59a72d 100644
--- a/backend/generated-go/v1/database_service.pb.go
+++ b/backend/generated-go/v1/database_service.pb.go
@@ -500,58 +500,6 @@ func (Changelog_Status) EnumDescriptor() ([]byte, []int) {
return file_v1_database_service_proto_rawDescGZIP(), []int{54, 0}
}
-type Changelog_Type int32
-
-const (
- Changelog_TYPE_UNSPECIFIED Changelog_Type = 0
- Changelog_BASELINE Changelog_Type = 1
- Changelog_MIGRATE Changelog_Type = 2
- Changelog_SDL Changelog_Type = 3
-)
-
-// Enum value maps for Changelog_Type.
-var (
- Changelog_Type_name = map[int32]string{
- 0: "TYPE_UNSPECIFIED",
- 1: "BASELINE",
- 2: "MIGRATE",
- 3: "SDL",
- }
- Changelog_Type_value = map[string]int32{
- "TYPE_UNSPECIFIED": 0,
- "BASELINE": 1,
- "MIGRATE": 2,
- "SDL": 3,
- }
-)
-
-func (x Changelog_Type) Enum() *Changelog_Type {
- p := new(Changelog_Type)
- *p = x
- return p
-}
-
-func (x Changelog_Type) String() string {
- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
-}
-
-func (Changelog_Type) Descriptor() protoreflect.EnumDescriptor {
- return file_v1_database_service_proto_enumTypes[9].Descriptor()
-}
-
-func (Changelog_Type) Type() protoreflect.EnumType {
- return &file_v1_database_service_proto_enumTypes[9]
-}
-
-func (x Changelog_Type) Number() protoreflect.EnumNumber {
- return protoreflect.EnumNumber(x)
-}
-
-// Deprecated: Use Changelog_Type.Descriptor instead.
-func (Changelog_Type) EnumDescriptor() ([]byte, []int) {
- return file_v1_database_service_proto_rawDescGZIP(), []int{54, 1}
-}
-
type GetSchemaStringRequest_ObjectType int32
const (
@@ -603,11 +551,11 @@ func (x GetSchemaStringRequest_ObjectType) String() string {
}
func (GetSchemaStringRequest_ObjectType) Descriptor() protoreflect.EnumDescriptor {
- return file_v1_database_service_proto_enumTypes[10].Descriptor()
+ return file_v1_database_service_proto_enumTypes[9].Descriptor()
}
func (GetSchemaStringRequest_ObjectType) Type() protoreflect.EnumType {
- return &file_v1_database_service_proto_enumTypes[10]
+ return &file_v1_database_service_proto_enumTypes[9]
}
func (x GetSchemaStringRequest_ObjectType) Number() protoreflect.EnumNumber {
@@ -5160,12 +5108,10 @@ type ListChangelogsRequest struct {
//
// Supported filter:
// - status: the changelog status, support "==" operation. check Changelog.Status for available values.
- // - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
// - create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
//
// Example:
// status == "DONE"
- // type in ["BASELINE", "MIGRATE"]
// status == "FAILED" && type == "SDL"
// create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"`
@@ -5359,8 +5305,7 @@ type Changelog struct {
TaskRun string `protobuf:"bytes,11,opt,name=task_run,json=taskRun,proto3" json:"task_run,omitempty"`
// The title of the plan associated with this changelog's task run.
// This field is populated by deriving the plan from task_run for display purposes.
- PlanTitle string `protobuf:"bytes,15,opt,name=plan_title,json=planTitle,proto3" json:"plan_title,omitempty"`
- Type Changelog_Type `protobuf:"varint,14,opt,name=type,proto3,enum=bytebase.v1.Changelog_Type" json:"type,omitempty"`
+ PlanTitle string `protobuf:"bytes,15,opt,name=plan_title,json=planTitle,proto3" json:"plan_title,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -5444,13 +5389,6 @@ func (x *Changelog) GetPlanTitle() string {
return ""
}
-func (x *Changelog) GetType() Changelog_Type {
- if x != nil {
- return x.Type
- }
- return Changelog_TYPE_UNSPECIFIED
-}
-
type GetSchemaStringRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The name of the database.
@@ -6045,7 +5983,7 @@ const file_v1_database_service_proto_rawDesc = "" +
"\x13GetChangelogRequest\x12:\n" +
"\x04name\x18\x01 \x01(\tB&\xe0A\x02\xfaA \n" +
"\x1ebytebase.com/DatabaseChangelogR\x04name\x12.\n" +
- "\x04view\x18\x02 \x01(\x0e2\x1a.bytebase.v1.ChangelogViewR\x04view\"\xaa\x04\n" +
+ "\x04view\x18\x02 \x01(\x0e2\x1a.bytebase.v1.ChangelogViewR\x04view\"\xb7\x03\n" +
"\tChangelog\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12;\n" +
"\vcreate_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
@@ -6056,19 +5994,13 @@ const file_v1_database_service_proto_rawDesc = "" +
"schemaSize\x12\x19\n" +
"\btask_run\x18\v \x01(\tR\ataskRun\x12\"\n" +
"\n" +
- "plan_title\x18\x0f \x01(\tB\x03\xe0A\x03R\tplanTitle\x12/\n" +
- "\x04type\x18\x0e \x01(\x0e2\x1b.bytebase.v1.Changelog.TypeR\x04type\"C\n" +
+ "plan_title\x18\x0f \x01(\tB\x03\xe0A\x03R\tplanTitle\"C\n" +
"\x06Status\x12\x16\n" +
"\x12STATUS_UNSPECIFIED\x10\x00\x12\v\n" +
"\aPENDING\x10\x01\x12\b\n" +
"\x04DONE\x10\x02\x12\n" +
"\n" +
- "\x06FAILED\x10\x03\"@\n" +
- "\x04Type\x12\x14\n" +
- "\x10TYPE_UNSPECIFIED\x10\x00\x12\f\n" +
- "\bBASELINE\x10\x01\x12\v\n" +
- "\aMIGRATE\x10\x02\x12\a\n" +
- "\x03SDL\x10\x03:e\xeaAb\n" +
+ "\x06FAILED\x10\x03:e\xeaAb\n" +
"\x1ebytebase.com/DatabaseChangelog\x12@instances/{instance}/databases/{database}/changelogs/{changelog}\"\x97\x03\n" +
"\x16GetSchemaStringRequest\x121\n" +
"\x04name\x18\x01 \x01(\tB\x1d\xe0A\x02\xfaA\x17\n" +
@@ -6125,7 +6057,7 @@ func file_v1_database_service_proto_rawDescGZIP() []byte {
return file_v1_database_service_proto_rawDescData
}
-var file_v1_database_service_proto_enumTypes = make([]protoimpl.EnumInfo, 11)
+var file_v1_database_service_proto_enumTypes = make([]protoimpl.EnumInfo, 10)
var file_v1_database_service_proto_msgTypes = make([]protoimpl.MessageInfo, 58)
var file_v1_database_service_proto_goTypes = []any{
(ChangelogView)(0), // 0: bytebase.v1.ChangelogView
@@ -6137,169 +6069,167 @@ var file_v1_database_service_proto_goTypes = []any{
(StreamMetadata_Type)(0), // 6: bytebase.v1.StreamMetadata.Type
(StreamMetadata_Mode)(0), // 7: bytebase.v1.StreamMetadata.Mode
(Changelog_Status)(0), // 8: bytebase.v1.Changelog.Status
- (Changelog_Type)(0), // 9: bytebase.v1.Changelog.Type
- (GetSchemaStringRequest_ObjectType)(0), // 10: bytebase.v1.GetSchemaStringRequest.ObjectType
- (*GetDatabaseRequest)(nil), // 11: bytebase.v1.GetDatabaseRequest
- (*BatchGetDatabasesRequest)(nil), // 12: bytebase.v1.BatchGetDatabasesRequest
- (*BatchGetDatabasesResponse)(nil), // 13: bytebase.v1.BatchGetDatabasesResponse
- (*ListDatabasesRequest)(nil), // 14: bytebase.v1.ListDatabasesRequest
- (*ListDatabasesResponse)(nil), // 15: bytebase.v1.ListDatabasesResponse
- (*UpdateDatabaseRequest)(nil), // 16: bytebase.v1.UpdateDatabaseRequest
- (*BatchUpdateDatabasesRequest)(nil), // 17: bytebase.v1.BatchUpdateDatabasesRequest
- (*BatchUpdateDatabasesResponse)(nil), // 18: bytebase.v1.BatchUpdateDatabasesResponse
- (*BatchSyncDatabasesRequest)(nil), // 19: bytebase.v1.BatchSyncDatabasesRequest
- (*BatchSyncDatabasesResponse)(nil), // 20: bytebase.v1.BatchSyncDatabasesResponse
- (*SyncDatabaseRequest)(nil), // 21: bytebase.v1.SyncDatabaseRequest
- (*SyncDatabaseResponse)(nil), // 22: bytebase.v1.SyncDatabaseResponse
- (*GetDatabaseMetadataRequest)(nil), // 23: bytebase.v1.GetDatabaseMetadataRequest
- (*GetDatabaseSchemaRequest)(nil), // 24: bytebase.v1.GetDatabaseSchemaRequest
- (*GetDatabaseSDLSchemaRequest)(nil), // 25: bytebase.v1.GetDatabaseSDLSchemaRequest
- (*DiffSchemaRequest)(nil), // 26: bytebase.v1.DiffSchemaRequest
- (*DiffSchemaResponse)(nil), // 27: bytebase.v1.DiffSchemaResponse
- (*Database)(nil), // 28: bytebase.v1.Database
- (*DatabaseMetadata)(nil), // 29: bytebase.v1.DatabaseMetadata
- (*SchemaMetadata)(nil), // 30: bytebase.v1.SchemaMetadata
- (*EnumTypeMetadata)(nil), // 31: bytebase.v1.EnumTypeMetadata
- (*EventMetadata)(nil), // 32: bytebase.v1.EventMetadata
- (*SequenceMetadata)(nil), // 33: bytebase.v1.SequenceMetadata
- (*TriggerMetadata)(nil), // 34: bytebase.v1.TriggerMetadata
- (*ExternalTableMetadata)(nil), // 35: bytebase.v1.ExternalTableMetadata
- (*TableMetadata)(nil), // 36: bytebase.v1.TableMetadata
- (*CheckConstraintMetadata)(nil), // 37: bytebase.v1.CheckConstraintMetadata
- (*TablePartitionMetadata)(nil), // 38: bytebase.v1.TablePartitionMetadata
- (*ColumnMetadata)(nil), // 39: bytebase.v1.ColumnMetadata
- (*GenerationMetadata)(nil), // 40: bytebase.v1.GenerationMetadata
- (*ViewMetadata)(nil), // 41: bytebase.v1.ViewMetadata
- (*DependencyColumn)(nil), // 42: bytebase.v1.DependencyColumn
- (*MaterializedViewMetadata)(nil), // 43: bytebase.v1.MaterializedViewMetadata
- (*DependencyTable)(nil), // 44: bytebase.v1.DependencyTable
- (*FunctionMetadata)(nil), // 45: bytebase.v1.FunctionMetadata
- (*ProcedureMetadata)(nil), // 46: bytebase.v1.ProcedureMetadata
- (*PackageMetadata)(nil), // 47: bytebase.v1.PackageMetadata
- (*TaskMetadata)(nil), // 48: bytebase.v1.TaskMetadata
- (*StreamMetadata)(nil), // 49: bytebase.v1.StreamMetadata
- (*SpatialIndexConfig)(nil), // 50: bytebase.v1.SpatialIndexConfig
- (*TessellationConfig)(nil), // 51: bytebase.v1.TessellationConfig
- (*GridLevel)(nil), // 52: bytebase.v1.GridLevel
- (*BoundingBox)(nil), // 53: bytebase.v1.BoundingBox
- (*StorageConfig)(nil), // 54: bytebase.v1.StorageConfig
- (*DimensionalConfig)(nil), // 55: bytebase.v1.DimensionalConfig
- (*DimensionConstraint)(nil), // 56: bytebase.v1.DimensionConstraint
- (*IndexMetadata)(nil), // 57: bytebase.v1.IndexMetadata
- (*ExtensionMetadata)(nil), // 58: bytebase.v1.ExtensionMetadata
- (*ForeignKeyMetadata)(nil), // 59: bytebase.v1.ForeignKeyMetadata
- (*DatabaseSchema)(nil), // 60: bytebase.v1.DatabaseSchema
- (*DatabaseSDLSchema)(nil), // 61: bytebase.v1.DatabaseSDLSchema
- (*ListChangelogsRequest)(nil), // 62: bytebase.v1.ListChangelogsRequest
- (*ListChangelogsResponse)(nil), // 63: bytebase.v1.ListChangelogsResponse
- (*GetChangelogRequest)(nil), // 64: bytebase.v1.GetChangelogRequest
- (*Changelog)(nil), // 65: bytebase.v1.Changelog
- (*GetSchemaStringRequest)(nil), // 66: bytebase.v1.GetSchemaStringRequest
- (*GetSchemaStringResponse)(nil), // 67: bytebase.v1.GetSchemaStringResponse
- nil, // 68: bytebase.v1.Database.LabelsEntry
- (*fieldmaskpb.FieldMask)(nil), // 69: google.protobuf.FieldMask
- (State)(0), // 70: bytebase.v1.State
- (*timestamppb.Timestamp)(nil), // 71: google.protobuf.Timestamp
- (*InstanceResource)(nil), // 72: bytebase.v1.InstanceResource
+ (GetSchemaStringRequest_ObjectType)(0), // 9: bytebase.v1.GetSchemaStringRequest.ObjectType
+ (*GetDatabaseRequest)(nil), // 10: bytebase.v1.GetDatabaseRequest
+ (*BatchGetDatabasesRequest)(nil), // 11: bytebase.v1.BatchGetDatabasesRequest
+ (*BatchGetDatabasesResponse)(nil), // 12: bytebase.v1.BatchGetDatabasesResponse
+ (*ListDatabasesRequest)(nil), // 13: bytebase.v1.ListDatabasesRequest
+ (*ListDatabasesResponse)(nil), // 14: bytebase.v1.ListDatabasesResponse
+ (*UpdateDatabaseRequest)(nil), // 15: bytebase.v1.UpdateDatabaseRequest
+ (*BatchUpdateDatabasesRequest)(nil), // 16: bytebase.v1.BatchUpdateDatabasesRequest
+ (*BatchUpdateDatabasesResponse)(nil), // 17: bytebase.v1.BatchUpdateDatabasesResponse
+ (*BatchSyncDatabasesRequest)(nil), // 18: bytebase.v1.BatchSyncDatabasesRequest
+ (*BatchSyncDatabasesResponse)(nil), // 19: bytebase.v1.BatchSyncDatabasesResponse
+ (*SyncDatabaseRequest)(nil), // 20: bytebase.v1.SyncDatabaseRequest
+ (*SyncDatabaseResponse)(nil), // 21: bytebase.v1.SyncDatabaseResponse
+ (*GetDatabaseMetadataRequest)(nil), // 22: bytebase.v1.GetDatabaseMetadataRequest
+ (*GetDatabaseSchemaRequest)(nil), // 23: bytebase.v1.GetDatabaseSchemaRequest
+ (*GetDatabaseSDLSchemaRequest)(nil), // 24: bytebase.v1.GetDatabaseSDLSchemaRequest
+ (*DiffSchemaRequest)(nil), // 25: bytebase.v1.DiffSchemaRequest
+ (*DiffSchemaResponse)(nil), // 26: bytebase.v1.DiffSchemaResponse
+ (*Database)(nil), // 27: bytebase.v1.Database
+ (*DatabaseMetadata)(nil), // 28: bytebase.v1.DatabaseMetadata
+ (*SchemaMetadata)(nil), // 29: bytebase.v1.SchemaMetadata
+ (*EnumTypeMetadata)(nil), // 30: bytebase.v1.EnumTypeMetadata
+ (*EventMetadata)(nil), // 31: bytebase.v1.EventMetadata
+ (*SequenceMetadata)(nil), // 32: bytebase.v1.SequenceMetadata
+ (*TriggerMetadata)(nil), // 33: bytebase.v1.TriggerMetadata
+ (*ExternalTableMetadata)(nil), // 34: bytebase.v1.ExternalTableMetadata
+ (*TableMetadata)(nil), // 35: bytebase.v1.TableMetadata
+ (*CheckConstraintMetadata)(nil), // 36: bytebase.v1.CheckConstraintMetadata
+ (*TablePartitionMetadata)(nil), // 37: bytebase.v1.TablePartitionMetadata
+ (*ColumnMetadata)(nil), // 38: bytebase.v1.ColumnMetadata
+ (*GenerationMetadata)(nil), // 39: bytebase.v1.GenerationMetadata
+ (*ViewMetadata)(nil), // 40: bytebase.v1.ViewMetadata
+ (*DependencyColumn)(nil), // 41: bytebase.v1.DependencyColumn
+ (*MaterializedViewMetadata)(nil), // 42: bytebase.v1.MaterializedViewMetadata
+ (*DependencyTable)(nil), // 43: bytebase.v1.DependencyTable
+ (*FunctionMetadata)(nil), // 44: bytebase.v1.FunctionMetadata
+ (*ProcedureMetadata)(nil), // 45: bytebase.v1.ProcedureMetadata
+ (*PackageMetadata)(nil), // 46: bytebase.v1.PackageMetadata
+ (*TaskMetadata)(nil), // 47: bytebase.v1.TaskMetadata
+ (*StreamMetadata)(nil), // 48: bytebase.v1.StreamMetadata
+ (*SpatialIndexConfig)(nil), // 49: bytebase.v1.SpatialIndexConfig
+ (*TessellationConfig)(nil), // 50: bytebase.v1.TessellationConfig
+ (*GridLevel)(nil), // 51: bytebase.v1.GridLevel
+ (*BoundingBox)(nil), // 52: bytebase.v1.BoundingBox
+ (*StorageConfig)(nil), // 53: bytebase.v1.StorageConfig
+ (*DimensionalConfig)(nil), // 54: bytebase.v1.DimensionalConfig
+ (*DimensionConstraint)(nil), // 55: bytebase.v1.DimensionConstraint
+ (*IndexMetadata)(nil), // 56: bytebase.v1.IndexMetadata
+ (*ExtensionMetadata)(nil), // 57: bytebase.v1.ExtensionMetadata
+ (*ForeignKeyMetadata)(nil), // 58: bytebase.v1.ForeignKeyMetadata
+ (*DatabaseSchema)(nil), // 59: bytebase.v1.DatabaseSchema
+ (*DatabaseSDLSchema)(nil), // 60: bytebase.v1.DatabaseSDLSchema
+ (*ListChangelogsRequest)(nil), // 61: bytebase.v1.ListChangelogsRequest
+ (*ListChangelogsResponse)(nil), // 62: bytebase.v1.ListChangelogsResponse
+ (*GetChangelogRequest)(nil), // 63: bytebase.v1.GetChangelogRequest
+ (*Changelog)(nil), // 64: bytebase.v1.Changelog
+ (*GetSchemaStringRequest)(nil), // 65: bytebase.v1.GetSchemaStringRequest
+ (*GetSchemaStringResponse)(nil), // 66: bytebase.v1.GetSchemaStringResponse
+ nil, // 67: bytebase.v1.Database.LabelsEntry
+ (*fieldmaskpb.FieldMask)(nil), // 68: google.protobuf.FieldMask
+ (State)(0), // 69: bytebase.v1.State
+ (*timestamppb.Timestamp)(nil), // 70: google.protobuf.Timestamp
+ (*InstanceResource)(nil), // 71: bytebase.v1.InstanceResource
}
var file_v1_database_service_proto_depIdxs = []int32{
- 28, // 0: bytebase.v1.BatchGetDatabasesResponse.databases:type_name -> bytebase.v1.Database
- 28, // 1: bytebase.v1.ListDatabasesResponse.databases:type_name -> bytebase.v1.Database
- 28, // 2: bytebase.v1.UpdateDatabaseRequest.database:type_name -> bytebase.v1.Database
- 69, // 3: bytebase.v1.UpdateDatabaseRequest.update_mask:type_name -> google.protobuf.FieldMask
- 16, // 4: bytebase.v1.BatchUpdateDatabasesRequest.requests:type_name -> bytebase.v1.UpdateDatabaseRequest
- 28, // 5: bytebase.v1.BatchUpdateDatabasesResponse.databases:type_name -> bytebase.v1.Database
+ 27, // 0: bytebase.v1.BatchGetDatabasesResponse.databases:type_name -> bytebase.v1.Database
+ 27, // 1: bytebase.v1.ListDatabasesResponse.databases:type_name -> bytebase.v1.Database
+ 27, // 2: bytebase.v1.UpdateDatabaseRequest.database:type_name -> bytebase.v1.Database
+ 68, // 3: bytebase.v1.UpdateDatabaseRequest.update_mask:type_name -> google.protobuf.FieldMask
+ 15, // 4: bytebase.v1.BatchUpdateDatabasesRequest.requests:type_name -> bytebase.v1.UpdateDatabaseRequest
+ 27, // 5: bytebase.v1.BatchUpdateDatabasesResponse.databases:type_name -> bytebase.v1.Database
1, // 6: bytebase.v1.GetDatabaseSDLSchemaRequest.format:type_name -> bytebase.v1.GetDatabaseSDLSchemaRequest.SDLFormat
- 70, // 7: bytebase.v1.Database.state:type_name -> bytebase.v1.State
- 71, // 8: bytebase.v1.Database.successful_sync_time:type_name -> google.protobuf.Timestamp
- 68, // 9: bytebase.v1.Database.labels:type_name -> bytebase.v1.Database.LabelsEntry
- 72, // 10: bytebase.v1.Database.instance_resource:type_name -> bytebase.v1.InstanceResource
- 30, // 11: bytebase.v1.DatabaseMetadata.schemas:type_name -> bytebase.v1.SchemaMetadata
- 58, // 12: bytebase.v1.DatabaseMetadata.extensions:type_name -> bytebase.v1.ExtensionMetadata
- 36, // 13: bytebase.v1.SchemaMetadata.tables:type_name -> bytebase.v1.TableMetadata
- 35, // 14: bytebase.v1.SchemaMetadata.external_tables:type_name -> bytebase.v1.ExternalTableMetadata
- 41, // 15: bytebase.v1.SchemaMetadata.views:type_name -> bytebase.v1.ViewMetadata
- 45, // 16: bytebase.v1.SchemaMetadata.functions:type_name -> bytebase.v1.FunctionMetadata
- 46, // 17: bytebase.v1.SchemaMetadata.procedures:type_name -> bytebase.v1.ProcedureMetadata
- 49, // 18: bytebase.v1.SchemaMetadata.streams:type_name -> bytebase.v1.StreamMetadata
- 48, // 19: bytebase.v1.SchemaMetadata.tasks:type_name -> bytebase.v1.TaskMetadata
- 43, // 20: bytebase.v1.SchemaMetadata.materialized_views:type_name -> bytebase.v1.MaterializedViewMetadata
- 47, // 21: bytebase.v1.SchemaMetadata.packages:type_name -> bytebase.v1.PackageMetadata
- 33, // 22: bytebase.v1.SchemaMetadata.sequences:type_name -> bytebase.v1.SequenceMetadata
- 32, // 23: bytebase.v1.SchemaMetadata.events:type_name -> bytebase.v1.EventMetadata
- 31, // 24: bytebase.v1.SchemaMetadata.enum_types:type_name -> bytebase.v1.EnumTypeMetadata
- 39, // 25: bytebase.v1.ExternalTableMetadata.columns:type_name -> bytebase.v1.ColumnMetadata
- 39, // 26: bytebase.v1.TableMetadata.columns:type_name -> bytebase.v1.ColumnMetadata
- 57, // 27: bytebase.v1.TableMetadata.indexes:type_name -> bytebase.v1.IndexMetadata
- 59, // 28: bytebase.v1.TableMetadata.foreign_keys:type_name -> bytebase.v1.ForeignKeyMetadata
- 38, // 29: bytebase.v1.TableMetadata.partitions:type_name -> bytebase.v1.TablePartitionMetadata
- 37, // 30: bytebase.v1.TableMetadata.check_constraints:type_name -> bytebase.v1.CheckConstraintMetadata
- 34, // 31: bytebase.v1.TableMetadata.triggers:type_name -> bytebase.v1.TriggerMetadata
+ 69, // 7: bytebase.v1.Database.state:type_name -> bytebase.v1.State
+ 70, // 8: bytebase.v1.Database.successful_sync_time:type_name -> google.protobuf.Timestamp
+ 67, // 9: bytebase.v1.Database.labels:type_name -> bytebase.v1.Database.LabelsEntry
+ 71, // 10: bytebase.v1.Database.instance_resource:type_name -> bytebase.v1.InstanceResource
+ 29, // 11: bytebase.v1.DatabaseMetadata.schemas:type_name -> bytebase.v1.SchemaMetadata
+ 57, // 12: bytebase.v1.DatabaseMetadata.extensions:type_name -> bytebase.v1.ExtensionMetadata
+ 35, // 13: bytebase.v1.SchemaMetadata.tables:type_name -> bytebase.v1.TableMetadata
+ 34, // 14: bytebase.v1.SchemaMetadata.external_tables:type_name -> bytebase.v1.ExternalTableMetadata
+ 40, // 15: bytebase.v1.SchemaMetadata.views:type_name -> bytebase.v1.ViewMetadata
+ 44, // 16: bytebase.v1.SchemaMetadata.functions:type_name -> bytebase.v1.FunctionMetadata
+ 45, // 17: bytebase.v1.SchemaMetadata.procedures:type_name -> bytebase.v1.ProcedureMetadata
+ 48, // 18: bytebase.v1.SchemaMetadata.streams:type_name -> bytebase.v1.StreamMetadata
+ 47, // 19: bytebase.v1.SchemaMetadata.tasks:type_name -> bytebase.v1.TaskMetadata
+ 42, // 20: bytebase.v1.SchemaMetadata.materialized_views:type_name -> bytebase.v1.MaterializedViewMetadata
+ 46, // 21: bytebase.v1.SchemaMetadata.packages:type_name -> bytebase.v1.PackageMetadata
+ 32, // 22: bytebase.v1.SchemaMetadata.sequences:type_name -> bytebase.v1.SequenceMetadata
+ 31, // 23: bytebase.v1.SchemaMetadata.events:type_name -> bytebase.v1.EventMetadata
+ 30, // 24: bytebase.v1.SchemaMetadata.enum_types:type_name -> bytebase.v1.EnumTypeMetadata
+ 38, // 25: bytebase.v1.ExternalTableMetadata.columns:type_name -> bytebase.v1.ColumnMetadata
+ 38, // 26: bytebase.v1.TableMetadata.columns:type_name -> bytebase.v1.ColumnMetadata
+ 56, // 27: bytebase.v1.TableMetadata.indexes:type_name -> bytebase.v1.IndexMetadata
+ 58, // 28: bytebase.v1.TableMetadata.foreign_keys:type_name -> bytebase.v1.ForeignKeyMetadata
+ 37, // 29: bytebase.v1.TableMetadata.partitions:type_name -> bytebase.v1.TablePartitionMetadata
+ 36, // 30: bytebase.v1.TableMetadata.check_constraints:type_name -> bytebase.v1.CheckConstraintMetadata
+ 33, // 31: bytebase.v1.TableMetadata.triggers:type_name -> bytebase.v1.TriggerMetadata
2, // 32: bytebase.v1.TablePartitionMetadata.type:type_name -> bytebase.v1.TablePartitionMetadata.Type
- 38, // 33: bytebase.v1.TablePartitionMetadata.subpartitions:type_name -> bytebase.v1.TablePartitionMetadata
- 57, // 34: bytebase.v1.TablePartitionMetadata.indexes:type_name -> bytebase.v1.IndexMetadata
- 37, // 35: bytebase.v1.TablePartitionMetadata.check_constraints:type_name -> bytebase.v1.CheckConstraintMetadata
- 40, // 36: bytebase.v1.ColumnMetadata.generation:type_name -> bytebase.v1.GenerationMetadata
+ 37, // 33: bytebase.v1.TablePartitionMetadata.subpartitions:type_name -> bytebase.v1.TablePartitionMetadata
+ 56, // 34: bytebase.v1.TablePartitionMetadata.indexes:type_name -> bytebase.v1.IndexMetadata
+ 36, // 35: bytebase.v1.TablePartitionMetadata.check_constraints:type_name -> bytebase.v1.CheckConstraintMetadata
+ 39, // 36: bytebase.v1.ColumnMetadata.generation:type_name -> bytebase.v1.GenerationMetadata
3, // 37: bytebase.v1.ColumnMetadata.identity_generation:type_name -> bytebase.v1.ColumnMetadata.IdentityGeneration
4, // 38: bytebase.v1.GenerationMetadata.type:type_name -> bytebase.v1.GenerationMetadata.Type
- 42, // 39: bytebase.v1.ViewMetadata.dependency_columns:type_name -> bytebase.v1.DependencyColumn
- 39, // 40: bytebase.v1.ViewMetadata.columns:type_name -> bytebase.v1.ColumnMetadata
- 34, // 41: bytebase.v1.ViewMetadata.triggers:type_name -> bytebase.v1.TriggerMetadata
- 42, // 42: bytebase.v1.MaterializedViewMetadata.dependency_columns:type_name -> bytebase.v1.DependencyColumn
- 34, // 43: bytebase.v1.MaterializedViewMetadata.triggers:type_name -> bytebase.v1.TriggerMetadata
- 57, // 44: bytebase.v1.MaterializedViewMetadata.indexes:type_name -> bytebase.v1.IndexMetadata
- 44, // 45: bytebase.v1.FunctionMetadata.dependency_tables:type_name -> bytebase.v1.DependencyTable
+ 41, // 39: bytebase.v1.ViewMetadata.dependency_columns:type_name -> bytebase.v1.DependencyColumn
+ 38, // 40: bytebase.v1.ViewMetadata.columns:type_name -> bytebase.v1.ColumnMetadata
+ 33, // 41: bytebase.v1.ViewMetadata.triggers:type_name -> bytebase.v1.TriggerMetadata
+ 41, // 42: bytebase.v1.MaterializedViewMetadata.dependency_columns:type_name -> bytebase.v1.DependencyColumn
+ 33, // 43: bytebase.v1.MaterializedViewMetadata.triggers:type_name -> bytebase.v1.TriggerMetadata
+ 56, // 44: bytebase.v1.MaterializedViewMetadata.indexes:type_name -> bytebase.v1.IndexMetadata
+ 43, // 45: bytebase.v1.FunctionMetadata.dependency_tables:type_name -> bytebase.v1.DependencyTable
5, // 46: bytebase.v1.TaskMetadata.state:type_name -> bytebase.v1.TaskMetadata.State
6, // 47: bytebase.v1.StreamMetadata.type:type_name -> bytebase.v1.StreamMetadata.Type
7, // 48: bytebase.v1.StreamMetadata.mode:type_name -> bytebase.v1.StreamMetadata.Mode
- 51, // 49: bytebase.v1.SpatialIndexConfig.tessellation:type_name -> bytebase.v1.TessellationConfig
- 54, // 50: bytebase.v1.SpatialIndexConfig.storage:type_name -> bytebase.v1.StorageConfig
- 55, // 51: bytebase.v1.SpatialIndexConfig.dimensional:type_name -> bytebase.v1.DimensionalConfig
- 52, // 52: bytebase.v1.TessellationConfig.grid_levels:type_name -> bytebase.v1.GridLevel
- 53, // 53: bytebase.v1.TessellationConfig.bounding_box:type_name -> bytebase.v1.BoundingBox
- 56, // 54: bytebase.v1.DimensionalConfig.constraints:type_name -> bytebase.v1.DimensionConstraint
- 50, // 55: bytebase.v1.IndexMetadata.spatial_config:type_name -> bytebase.v1.SpatialIndexConfig
+ 50, // 49: bytebase.v1.SpatialIndexConfig.tessellation:type_name -> bytebase.v1.TessellationConfig
+ 53, // 50: bytebase.v1.SpatialIndexConfig.storage:type_name -> bytebase.v1.StorageConfig
+ 54, // 51: bytebase.v1.SpatialIndexConfig.dimensional:type_name -> bytebase.v1.DimensionalConfig
+ 51, // 52: bytebase.v1.TessellationConfig.grid_levels:type_name -> bytebase.v1.GridLevel
+ 52, // 53: bytebase.v1.TessellationConfig.bounding_box:type_name -> bytebase.v1.BoundingBox
+ 55, // 54: bytebase.v1.DimensionalConfig.constraints:type_name -> bytebase.v1.DimensionConstraint
+ 49, // 55: bytebase.v1.IndexMetadata.spatial_config:type_name -> bytebase.v1.SpatialIndexConfig
0, // 56: bytebase.v1.ListChangelogsRequest.view:type_name -> bytebase.v1.ChangelogView
- 65, // 57: bytebase.v1.ListChangelogsResponse.changelogs:type_name -> bytebase.v1.Changelog
+ 64, // 57: bytebase.v1.ListChangelogsResponse.changelogs:type_name -> bytebase.v1.Changelog
0, // 58: bytebase.v1.GetChangelogRequest.view:type_name -> bytebase.v1.ChangelogView
- 71, // 59: bytebase.v1.Changelog.create_time:type_name -> google.protobuf.Timestamp
+ 70, // 59: bytebase.v1.Changelog.create_time:type_name -> google.protobuf.Timestamp
8, // 60: bytebase.v1.Changelog.status:type_name -> bytebase.v1.Changelog.Status
- 9, // 61: bytebase.v1.Changelog.type:type_name -> bytebase.v1.Changelog.Type
- 10, // 62: bytebase.v1.GetSchemaStringRequest.type:type_name -> bytebase.v1.GetSchemaStringRequest.ObjectType
- 29, // 63: bytebase.v1.GetSchemaStringRequest.metadata:type_name -> bytebase.v1.DatabaseMetadata
- 11, // 64: bytebase.v1.DatabaseService.GetDatabase:input_type -> bytebase.v1.GetDatabaseRequest
- 12, // 65: bytebase.v1.DatabaseService.BatchGetDatabases:input_type -> bytebase.v1.BatchGetDatabasesRequest
- 14, // 66: bytebase.v1.DatabaseService.ListDatabases:input_type -> bytebase.v1.ListDatabasesRequest
- 16, // 67: bytebase.v1.DatabaseService.UpdateDatabase:input_type -> bytebase.v1.UpdateDatabaseRequest
- 17, // 68: bytebase.v1.DatabaseService.BatchUpdateDatabases:input_type -> bytebase.v1.BatchUpdateDatabasesRequest
- 21, // 69: bytebase.v1.DatabaseService.SyncDatabase:input_type -> bytebase.v1.SyncDatabaseRequest
- 19, // 70: bytebase.v1.DatabaseService.BatchSyncDatabases:input_type -> bytebase.v1.BatchSyncDatabasesRequest
- 23, // 71: bytebase.v1.DatabaseService.GetDatabaseMetadata:input_type -> bytebase.v1.GetDatabaseMetadataRequest
- 24, // 72: bytebase.v1.DatabaseService.GetDatabaseSchema:input_type -> bytebase.v1.GetDatabaseSchemaRequest
- 25, // 73: bytebase.v1.DatabaseService.GetDatabaseSDLSchema:input_type -> bytebase.v1.GetDatabaseSDLSchemaRequest
- 26, // 74: bytebase.v1.DatabaseService.DiffSchema:input_type -> bytebase.v1.DiffSchemaRequest
- 62, // 75: bytebase.v1.DatabaseService.ListChangelogs:input_type -> bytebase.v1.ListChangelogsRequest
- 64, // 76: bytebase.v1.DatabaseService.GetChangelog:input_type -> bytebase.v1.GetChangelogRequest
- 66, // 77: bytebase.v1.DatabaseService.GetSchemaString:input_type -> bytebase.v1.GetSchemaStringRequest
- 28, // 78: bytebase.v1.DatabaseService.GetDatabase:output_type -> bytebase.v1.Database
- 13, // 79: bytebase.v1.DatabaseService.BatchGetDatabases:output_type -> bytebase.v1.BatchGetDatabasesResponse
- 15, // 80: bytebase.v1.DatabaseService.ListDatabases:output_type -> bytebase.v1.ListDatabasesResponse
- 28, // 81: bytebase.v1.DatabaseService.UpdateDatabase:output_type -> bytebase.v1.Database
- 18, // 82: bytebase.v1.DatabaseService.BatchUpdateDatabases:output_type -> bytebase.v1.BatchUpdateDatabasesResponse
- 22, // 83: bytebase.v1.DatabaseService.SyncDatabase:output_type -> bytebase.v1.SyncDatabaseResponse
- 20, // 84: bytebase.v1.DatabaseService.BatchSyncDatabases:output_type -> bytebase.v1.BatchSyncDatabasesResponse
- 29, // 85: bytebase.v1.DatabaseService.GetDatabaseMetadata:output_type -> bytebase.v1.DatabaseMetadata
- 60, // 86: bytebase.v1.DatabaseService.GetDatabaseSchema:output_type -> bytebase.v1.DatabaseSchema
- 61, // 87: bytebase.v1.DatabaseService.GetDatabaseSDLSchema:output_type -> bytebase.v1.DatabaseSDLSchema
- 27, // 88: bytebase.v1.DatabaseService.DiffSchema:output_type -> bytebase.v1.DiffSchemaResponse
- 63, // 89: bytebase.v1.DatabaseService.ListChangelogs:output_type -> bytebase.v1.ListChangelogsResponse
- 65, // 90: bytebase.v1.DatabaseService.GetChangelog:output_type -> bytebase.v1.Changelog
- 67, // 91: bytebase.v1.DatabaseService.GetSchemaString:output_type -> bytebase.v1.GetSchemaStringResponse
- 78, // [78:92] is the sub-list for method output_type
- 64, // [64:78] is the sub-list for method input_type
- 64, // [64:64] is the sub-list for extension type_name
- 64, // [64:64] is the sub-list for extension extendee
- 0, // [0:64] is the sub-list for field type_name
+ 9, // 61: bytebase.v1.GetSchemaStringRequest.type:type_name -> bytebase.v1.GetSchemaStringRequest.ObjectType
+ 28, // 62: bytebase.v1.GetSchemaStringRequest.metadata:type_name -> bytebase.v1.DatabaseMetadata
+ 10, // 63: bytebase.v1.DatabaseService.GetDatabase:input_type -> bytebase.v1.GetDatabaseRequest
+ 11, // 64: bytebase.v1.DatabaseService.BatchGetDatabases:input_type -> bytebase.v1.BatchGetDatabasesRequest
+ 13, // 65: bytebase.v1.DatabaseService.ListDatabases:input_type -> bytebase.v1.ListDatabasesRequest
+ 15, // 66: bytebase.v1.DatabaseService.UpdateDatabase:input_type -> bytebase.v1.UpdateDatabaseRequest
+ 16, // 67: bytebase.v1.DatabaseService.BatchUpdateDatabases:input_type -> bytebase.v1.BatchUpdateDatabasesRequest
+ 20, // 68: bytebase.v1.DatabaseService.SyncDatabase:input_type -> bytebase.v1.SyncDatabaseRequest
+ 18, // 69: bytebase.v1.DatabaseService.BatchSyncDatabases:input_type -> bytebase.v1.BatchSyncDatabasesRequest
+ 22, // 70: bytebase.v1.DatabaseService.GetDatabaseMetadata:input_type -> bytebase.v1.GetDatabaseMetadataRequest
+ 23, // 71: bytebase.v1.DatabaseService.GetDatabaseSchema:input_type -> bytebase.v1.GetDatabaseSchemaRequest
+ 24, // 72: bytebase.v1.DatabaseService.GetDatabaseSDLSchema:input_type -> bytebase.v1.GetDatabaseSDLSchemaRequest
+ 25, // 73: bytebase.v1.DatabaseService.DiffSchema:input_type -> bytebase.v1.DiffSchemaRequest
+ 61, // 74: bytebase.v1.DatabaseService.ListChangelogs:input_type -> bytebase.v1.ListChangelogsRequest
+ 63, // 75: bytebase.v1.DatabaseService.GetChangelog:input_type -> bytebase.v1.GetChangelogRequest
+ 65, // 76: bytebase.v1.DatabaseService.GetSchemaString:input_type -> bytebase.v1.GetSchemaStringRequest
+ 27, // 77: bytebase.v1.DatabaseService.GetDatabase:output_type -> bytebase.v1.Database
+ 12, // 78: bytebase.v1.DatabaseService.BatchGetDatabases:output_type -> bytebase.v1.BatchGetDatabasesResponse
+ 14, // 79: bytebase.v1.DatabaseService.ListDatabases:output_type -> bytebase.v1.ListDatabasesResponse
+ 27, // 80: bytebase.v1.DatabaseService.UpdateDatabase:output_type -> bytebase.v1.Database
+ 17, // 81: bytebase.v1.DatabaseService.BatchUpdateDatabases:output_type -> bytebase.v1.BatchUpdateDatabasesResponse
+ 21, // 82: bytebase.v1.DatabaseService.SyncDatabase:output_type -> bytebase.v1.SyncDatabaseResponse
+ 19, // 83: bytebase.v1.DatabaseService.BatchSyncDatabases:output_type -> bytebase.v1.BatchSyncDatabasesResponse
+ 28, // 84: bytebase.v1.DatabaseService.GetDatabaseMetadata:output_type -> bytebase.v1.DatabaseMetadata
+ 59, // 85: bytebase.v1.DatabaseService.GetDatabaseSchema:output_type -> bytebase.v1.DatabaseSchema
+ 60, // 86: bytebase.v1.DatabaseService.GetDatabaseSDLSchema:output_type -> bytebase.v1.DatabaseSDLSchema
+ 26, // 87: bytebase.v1.DatabaseService.DiffSchema:output_type -> bytebase.v1.DiffSchemaResponse
+ 62, // 88: bytebase.v1.DatabaseService.ListChangelogs:output_type -> bytebase.v1.ListChangelogsResponse
+ 64, // 89: bytebase.v1.DatabaseService.GetChangelog:output_type -> bytebase.v1.Changelog
+ 66, // 90: bytebase.v1.DatabaseService.GetSchemaString:output_type -> bytebase.v1.GetSchemaStringResponse
+ 77, // [77:91] is the sub-list for method output_type
+ 63, // [63:77] is the sub-list for method input_type
+ 63, // [63:63] is the sub-list for extension type_name
+ 63, // [63:63] is the sub-list for extension extendee
+ 0, // [0:63] is the sub-list for field type_name
}
func init() { file_v1_database_service_proto_init() }
@@ -6320,7 +6250,7 @@ func file_v1_database_service_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_database_service_proto_rawDesc), len(file_v1_database_service_proto_rawDesc)),
- NumEnums: 11,
+ NumEnums: 10,
NumMessages: 58,
NumExtensions: 0,
NumServices: 1,
diff --git a/backend/generated-go/v1/database_service_equal.pb.go b/backend/generated-go/v1/database_service_equal.pb.go
index a4abdcfc8c..c174440d04 100644
--- a/backend/generated-go/v1/database_service_equal.pb.go
+++ b/backend/generated-go/v1/database_service_equal.pb.go
@@ -1698,9 +1698,6 @@ func (x *Changelog) Equal(y *Changelog) bool {
if x.PlanTitle != y.PlanTitle {
return false
}
- if x.Type != y.Type {
- return false
- }
return true
}
diff --git a/backend/plugin/schema/pg/column_migration_integration_test.go b/backend/plugin/schema/pg/column_migration_integration_test.go
index 0915cadac9..8bdec7564b 100644
--- a/backend/plugin/schema/pg/column_migration_integration_test.go
+++ b/backend/plugin/schema/pg/column_migration_integration_test.go
@@ -387,7 +387,7 @@ ALTER TABLE "public"."documents" ALTER COLUMN "content" SET DEFAULT '';
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Step 1: Get SDL diff using AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/column_rewrite_test.go b/backend/plugin/schema/pg/column_rewrite_test.go
deleted file mode 100644
index 7f77c00248..0000000000
--- a/backend/plugin/schema/pg/column_rewrite_test.go
+++ /dev/null
@@ -1,513 +0,0 @@
-package pg
-
-import (
- "testing"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/postgresql"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
- "github.com/bytebase/bytebase/backend/plugin/schema"
-)
-
-// TestColumnRewriteOperations tests the ANTLR TokenStreamRewriter functionality
-// for column operations including add, modify, delete with various edge cases
-func TestColumnRewriteOperations(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- currentTable *storepb.TableMetadata
- previousTable *storepb.TableMetadata
- expectedSDL string
- description string
- }{
- // Single Column Add Tests
- {
- name: "Add column to single column table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "name" VARCHAR(50)
-);`,
- description: "Should add second column with proper comma",
- },
- {
- name: "Add column to multi-column table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- {Name: "email", Type: "VARCHAR(100)", Nullable: true, Default: "'[email protected]'"},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "name" VARCHAR(50),
- "email" VARCHAR(100) DEFAULT '[email protected]'
-);`,
- description: "Should add third column with default value",
- },
-
- // Single Column Drop Tests
- {
- name: "Drop last column from two-column table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL
-);`,
- description: "Should drop last column and remove preceding comma",
- },
- {
- name: "Drop first column from two-column table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "name" VARCHAR(50)
-);`,
- description: "Should drop first column and remove following comma",
- },
- {
- name: "Drop middle column from three-column table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50),
- email VARCHAR(100)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(100)", Nullable: true},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- {Name: "email", Type: "VARCHAR(100)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "email" VARCHAR(100)
-);`,
- description: "Should drop middle column and handle comma correctly",
- },
-
- // Column Modify Tests
- {
- name: "Modify column type",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "TEXT", Nullable: true},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "name" TEXT
-);`,
- description: "Should modify column type from VARCHAR to TEXT",
- },
- {
- name: "Modify column nullable constraint",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: false},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "name" VARCHAR(50) NOT NULL
-);`,
- description: "Should add NOT NULL constraint",
- },
- {
- name: "Add default value to column",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true, Default: "'unknown'"},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "name" VARCHAR(50) DEFAULT 'unknown'
-);`,
- description: "Should add default value to existing column",
- },
-
- // Complex Multi-Operation Tests
- {
- name: "Drop first, modify middle, add last",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50),
- email VARCHAR(100)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "name", Type: "TEXT", Nullable: false},
- {Name: "email", Type: "VARCHAR(100)", Nullable: true},
- {Name: "created_at", Type: "TIMESTAMP", Nullable: true, Default: "CURRENT_TIMESTAMP"},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- {Name: "email", Type: "VARCHAR(100)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "name" TEXT NOT NULL,
- "email" VARCHAR(100),
- "created_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);`,
- description: "Should handle complex multi-operation scenario",
- },
- {
- name: "Drop last column and add new column",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(100)", Nullable: true, Default: "'[email protected]'"},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "email" VARCHAR(100) DEFAULT '[email protected]'
-);`,
- description: "Should drop last column and add new column in its place",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the original SDL to create an AST chunk
- parseResults, err := pgparser.ParsePostgreSQL(tc.originalSDL)
- require.NoError(t, err, "Failed to parse original SDL")
- require.Len(t, parseResults, 1, "Should parse single statement")
-
- // Extract the CREATE TABLE AST node
- var createTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createTableNode,
- }, parseResults[0].Tree)
- require.NotNil(t, createTableNode, "Failed to extract CREATE TABLE AST node")
-
- // Create a mock chunk
- chunk := &schema.SDLChunk{
- Identifier: "public.test",
- ASTNode: createTableNode,
- }
-
- // Apply column changes
- err = applyTableChangesToChunk(chunk, tc.currentTable, tc.previousTable, nil)
- if tc.expectedSDL == "" {
- // For cases where we don't specify expected SDL, we just want to ensure no error
- assert.NoError(t, err, "applyTableChangesToChunk should not return error")
- } else {
- require.NoError(t, err, "applyTableChangesToChunk failed")
-
- // Get the modified SDL text by recreating the chunk text
- // Since we don't have a direct way to get text from AST, we'll validate the structure instead
- // This is a limitation - in a real scenario, we'd want to validate the actual SDL output
- assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil after modification")
- t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
- }
- })
- }
-}
-
-// TestColumnCommaHandlingEdgeCases tests specific edge cases for comma handling
-func TestColumnCommaHandlingEdgeCases(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- description string
- // We'll test the actual comma deletion logic directly
- testColumnIndex int // Which column to delete (0-based)
- expectedResult string
- }{
- {
- name: "Drop column before table constraint",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50),
- CONSTRAINT pk_test PRIMARY KEY (id)
-);`,
- description: "Should drop column and comma before constraint",
- testColumnIndex: 1, // Drop 'name'
- expectedResult: `CREATE TABLE test (
- id INTEGER NOT NULL,
- CONSTRAINT pk_test PRIMARY KEY (id)
-);`,
- },
- {
- name: "Drop column before multiple constraints",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50),
- email VARCHAR(100),
- CONSTRAINT pk_test PRIMARY KEY (id),
- CONSTRAINT uk_email UNIQUE (email)
-);`,
- description: "Should handle comma correctly with multiple constraints",
- testColumnIndex: 2, // Drop 'email'
- expectedResult: `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50),
- CONSTRAINT pk_test PRIMARY KEY (id),
- CONSTRAINT uk_email UNIQUE (email)
-);`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the SDL
- parseResults, err := pgparser.ParsePostgreSQL(tc.originalSDL)
- require.NoError(t, err, "Failed to parse SDL")
- require.Len(t, parseResults, 1, "Should parse single statement")
-
- var createTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createTableNode,
- }, parseResults[0].Tree)
- require.NotNil(t, createTableNode, "Failed to extract CREATE TABLE AST")
-
- // Extract columns
- columnDefs := extractColumnDefinitionsWithAST(createTableNode)
- require.Greater(t, len(columnDefs.Order), tc.testColumnIndex,
- "Test column index out of range")
-
- columnName := columnDefs.Order[tc.testColumnIndex]
- columnDef := columnDefs.Map[columnName]
-
- // Get the rewriter
- tokenStream := parseResults[0].Tokens
- rewriter := antlr.NewTokenStreamRewriter(tokenStream)
-
- // Test the deleteColumnFromAST function directly
- err = deleteColumnFromAST(rewriter, columnDef.ASTNode, createTableNode)
- assert.NoError(t, err, "deleteColumnFromAST should not return error")
-
- // Get the result
- result := rewriter.GetTextDefault()
-
- // For now, just ensure the operation completed without error
- // In a full implementation, we'd want to compare with expectedResult
- assert.NotEmpty(t, result, "Result should not be empty")
- t.Logf("Test case '%s' result:\n%s", tc.name, result)
- })
- }
-}
-
-// TestColumnRewriteWithCollation tests column operations with collation
-func TestColumnRewriteWithCollation(t *testing.T) {
- originalSDL := `CREATE TABLE test (
- id INTEGER NOT NULL,
- name VARCHAR(50) COLLATE "C"
-);`
-
- currentTable := &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true, Collation: "en_US.UTF-8"},
- },
- }
-
- previousTable := &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(50)", Nullable: true, Collation: "C"},
- },
- }
-
- // Parse and test
- parseResults, err := pgparser.ParsePostgreSQL(originalSDL)
- require.NoError(t, err)
- require.Len(t, parseResults, 1, "Should parse single statement")
-
- var createTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createTableNode,
- }, parseResults[0].Tree)
- require.NotNil(t, createTableNode)
-
- chunk := &schema.SDLChunk{
- Identifier: "public.test",
- ASTNode: createTableNode,
- }
-
- err = applyTableChangesToChunk(chunk, currentTable, previousTable, nil)
- assert.NoError(t, err, "Should handle collation changes without error")
-}
-
-// TestGenerateColumnSDLFunction tests the generateColumnSDL function directly
-func TestGenerateColumnSDLFunction(t *testing.T) {
- testCases := []struct {
- name string
- column *storepb.ColumnMetadata
- expected string
- }{
- {
- name: "Simple column",
- column: &storepb.ColumnMetadata{
- Name: "id",
- Type: "INTEGER",
- Nullable: false,
- },
- expected: `"id" INTEGER NOT NULL`,
- },
- {
- name: "Column with default",
- column: &storepb.ColumnMetadata{
- Name: "name",
- Type: "VARCHAR(50)",
- Nullable: true,
- Default: "'unknown'",
- },
- expected: `"name" VARCHAR(50) DEFAULT 'unknown'`,
- },
- {
- name: "Column with all attributes",
- column: &storepb.ColumnMetadata{
- Name: "title",
- Type: "TEXT",
- Nullable: false,
- Default: "'default title'",
- Collation: "en_US.UTF-8",
- },
- expected: `"title" TEXT DEFAULT 'default title' NOT NULL COLLATE "en_US.UTF-8"`,
- },
- {
- name: "Nil column",
- column: nil,
- expected: "",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := generateColumnSDL(tc.column, "test_table", nil)
- assert.Equal(t, tc.expected, result)
- })
- }
-}
diff --git a/backend/plugin/schema/pg/column_sdl_diff_test.go b/backend/plugin/schema/pg/column_sdl_diff_test.go
index 2b1a290a03..ac74ac8482 100644
--- a/backend/plugin/schema/pg/column_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/column_sdl_diff_test.go
@@ -427,7 +427,7 @@ func TestColumnSDLDiff(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Call GetSDLDiff
- diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil)
require.NoError(t, err, "GetSDLDiff should not return error")
// Validate table changes count
diff --git a/backend/plugin/schema/pg/comment_migration_test.go b/backend/plugin/schema/pg/comment_migration_test.go
index b2e4c1da73..1c01750dae 100644
--- a/backend/plugin/schema/pg/comment_migration_test.go
+++ b/backend/plugin/schema/pg/comment_migration_test.go
@@ -79,7 +79,7 @@ COMMENT ON TABLE "public"."users" IS 'User information table';
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -163,7 +163,7 @@ COMMENT ON COLUMN "public"."users"."name" IS 'User full name';
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -201,7 +201,7 @@ CREATE TABLE "public"."users" (
CREATE VIEW "public"."active_users" AS SELECT * FROM users;
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -223,7 +223,7 @@ COMMENT ON SEQUENCE "public"."user_id_seq" IS 'Sequence for user IDs';
CREATE SEQUENCE "public"."user_id_seq" AS integer START WITH 1 INCREMENT BY 1;
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -257,7 +257,7 @@ END;
$$;
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -280,7 +280,7 @@ COMMENT ON SCHEMA "app" IS 'Application schema';
CREATE SCHEMA "app";
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -341,7 +341,7 @@ comment';
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -372,7 +372,7 @@ CREATE TABLE "public"."users" (
COMMENT ON TABLE "public"."users" IS 'Old comment';
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Should have no table changes
@@ -410,7 +410,7 @@ CREATE TABLE "public"."users" (
COMMENT ON TABLE "public"."users" IS 'Basic user table';
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Should have table change
@@ -445,7 +445,7 @@ COMMENT ON FUNCTION "public"."calculate_tax"(numeric) IS 'Calculate 10% tax';
previousSDL := ``
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -540,7 +540,7 @@ CREATE TABLE "public"."test_r_table" (
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -600,20 +600,6 @@ COMMENT ON VIEW "public"."test_view" IS 'A view that combines test_table and tes
// Create mock schemas with view metadata
// Previous schema: no views
- previousSchema := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- },
- },
- },
- []byte{},
- &storepb.DatabaseConfig{},
- storepb.Engine_POSTGRES,
- false,
- )
// Current schema: includes view with comment
currentSchema := model.NewDatabaseMetadata(
@@ -646,7 +632,7 @@ JOIN
false,
)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -682,7 +668,7 @@ CREATE TABLE "public"."products" (
);
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -709,7 +695,7 @@ COMMENT ON TABLE "public"."users" IS 'User information table';
`
previousSDL := ``
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -741,7 +727,7 @@ CREATE TABLE "public"."users" (
);
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -776,7 +762,7 @@ CREATE TABLE "public"."users" (
);
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -816,7 +802,7 @@ CREATE TABLE "public"."users" (
COMMENT ON COLUMN "public"."users"."name" IS 'User name';
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -896,7 +882,7 @@ COMMENT ON SEQUENCE "public"."product_id_seq" IS 'Product ID sequence';
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -935,40 +921,6 @@ COMMENT ON INDEX "public"."idx_products_name" IS 'Index for product name lookup'
`
// Previous schema: table with columns but no indexes
- previousSchema := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- },
- {
- Name: "name",
- Type: "text",
- },
- {
- Name: "price",
- Type: "numeric",
- },
- },
- },
- },
- },
- },
- },
- []byte{},
- &storepb.DatabaseConfig{},
- storepb.Engine_POSTGRES,
- false,
- )
// Current schema: includes index with comment
currentSchema := model.NewDatabaseMetadata(
@@ -1014,7 +966,7 @@ COMMENT ON INDEX "public"."idx_products_name" IS 'Index for product name lookup'
false,
)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
@@ -1052,36 +1004,6 @@ COMMENT ON SEQUENCE "public"."product_id_seq" IS 'Product ID sequence';
`
// Previous schema: table but no sequences
- previousSchema := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- },
- {
- Name: "name",
- Type: "text",
- },
- },
- },
- },
- },
- },
- },
- []byte{},
- &storepb.DatabaseConfig{},
- storepb.Engine_POSTGRES,
- false,
- )
// Current schema: table and sequence with comment
currentSchema := model.NewDatabaseMetadata(
@@ -1124,7 +1046,7 @@ COMMENT ON SEQUENCE "public"."product_id_seq" IS 'Product ID sequence';
false,
)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
migrationSQL, err := generateMigration(diff)
diff --git a/backend/plugin/schema/pg/commented_enum_test.go b/backend/plugin/schema/pg/commented_enum_test.go
index 4dea632e5c..730630c393 100644
--- a/backend/plugin/schema/pg/commented_enum_test.go
+++ b/backend/plugin/schema/pg/commented_enum_test.go
@@ -131,7 +131,7 @@ COMMENT ON TYPE "public"."user_role_enum" IS 'User role types';
previousSDL := ""
currentSDL := fileContent
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err, "GetSDLDiff should not fail with commented SQL: %v", err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/constraint_rewrite_test.go b/backend/plugin/schema/pg/constraint_rewrite_test.go
deleted file mode 100644
index 4dafb57649..0000000000
--- a/backend/plugin/schema/pg/constraint_rewrite_test.go
+++ /dev/null
@@ -1,773 +0,0 @@
-package pg
-
-import (
- "testing"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/postgresql"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
- "github.com/bytebase/bytebase/backend/plugin/schema"
-)
-
-// TestConstraintRewriteOperations tests the ANTLR TokenStreamRewriter functionality
-// for constraint operations including add, modify, delete with various edge cases
-func TestConstraintRewriteOperations(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- currentTable *storepb.TableMetadata
- previousTable *storepb.TableMetadata
- expectedSDL string
- description string
- }{
- // Single Check Constraint Add Tests
- {
- name: "Add check constraint to table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- age INTEGER
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "age", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{
- {Name: "chk_age_positive", Expression: "(age > 0)"},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "age", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{},
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "age" INTEGER,
- CONSTRAINT "chk_age_positive" CHECK (age > 0)
-);`,
- description: "Should add check constraint to existing table",
- },
-
- // Check Constraint Drop Tests
- {
- name: "Drop check constraint from table",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- age INTEGER,
- CONSTRAINT chk_age_positive CHECK (age > 0)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "age", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{},
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "age", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{
- {Name: "chk_age_positive", Expression: "(age > 0)"},
- },
- },
- expectedSDL: `CREATE TABLE test (
- "id" INTEGER NOT NULL,
- "age" INTEGER
-);`,
- description: "Should drop check constraint from table",
- },
-
- // Foreign Key Constraint Add Tests
- {
- name: "Add foreign key constraint to table",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- customer_id INTEGER
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "customer_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{
- {
- Name: "fk_customer",
- Columns: []string{"customer_id"},
- ReferencedSchema: "public",
- ReferencedTable: "customers",
- ReferencedColumns: []string{"id"},
- OnDelete: "CASCADE",
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "customer_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{},
- },
- expectedSDL: `CREATE TABLE orders (
- "id" INTEGER NOT NULL,
- "customer_id" INTEGER,
- CONSTRAINT "fk_customer" FOREIGN KEY ("customer_id") REFERENCES "customers" ("id") ON DELETE CASCADE
-);`,
- description: "Should add foreign key constraint to existing table",
- },
-
- // Complex Multi-Operation Tests
- {
- name: "Add check constraint and foreign key constraint",
- originalSDL: `CREATE TABLE products (
- id INTEGER NOT NULL,
- name VARCHAR(100),
- price DECIMAL,
- category_id INTEGER
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(100)", Nullable: true},
- {Name: "price", Type: "DECIMAL", Nullable: true},
- {Name: "category_id", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{
- {Name: "chk_price_positive", Expression: "(price > 0)"},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{
- {
- Name: "fk_category",
- Columns: []string{"category_id"},
- ReferencedSchema: "public",
- ReferencedTable: "categories",
- ReferencedColumns: []string{"id"},
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(100)", Nullable: true},
- {Name: "price", Type: "DECIMAL", Nullable: true},
- {Name: "category_id", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{},
- ForeignKeys: []*storepb.ForeignKeyMetadata{},
- },
- expectedSDL: `CREATE TABLE products (
- "id" INTEGER NOT NULL,
- "name" VARCHAR(100),
- "price" DECIMAL,
- "category_id" INTEGER,
- CONSTRAINT "chk_price_positive" CHECK (price > 0),
- CONSTRAINT "fk_category" FOREIGN KEY ("category_id") REFERENCES "categories" ("id")
-);`,
- description: "Should add both check and foreign key constraints",
- },
-
- // Primary Key Constraint Tests
- {
- name: "Add primary key constraint to table",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- order_number VARCHAR(50)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "order_number", Type: "VARCHAR(50)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_orders",
- Primary: true,
- Expressions: []string{"id"},
- IsConstraint: true,
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "order_number", Type: "VARCHAR(50)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{},
- },
- expectedSDL: `CREATE TABLE orders (
- "id" INTEGER NOT NULL,
- "order_number" VARCHAR(50),
- CONSTRAINT "pk_orders" PRIMARY KEY (id)
-);`,
- description: "Should add primary key constraint to existing table",
- },
-
- // Unique Constraint Tests
- {
- name: "Add unique constraint to table",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "uk_users_email",
- Unique: true,
- Expressions: []string{"email"},
- IsConstraint: true,
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{},
- },
- expectedSDL: `CREATE TABLE users (
- "id" INTEGER NOT NULL,
- "email" VARCHAR(255),
- CONSTRAINT "uk_users_email" UNIQUE (email)
-);`,
- description: "Should add unique constraint to existing table",
- },
-
- // Combined Constraint Tests
- {
- name: "Add primary key and unique constraints together",
- originalSDL: `CREATE TABLE customers (
- id INTEGER NOT NULL,
- email VARCHAR(255),
- phone VARCHAR(20)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "customers",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- {Name: "phone", Type: "VARCHAR(20)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_customers",
- Primary: true,
- Expressions: []string{"id"},
- IsConstraint: true,
- },
- {
- Name: "uk_customers_email",
- Unique: true,
- Expressions: []string{"email"},
- IsConstraint: true,
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "customers",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- {Name: "phone", Type: "VARCHAR(20)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{},
- },
- expectedSDL: `CREATE TABLE customers (
- "id" INTEGER NOT NULL,
- "email" VARCHAR(255),
- "phone" VARCHAR(20),
- CONSTRAINT "pk_customers" PRIMARY KEY (id),
- CONSTRAINT "uk_customers_email" UNIQUE (email)
-);`,
- description: "Should add both primary key and unique constraints",
- },
-
- // Test that FK always includes schema name (even for public schema)
- {
- name: "Add foreign key constraint with public schema reference",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- customer_id INTEGER
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "customer_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{
- {
- Name: "fk_customer_public",
- Columns: []string{"customer_id"},
- ReferencedSchema: "public",
- ReferencedTable: "customers",
- ReferencedColumns: []string{"id"},
- OnDelete: "CASCADE",
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "customer_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{},
- },
- expectedSDL: `CREATE TABLE orders (
- "id" INTEGER NOT NULL,
- "customer_id" INTEGER,
- CONSTRAINT "fk_customer_public" FOREIGN KEY ("customer_id") REFERENCES "public"."customers" ("id") ON DELETE CASCADE
-);`,
- description: "Should always include schema name in FK references (even for public schema)",
- },
-
- // Drop Constraint Tests
- {
- name: "Drop primary key constraint from table",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255),
- CONSTRAINT pk_users PRIMARY KEY (id)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{},
- },
- previousTable: &storepb.TableMetadata{
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_users",
- Primary: true,
- Expressions: []string{"id"},
- IsConstraint: true,
- },
- },
- },
- expectedSDL: `CREATE TABLE users (
- "id" INTEGER NOT NULL,
- "email" VARCHAR(255)
-);`,
- description: "Should drop primary key constraint from table",
- },
-
- {
- name: "Drop unique constraint from table",
- originalSDL: `CREATE TABLE products (
- id INTEGER NOT NULL,
- code VARCHAR(50),
- CONSTRAINT uk_products_code UNIQUE (code)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "code", Type: "VARCHAR(50)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{},
- },
- previousTable: &storepb.TableMetadata{
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "code", Type: "VARCHAR(50)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "uk_products_code",
- Unique: true,
- Expressions: []string{"code"},
- IsConstraint: true,
- },
- },
- },
- expectedSDL: `CREATE TABLE products (
- "id" INTEGER NOT NULL,
- "code" VARCHAR(50)
-);`,
- description: "Should drop unique constraint from table",
- },
-
- {
- name: "Drop foreign key constraint from table",
- originalSDL: `CREATE TABLE order_items (
- id INTEGER NOT NULL,
- order_id INTEGER,
- CONSTRAINT fk_order_items_order FOREIGN KEY (order_id) REFERENCES "public"."orders" (id)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "order_items",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "order_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{},
- },
- previousTable: &storepb.TableMetadata{
- Name: "order_items",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "order_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{
- {
- Name: "fk_order_items_order",
- Columns: []string{"order_id"},
- ReferencedSchema: "public",
- ReferencedTable: "orders",
- ReferencedColumns: []string{"id"},
- },
- },
- },
- expectedSDL: `CREATE TABLE order_items (
- "id" INTEGER NOT NULL,
- "order_id" INTEGER
-);`,
- description: "Should drop foreign key constraint from table",
- },
-
- // Modify Constraint Tests
- {
- name: "Modify primary key constraint (change columns)",
- originalSDL: `CREATE TABLE composite_pk (
- id INTEGER NOT NULL,
- tenant_id INTEGER NOT NULL,
- name VARCHAR(255),
- CONSTRAINT pk_composite_old PRIMARY KEY (id)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "composite_pk",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "tenant_id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(255)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_composite_new",
- Primary: true,
- Expressions: []string{"id", "tenant_id"},
- IsConstraint: true,
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "composite_pk",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "tenant_id", Type: "INTEGER", Nullable: false},
- {Name: "name", Type: "VARCHAR(255)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_composite_old",
- Primary: true,
- Expressions: []string{"id"},
- IsConstraint: true,
- },
- },
- },
- expectedSDL: `CREATE TABLE composite_pk (
- "id" INTEGER NOT NULL,
- "tenant_id" INTEGER NOT NULL,
- "name" VARCHAR(255),
- CONSTRAINT "pk_composite_new" PRIMARY KEY (id, tenant_id)
-);`,
- description: "Should modify primary key constraint to include multiple columns",
- },
-
- {
- name: "Modify unique constraint (change columns)",
- originalSDL: `CREATE TABLE users_unique (
- id INTEGER NOT NULL,
- email VARCHAR(255),
- username VARCHAR(100),
- CONSTRAINT uk_users_email_only UNIQUE (email)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "users_unique",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- {Name: "username", Type: "VARCHAR(100)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "uk_users_email_username",
- Unique: true,
- Expressions: []string{"email", "username"},
- IsConstraint: true,
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "users_unique",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "email", Type: "VARCHAR(255)", Nullable: true},
- {Name: "username", Type: "VARCHAR(100)", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "uk_users_email_only",
- Unique: true,
- Expressions: []string{"email"},
- IsConstraint: true,
- },
- },
- },
- expectedSDL: `CREATE TABLE users_unique (
- "id" INTEGER NOT NULL,
- "email" VARCHAR(255),
- "username" VARCHAR(100),
- CONSTRAINT "uk_users_email_username" UNIQUE (email, username)
-);`,
- description: "Should modify unique constraint to include multiple columns",
- },
-
- {
- name: "Modify foreign key constraint (change referenced table)",
- originalSDL: `CREATE TABLE comments (
- id INTEGER NOT NULL,
- author_id INTEGER,
- CONSTRAINT fk_comments_author FOREIGN KEY (author_id) REFERENCES "public"."users" (id)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "comments",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "author_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{
- {
- Name: "fk_comments_author",
- Columns: []string{"author_id"},
- ReferencedSchema: "public",
- ReferencedTable: "authors",
- ReferencedColumns: []string{"id"},
- OnDelete: "SET NULL",
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "comments",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "author_id", Type: "INTEGER", Nullable: true},
- },
- ForeignKeys: []*storepb.ForeignKeyMetadata{
- {
- Name: "fk_comments_author",
- Columns: []string{"author_id"},
- ReferencedSchema: "public",
- ReferencedTable: "users",
- ReferencedColumns: []string{"id"},
- },
- },
- },
- expectedSDL: `CREATE TABLE comments (
- "id" INTEGER NOT NULL,
- "author_id" INTEGER,
- CONSTRAINT "fk_comments_author" FOREIGN KEY ("author_id") REFERENCES "public"."authors" ("id") ON DELETE SET NULL
-);`,
- description: "Should modify foreign key constraint to reference different table and add ON DELETE",
- },
-
- // Complex Mixed Operations
- {
- name: "Replace primary key and add unique constraint",
- originalSDL: `CREATE TABLE logs (
- id INTEGER NOT NULL,
- session_id VARCHAR(255) NOT NULL,
- timestamp TIMESTAMP,
- CONSTRAINT pk_logs_id PRIMARY KEY (id)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "logs",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "session_id", Type: "VARCHAR(255)", Nullable: false},
- {Name: "timestamp", Type: "TIMESTAMP", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_logs_session_timestamp",
- Primary: true,
- Expressions: []string{"session_id", "timestamp"},
- IsConstraint: true,
- },
- {
- Name: "uk_logs_id",
- Unique: true,
- Expressions: []string{"id"},
- IsConstraint: true,
- },
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "logs",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "session_id", Type: "VARCHAR(255)", Nullable: false},
- {Name: "timestamp", Type: "TIMESTAMP", Nullable: true},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "pk_logs_id",
- Primary: true,
- Expressions: []string{"id"},
- IsConstraint: true,
- },
- },
- },
- expectedSDL: `CREATE TABLE logs (
- "id" INTEGER NOT NULL,
- "session_id" VARCHAR(255) NOT NULL,
- "timestamp" TIMESTAMP,
- CONSTRAINT "pk_logs_session_timestamp" PRIMARY KEY (session_id, timestamp),
- CONSTRAINT "uk_logs_id" UNIQUE (id)
-);`,
- description: "Should replace primary key constraint and add unique constraint",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the original SDL to create an AST chunk
- parseResults, err := pgparser.ParsePostgreSQL(tc.originalSDL)
- require.NoError(t, err, "Failed to parse original SDL")
- require.Len(t, parseResults, 1, "Should parse single statement")
-
- // Extract the CREATE TABLE AST node
- var createTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createTableNode,
- }, parseResults[0].Tree)
- require.NotNil(t, createTableNode, "Failed to extract CREATE TABLE AST node")
-
- // Create a mock chunk
- chunk := &schema.SDLChunk{
- Identifier: "public." + tc.currentTable.Name,
- ASTNode: createTableNode,
- }
-
- // Apply constraint changes
- err = applyTableChangesToChunk(chunk, tc.currentTable, tc.previousTable, nil)
- if tc.expectedSDL == "" {
- // For cases where we don't specify expected SDL, we just want to ensure no error
- assert.NoError(t, err, "applyTableChangesToChunk should not return error")
- } else {
- require.NoError(t, err, "applyTableChangesToChunk failed")
-
- // Get the modified SDL text by recreating the chunk text
- // Since we don't have a direct way to get text from AST, we'll validate the structure instead
- // This is a limitation - in a real scenario, we'd want to validate the actual SDL output
- assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil after modification")
- t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
- }
- })
- }
-}
-
-// TestConstraintModificationOperations tests constraint modification operations
-func TestConstraintModificationOperations(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- currentTable *storepb.TableMetadata
- previousTable *storepb.TableMetadata
- description string
- }{
- {
- name: "Modify check constraint expression",
- originalSDL: `CREATE TABLE test (
- id INTEGER NOT NULL,
- age INTEGER,
- CONSTRAINT chk_age_positive CHECK (age > 0)
-);`,
- currentTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "age", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{
- {Name: "chk_age_positive", Expression: "(age >= 0)"},
- },
- },
- previousTable: &storepb.TableMetadata{
- Name: "test",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "INTEGER", Nullable: false},
- {Name: "age", Type: "INTEGER", Nullable: true},
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{
- {Name: "chk_age_positive", Expression: "(age > 0)"},
- },
- },
- description: "Should modify check constraint expression",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the original SDL to create an AST chunk
- parseResults, err := pgparser.ParsePostgreSQL(tc.originalSDL)
- require.NoError(t, err, "Failed to parse original SDL")
- require.Len(t, parseResults, 1, "Should parse single statement")
-
- // Extract the CREATE TABLE AST node
- var createTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createTableNode,
- }, parseResults[0].Tree)
- require.NotNil(t, createTableNode, "Failed to extract CREATE TABLE AST node")
-
- // Create a mock chunk
- chunk := &schema.SDLChunk{
- Identifier: "public." + tc.currentTable.Name,
- ASTNode: createTableNode,
- }
-
- // Apply constraint changes
- err = applyTableChangesToChunk(chunk, tc.currentTable, tc.previousTable, nil)
- assert.NoError(t, err, "applyTableChangesToChunk should not return error")
- assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil after modification")
- t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
- })
- }
-}
diff --git a/backend/plugin/schema/pg/enum_type_test.go b/backend/plugin/schema/pg/enum_type_test.go
index c2a94be025..19ea7365bd 100644
--- a/backend/plugin/schema/pg/enum_type_test.go
+++ b/backend/plugin/schema/pg/enum_type_test.go
@@ -270,7 +270,7 @@ CREATE TABLE "public"."users" (
);`
// Get SDL diff (simulates bb rollout behavior)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -324,7 +324,7 @@ CREATE TABLE "public"."users" (
);`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -363,7 +363,7 @@ CREATE TABLE "public"."users" (
);`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -664,7 +664,7 @@ func TestEnumTypeCommentChanges(t *testing.T) {
COMMENT ON TYPE "public"."status_type" IS 'User status enum';`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/exclude_index_test.go b/backend/plugin/schema/pg/exclude_index_test.go
index 4de809046d..e2e157cbb6 100644
--- a/backend/plugin/schema/pg/exclude_index_test.go
+++ b/backend/plugin/schema/pg/exclude_index_test.go
@@ -42,20 +42,14 @@ CREATE INDEX idx_employee_shifts_time ON "public"."employee_shifts" USING gist (
CREATE INDEX idx_employee_shifts_type ON "public"."employee_shifts" (shift_type);
`
- previousDBMetadata := &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{},
- }
-
currentDBMetadata := &storepb.DatabaseSchemaMetadata{
Name: "testdb",
Schemas: []*storepb.SchemaMetadata{},
}
- previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -152,15 +146,9 @@ CREATE TABLE "public"."meetings" (
},
}
- previousDBMetadata := &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{},
- }
-
- previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
ddl, err := generateMigration(diff)
@@ -205,20 +193,14 @@ CREATE INDEX idx_order_summary_month ON "public"."order_summary" (order_month);
CREATE UNIQUE INDEX idx_order_summary_unique ON "public"."order_summary" (customer_id, order_month);
`
- previousDBMetadata := &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{},
- }
-
currentDBMetadata := &storepb.DatabaseSchemaMetadata{
Name: "testdb",
Schemas: []*storepb.SchemaMetadata{},
}
- previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -282,20 +264,14 @@ CREATE TABLE "public"."orders" (
CREATE INDEX idx_orders_customer ON "public"."orders" (customer_id);
`
- previousDBMetadata := &storepb.DatabaseSchemaMetadata{
- Name: "testdb",
- Schemas: []*storepb.SchemaMetadata{},
- }
-
currentDBMetadata := &storepb.DatabaseSchemaMetadata{
Name: "testdb",
Schemas: []*storepb.SchemaMetadata{},
}
- previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)
- diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/extension_test.go b/backend/plugin/schema/pg/extension_test.go
index df71168bb7..a287b710fe 100644
--- a/backend/plugin/schema/pg/extension_test.go
+++ b/backend/plugin/schema/pg/extension_test.go
@@ -290,7 +290,7 @@ CREATE TABLE "public"."users" (
);`
// Get SDL diff (simulates bb rollout initialization)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -338,7 +338,7 @@ CREATE TABLE "public"."users" (
);`
// Get SDL diff (simulates bb rollout behavior)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -385,7 +385,7 @@ CREATE TABLE "public"."users" (
);`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -416,7 +416,7 @@ CREATE TABLE "public"."users" (
currentSDL := `CREATE EXTENSION IF NOT EXISTS "uuid-ossp" VERSION '1.1';`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -455,7 +455,7 @@ func TestExtensionCommentChanges(t *testing.T) {
COMMENT ON EXTENSION "uuid-ossp" IS 'UUID generation functions';`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -515,7 +515,7 @@ CREATE TABLE "public"."email_addresses" (
);`
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -630,7 +630,7 @@ func TestExtensionRoundtripNoDiff(t *testing.T) {
// STEP 3: Compare user SDL (previous) vs dumped SDL (current)
// This is what happens in bb rollout when user doesn't change anything
// Pass currentSchema so usability check can work
- diff, err := GetSDLDiff(dumpedSDL, userSDL, currentSchema, nil)
+ diff, err := GetSDLDiff(dumpedSDL, userSDL, currentSchema)
require.NoError(t, err)
// CRITICAL: There should be NO extension changes!
@@ -672,7 +672,7 @@ func TestExtensionRoundtripNoDiff(t *testing.T) {
dumpedSDL, err := getSDLFormat(metadata)
require.NoError(t, err)
- diff, err := GetSDLDiff(dumpedSDL, userSDL, currentSchema, nil)
+ diff, err := GetSDLDiff(dumpedSDL, userSDL, currentSchema)
require.NoError(t, err)
require.Equal(t, 0, len(diff.ExtensionChanges), "No changes for extension with version")
@@ -699,7 +699,7 @@ COMMENT ON EXTENSION "citext" IS 'Case-insensitive text type';`
dumpedSDL, err := getSDLFormat(metadata)
require.NoError(t, err)
- diff, err := GetSDLDiff(dumpedSDL, userSDL, currentSchema, nil)
+ diff, err := GetSDLDiff(dumpedSDL, userSDL, currentSchema)
require.NoError(t, err)
require.Equal(t, 0, len(diff.ExtensionChanges), "No changes for extension with comment")
diff --git a/backend/plugin/schema/pg/function_migration_integration_test.go b/backend/plugin/schema/pg/function_migration_integration_test.go
index a9760c46cb..508dac5e79 100644
--- a/backend/plugin/schema/pg/function_migration_integration_test.go
+++ b/backend/plugin/schema/pg/function_migration_integration_test.go
@@ -204,7 +204,7 @@ func TestFunctionSDLDiffAndMigrationIntegration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Step 1: Get SDL diff using AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -284,7 +284,7 @@ func TestFunctionMigrationASTOnlyModeValidation(t *testing.T) {
`
// Get diff without metadata extraction
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -332,7 +332,7 @@ func TestOverloadedFunctionSignatureHandling(t *testing.T) {
`
// Get diff without metadata extraction (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -424,7 +424,7 @@ func TestProcedureDropMigration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -599,7 +599,7 @@ func TestDropProcedureShouldNotAffectFunctionComment(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/function_rewrite_test.go b/backend/plugin/schema/pg/function_rewrite_test.go
deleted file mode 100644
index 76235487b5..0000000000
--- a/backend/plugin/schema/pg/function_rewrite_test.go
+++ /dev/null
@@ -1,526 +0,0 @@
-package pg
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- parser "github.com/bytebase/parser/postgresql"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/schema"
-)
-
-// TestFunctionRewriteOperations tests the ANTLR TokenStreamRewriter functionality
-// for standalone CREATE FUNCTION operations including add, modify, delete
-func TestFunctionRewriteOperations(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- currentFunctions []*storepb.FunctionMetadata
- previousFunctions []*storepb.FunctionMetadata
- expectedFunctionCount int
- description string
- }{
- {
- name: "Add new standalone function",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);`,
- currentFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_user_count",
- Definition: `CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- previousFunctions: []*storepb.FunctionMetadata{},
- expectedFunctionCount: 1,
- description: "Should add new standalone function to chunks",
- },
- {
- name: "Add function with complex signature",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- amount DECIMAL(10,2) NOT NULL
-);`,
- currentFunctions: []*storepb.FunctionMetadata{
- {
- Name: "calculate_total",
- Definition: `CREATE OR REPLACE FUNCTION calculate_total(
- p_start_date DATE,
- p_end_date DATE,
- p_discount_rate DECIMAL DEFAULT 0.0
-)
-RETURNS DECIMAL(10,2) AS $$
-BEGIN
- RETURN (
- SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)
- FROM orders
- WHERE created_at::DATE BETWEEN p_start_date AND p_end_date
- );
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- previousFunctions: []*storepb.FunctionMetadata{},
- expectedFunctionCount: 1,
- description: "Should add new function with complex signature to chunks",
- },
- {
- name: "Drop standalone function",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);
-
-CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql;`,
- currentFunctions: []*storepb.FunctionMetadata{},
- previousFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_user_count",
- Definition: `CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- expectedFunctionCount: 0,
- description: "Should remove standalone function from chunks",
- },
- {
- name: "Modify function (change definition)",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL,
- active BOOLEAN DEFAULT true
-);
-
-CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql;`,
- currentFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_user_count",
- Definition: `CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users WHERE active = true);
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- previousFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_user_count",
- Definition: `CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- expectedFunctionCount: 1,
- description: "Should modify existing function when definition changes",
- },
- {
- name: "Multiple function operations",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- customer_id INTEGER,
- total DECIMAL(10,2),
- status VARCHAR(20)
-);
-
-CREATE OR REPLACE FUNCTION get_order_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM orders);
-END;
-$$ LANGUAGE plpgsql;`,
- currentFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_total_amount",
- Definition: `CREATE OR REPLACE FUNCTION get_total_amount()
-RETURNS DECIMAL(10,2) AS $$
-BEGIN
- RETURN (SELECT SUM(total) FROM orders);
-END;
-$$ LANGUAGE plpgsql`,
- },
- {
- Name: "get_active_orders",
- Definition: `CREATE OR REPLACE FUNCTION get_active_orders()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM orders WHERE status = 'active');
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- previousFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_order_count",
- Definition: `CREATE OR REPLACE FUNCTION get_order_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM orders);
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- expectedFunctionCount: 2,
- description: "Should handle multiple function operations (drop old, add new)",
- },
- {
- name: "Schema-qualified function names",
- originalSDL: `CREATE SCHEMA test_schema;
-CREATE TABLE test_schema.products (
- id INTEGER NOT NULL,
- name VARCHAR(255)
-);`,
- currentFunctions: []*storepb.FunctionMetadata{
- {
- Name: "get_product_count",
- Definition: `CREATE OR REPLACE FUNCTION test_schema.get_product_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM test_schema.products);
-END;
-$$ LANGUAGE plpgsql`,
- },
- },
- previousFunctions: []*storepb.FunctionMetadata{},
- expectedFunctionCount: 1,
- description: "Should handle schema-qualified function names",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the original SDL to create chunks
- chunks, err := ChunkSDLText(tc.originalSDL)
- require.NoError(t, err, "Failed to parse original SDL")
-
- // Create function maps for simulation
- currentFunctions := make(map[string]*storepb.FunctionMetadata)
- previousFunctions := make(map[string]*storepb.FunctionMetadata)
-
- for _, fn := range tc.currentFunctions {
- key := formatFunctionKey("public", fn)
- currentFunctions[key] = fn
- }
-
- for _, fn := range tc.previousFunctions {
- key := formatFunctionKey("public", fn)
- previousFunctions[key] = fn
- }
-
- // Apply function changes directly to test the core logic
- err = applyFunctionChangesInternal(chunks, currentFunctions, previousFunctions)
- require.NoError(t, err, "Failed to apply function changes")
-
- // Verify the expected number of functions
- assert.Len(t, chunks.Functions, tc.expectedFunctionCount,
- "Expected %d functions, got %d", tc.expectedFunctionCount, len(chunks.Functions))
-
- // Verify each current function is present
- for key, fn := range currentFunctions {
- chunk, exists := chunks.Functions[key]
- assert.True(t, exists, "Expected function %s not found in chunks", key)
- if exists {
- assert.NotNil(t, chunk.ASTNode, "Function chunk should have AST node")
- // Verify we can get text from the chunk using the proper extraction function
- if functionAST, ok := chunk.ASTNode.(*parser.CreatefunctionstmtContext); ok {
- text := extractFunctionTextFromAST(functionAST)
- assert.NotEmpty(t, text, "Function chunk should have non-empty text")
- assert.Contains(t, text, "CREATE", "Function text should contain CREATE")
- assert.Contains(t, text, "FUNCTION", "Function text should contain FUNCTION")
- assert.Contains(t, text, fn.Name, "Function text should contain function name")
- }
- }
- }
-
- // Verify previous functions that shouldn't exist are removed
- for key := range previousFunctions {
- if _, stillExists := currentFunctions[key]; !stillExists {
- _, exists := chunks.Functions[key]
- assert.False(t, exists, "Function %s should have been removed from chunks", key)
- }
- }
-
- t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
- })
- }
-}
-
-// applyFunctionChangesInternal is a test helper that directly applies function changes to chunks
-func applyFunctionChangesInternal(chunks *schema.SDLChunks, currentFunctions, previousFunctions map[string]*storepb.FunctionMetadata) error {
- if chunks == nil {
- return nil
- }
-
- // Process function additions: create new function chunks
- for functionKey, currentFunction := range currentFunctions {
- if _, exists := previousFunctions[functionKey]; !exists {
- // New function - create a chunk for it
- err := createFunctionChunk(chunks, currentFunction, functionKey)
- if err != nil {
- return err
- }
- }
- }
-
- // Process function modifications: update existing chunks
- for functionKey, currentFunction := range currentFunctions {
- if previousFunction, exists := previousFunctions[functionKey]; exists {
- // Function exists in both - check if it needs modification
- err := updateFunctionChunkIfNeeded(chunks, currentFunction, previousFunction, functionKey)
- if err != nil {
- return err
- }
- }
- }
-
- // Process function deletions: remove dropped function chunks
- for functionKey := range previousFunctions {
- if _, exists := currentFunctions[functionKey]; !exists {
- // Function was dropped - remove it from chunks
- deleteFunctionChunk(chunks, functionKey)
- }
- }
-
- return nil
-}
-
-// TestGenerateCreateFunctionSDL tests the SDL generation for CREATE FUNCTION statements
-func TestGenerateCreateFunctionSDL(t *testing.T) {
- testCases := []struct {
- name string
- function *storepb.FunctionMetadata
- expectedSDL string
- }{
- {
- name: "Simple function",
- function: &storepb.FunctionMetadata{
- Name: "get_user_count",
- Definition: `CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql`,
- },
- expectedSDL: `CREATE OR REPLACE FUNCTION get_user_count()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM users);
-END;
-$$ LANGUAGE plpgsql`,
- },
- {
- name: "Function with parameters",
- function: &storepb.FunctionMetadata{
- Name: "calculate_total",
- Definition: `CREATE OR REPLACE FUNCTION calculate_total(
- p_start_date DATE,
- p_end_date DATE,
- p_discount_rate DECIMAL DEFAULT 0.0
-)
-RETURNS DECIMAL(10,2) AS $$
-BEGIN
- RETURN (
- SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)
- FROM orders
- WHERE created_at::DATE BETWEEN p_start_date AND p_end_date
- );
-END;
-$$ LANGUAGE plpgsql`,
- },
- expectedSDL: `CREATE OR REPLACE FUNCTION calculate_total(
- p_start_date DATE,
- p_end_date DATE,
- p_discount_rate DECIMAL DEFAULT 0.0
-)
-RETURNS DECIMAL(10,2) AS $$
-BEGIN
- RETURN (
- SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)
- FROM orders
- WHERE created_at::DATE BETWEEN p_start_date AND p_end_date
- );
-END;
-$$ LANGUAGE plpgsql`,
- },
- {
- name: "Function with trailing semicolon",
- function: &storepb.FunctionMetadata{
- Name: "simple_func",
- Definition: `CREATE OR REPLACE FUNCTION simple_func()
-RETURNS TEXT AS $$
-BEGIN
- RETURN 'hello';
-END;
-$$ LANGUAGE plpgsql;`,
- },
- expectedSDL: `CREATE OR REPLACE FUNCTION simple_func()
-RETURNS TEXT AS $$
-BEGIN
- RETURN 'hello';
-END;
-$$ LANGUAGE plpgsql`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := generateCreateFunctionSDL(tc.function)
- assert.Equal(t, tc.expectedSDL, result)
- })
- }
-}
-
-// TestFunctionDefinitionsEqual tests the function comparison logic
-func TestFunctionDefinitionsEqual(t *testing.T) {
- testCases := []struct {
- name string
- function1 *storepb.FunctionMetadata
- function2 *storepb.FunctionMetadata
- expected bool
- }{
- {
- name: "Identical functions",
- function1: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- function2: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- expected: true,
- },
- {
- name: "Different names",
- function1: &storepb.FunctionMetadata{
- Name: "test_func1",
- Definition: `CREATE OR REPLACE FUNCTION test_func1()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- function2: &storepb.FunctionMetadata{
- Name: "test_func2",
- Definition: `CREATE OR REPLACE FUNCTION test_func2()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- expected: false,
- },
- {
- name: "Different definitions",
- function1: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- function2: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 2;
-END;
-$$ LANGUAGE plpgsql`,
- },
- expected: false,
- },
- {
- name: "Same definition with different trailing semicolons",
- function1: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- function2: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql;`,
- },
- expected: true,
- },
- {
- name: "Same definition with different whitespace",
- function1: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: `CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql`,
- },
- function2: &storepb.FunctionMetadata{
- Name: "test_func",
- Definition: ` CREATE OR REPLACE FUNCTION test_func()
-RETURNS INTEGER AS $$
-BEGIN
- RETURN 1;
-END;
-$$ LANGUAGE plpgsql `,
- },
- expected: true,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := functionDefinitionsEqual(tc.function1, tc.function2)
- assert.Equal(t, tc.expected, result)
- })
- }
-}
diff --git a/backend/plugin/schema/pg/function_sdl_diff_test.go b/backend/plugin/schema/pg/function_sdl_diff_test.go
index 9818185054..7af4fa29ab 100644
--- a/backend/plugin/schema/pg/function_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/function_sdl_diff_test.go
@@ -233,7 +233,7 @@ func TestFunctionSDLDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -521,7 +521,7 @@ $$;
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
// Count different action types
diff --git a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
index dfe2c4ff8f..90a1ad7b4f 100644
--- a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
+++ b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
@@ -2386,7 +2386,7 @@ CREATE TABLE table2 (
dbMetadata := model.NewDatabaseMetadata(currentSchema, nil, nil, storepb.Engine_POSTGRES, false)
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, dbMetadata, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, dbMetadata)
require.NoError(t, err)
// Generate migration SQL with topological sorting
@@ -2475,7 +2475,7 @@ SELECT id, info, created_at, updated_at FROM table_base;
dbMetadata := model.NewDatabaseMetadata(currentSchema, nil, nil, storepb.Engine_POSTGRES, false)
// Get SDL diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, dbMetadata, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, dbMetadata)
require.NoError(t, err)
// Generate migration SQL with topological sorting
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.go
index 090a7028f4..6c27a225a4 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -4,7 +4,6 @@ import (
"fmt"
"strings"
- "github.com/antlr4-go/antlr/v4"
"github.com/pkg/errors"
parser "github.com/bytebase/parser/postgresql"
@@ -20,7 +19,7 @@ func init() {
schema.RegisterGetSDLDiff(storepb.Engine_COCKROACHDB, GetSDLDiff)
}
-func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseMetadata) (*schema.MetadataDiff, error) {
+func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema *model.DatabaseMetadata) (*schema.MetadataDiff, error) {
generatedSDL, err := convertDatabaseSchemaToSDL(currentSchema)
if err != nil {
return nil, errors.Wrap(err, "failed to convert current schema to SDL format for initialization")
@@ -50,14 +49,6 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previ
return nil, errors.Wrap(err, "failed to chunk previous SDL text")
}
- // Check for drift scenario: when both schemas are provided, apply minimal changes to previousChunks
- if currentSchema != nil && previousSchema != nil {
- err = applyMinimalChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return nil, errors.Wrap(err, "failed to apply minimal changes to SDL chunks")
- }
- }
-
// Pre-compute SDL chunks from current database metadata for performance optimization
// This avoids repeated calls to convertDatabaseSchemaToSDL and ChunkSDLText during usability checks
currentDBSDLChunks, err := buildCurrentDatabaseSDLChunks(currentSchema)
@@ -80,7 +71,7 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previ
}
// Process table changes
- err = processTableChanges(currentChunks, previousChunks, currentSchema, previousSchema, currentDBSDLChunks, diff)
+ err = processTableChanges(currentChunks, previousChunks, currentSchema, currentDBSDLChunks, diff)
if err != nil {
return nil, errors.Wrap(err, "failed to process table changes")
}
@@ -125,820 +116,6 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previ
return diff, nil
}
-// applyMinimalChangesToChunks applies minimal changes to the previous SDL chunks based on schema differences
-// This implements the minimal change principle for drift scenarios by directly manipulating chunks
-func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get table differences between schemas
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Create maps for efficient table lookup using full schema.table identifier
- currentTables := make(map[string]*storepb.TableMetadata)
- previousTables := make(map[string]*storepb.TableMetadata)
-
- // Build current tables map with proper schema qualification
- for _, schema := range currentMetadata.Schemas {
- schemaName := schema.Name
- if schemaName == "" {
- schemaName = "public" // Default schema for PostgreSQL
- }
- for _, table := range schema.Tables {
- tableKey := schemaName + "." + table.Name
- currentTables[tableKey] = table
- }
- }
-
- // Build previous tables map with proper schema qualification
- for _, schema := range previousMetadata.Schemas {
- schemaName := schema.Name
- if schemaName == "" {
- schemaName = "public" // Default schema for PostgreSQL
- }
- for _, table := range schema.Tables {
- tableKey := schemaName + "." + table.Name
- previousTables[tableKey] = table
- }
- }
-
- // Build existing chunk keys mapping for table operations
- existingChunkKeys := make(map[string]string) // schema.table -> chunk key
- for chunkKey, chunk := range previousChunks.Tables {
- if chunk != nil {
- existingChunkKeys[chunk.Identifier] = chunkKey
- }
- }
-
- // Build sequences map: schema.table -> sequences for that table
- tableSequencesMap := make(map[string][]*storepb.SequenceMetadata)
- for _, schema := range currentMetadata.Schemas {
- schemaName := schema.Name
- if schemaName == "" {
- schemaName = "public"
- }
- for _, sequence := range schema.Sequences {
- if sequence.OwnerTable != "" {
- tableKey := schemaName + "." + sequence.OwnerTable
- tableSequencesMap[tableKey] = append(tableSequencesMap[tableKey], sequence)
- }
- }
- }
-
- // Process table additions: add new tables to chunks
- for tableKey, currentTable := range currentTables {
- if _, exists := previousTables[tableKey]; !exists {
- // Table was added - generate SDL for the new table and parse it to AST
- var buf strings.Builder
- schemaName, _ := parseIdentifier(tableKey)
- // Get sequences for this table
- tableSequences := tableSequencesMap[tableKey]
- err := writeCreateTableSDL(&buf, schemaName, currentTable, tableSequences)
- if err != nil {
- return errors.Wrapf(err, "failed to generate SDL for new table %s", tableKey)
- }
- tableSDL := buf.String()
-
- // Parse the generated SDL to create AST node
- parseResults, err := pgparser.ParsePostgreSQL(tableSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated SDL for new table %s", tableKey)
- }
-
- // Extract the CREATE TABLE AST node
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
- var createTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createTableNode,
- }, parseResult.Tree)
-
- if createTableNode == nil {
- return errors.Errorf("failed to extract CREATE TABLE AST node for new table %s", tableKey)
- }
-
- // Always use schema.table format for all table identifiers
- chunkKey := tableKey
-
- // Add the new table chunk with proper AST node
- previousChunks.Tables[chunkKey] = &schema.SDLChunk{
- Identifier: chunkKey,
- ASTNode: createTableNode,
- }
- }
- }
-
- // Process table modifications: apply column-level changes using ANTLR rewrite
- for tableKey, currentTable := range currentTables {
- if previousTable, exists := previousTables[tableKey]; exists {
- // Table exists in both schemas - check for column differences
- if existingKey, chunkExists := existingChunkKeys[tableKey]; chunkExists {
- if chunk := previousChunks.Tables[existingKey]; chunk != nil {
- // Get sequences for this table
- tableSequences := tableSequencesMap[tableKey]
- // Apply both column and constraint changes to the existing chunk using a single rewriter
- err := applyTableChangesToChunk(chunk, currentTable, previousTable, tableSequences)
- if err != nil {
- return errors.Wrapf(err, "failed to apply table changes to table %s", tableKey)
- }
- }
- }
- }
- }
-
- // Process table deletions: remove dropped tables from chunks
- for tableKey := range previousTables {
- if _, exists := currentTables[tableKey]; !exists {
- // Table was dropped - find the corresponding chunk key and remove it
- if existingKey, exists := existingChunkKeys[tableKey]; exists {
- delete(previousChunks.Tables, existingKey)
- }
- // If no mapping exists, the table was not in the original chunks,
- // so there's nothing to delete - this is the expected behavior
- }
- }
-
- // Process standalone index changes: apply minimal changes to index chunks
- err := applyStandaloneIndexChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply standalone index changes")
- }
-
- // Process function changes: apply minimal changes to function chunks
- err = applyFunctionChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply function changes")
- }
-
- // Process sequence changes: apply minimal changes to sequence chunks
- err = applySequenceChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply sequence changes")
- }
-
- // Process view changes: apply minimal changes to view chunks
- err = applyViewChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply view changes")
- }
-
- // Process materialized view changes: apply minimal changes to materialized view chunks
- err = applyMaterializedViewChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply materialized view changes")
- }
-
- // Process enum type changes: apply minimal changes to enum type chunks
- err = applyEnumTypeChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply enum type changes")
- }
-
- // Process extension changes: apply minimal changes to extension chunks
- // Extensions are database-level objects
- err = applyExtensionChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply extension changes")
- }
-
- // Process trigger changes: apply minimal changes to trigger chunks
- err = applyTriggerChangesToChunks(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply trigger changes")
- }
-
- // Process column comment changes: sync column comments based on metadata
- err = applyColumnCommentChanges(previousChunks, currentSchema, previousSchema)
- if err != nil {
- return errors.Wrap(err, "failed to apply column comment changes")
- }
-
- return nil
-}
-
-// applyTableChangesToChunk applies minimal column and constraint changes to an existing CREATE TABLE chunk
-// by working with the individual chunk's SQL text instead of the full script's tokenStream
-func applyTableChangesToChunk(chunk *schema.SDLChunk, currentTable, previousTable *storepb.TableMetadata, sequences []*storepb.SequenceMetadata) error {
- if chunk == nil || chunk.ASTNode == nil || currentTable == nil || previousTable == nil {
- return nil
- }
-
- // Get the original chunk text
- originalChunkText := chunk.GetText()
- if originalChunkText == "" {
- return errors.New("chunk has no text content")
- }
-
- // Parse the individual chunk text to get a fresh AST with its own tokenStream
- parseResults, err := pgparser.ParsePostgreSQL(originalChunkText)
- if err != nil {
- return errors.Wrapf(err, "failed to parse original chunk text: %s", originalChunkText)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE TABLE AST node from the fresh parse
- var createStmt *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &createStmt,
- }, parseResult.Tree)
-
- if createStmt == nil {
- return errors.New("failed to extract CREATE TABLE AST node from chunk text")
- }
-
- // Get the parser and tokenStream from the fresh parse
- ctxParser := createStmt.GetParser()
- if ctxParser == nil {
- return errors.New("parser not available for fresh AST node")
- }
-
- tokenStream := ctxParser.GetTokenStream()
- if tokenStream == nil {
- return errors.New("token stream not available for fresh parser")
- }
-
- // Create rewriter for the individual chunk's tokenStream
- rewriter := antlr.NewTokenStreamRewriter(tokenStream)
-
- // Apply column changes using the rewriter
- err = applyColumnChanges(rewriter, createStmt, currentTable, previousTable, sequences)
- if err != nil {
- return errors.Wrapf(err, "failed to apply column changes")
- }
-
- // Apply constraint changes using the same rewriter
- err = applyConstraintChanges(rewriter, createStmt, currentTable, previousTable)
- if err != nil {
- return errors.Wrapf(err, "failed to apply constraint changes")
- }
-
- // Get the modified SQL from the rewriter
- modifiedSQL := rewriter.GetTextDefault()
-
- // Parse the modified SQL to get the final AST
- finalParseResult, err := pgparser.ParsePostgreSQL(modifiedSQL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse modified SQL: %s", modifiedSQL)
- }
-
- if len(finalParseResult) != 1 {
- return errors.Errorf("expected exactly one statement in modified SQL, got %d", len(finalParseResult))
- }
-
- // Extract the final CREATE TABLE AST node
- var newCreateTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &newCreateTableNode,
- }, finalParseResult[0].Tree)
-
- if newCreateTableNode == nil {
- return errors.New("failed to extract CREATE TABLE AST node from modified text")
- }
-
- // Update the chunk with the new AST node
- chunk.ASTNode = newCreateTableNode
-
- // Synchronize COMMENT ON TABLE statements only if comment has changed
- if currentTable.Comment != previousTable.Comment {
- schemaName, tableName := parseIdentifier(chunk.Identifier)
- if err := syncObjectCommentStatements(chunk, currentTable.Comment, "TABLE", schemaName, tableName); err != nil {
- return errors.Wrapf(err, "failed to sync COMMENT statements for table %s", chunk.Identifier)
- }
- }
-
- return nil
-}
-
-// applyColumnChanges applies column changes using the provided rewriter without parsing SQL
-func applyColumnChanges(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, currentTable, previousTable *storepb.TableMetadata, sequences []*storepb.SequenceMetadata) error {
- // Create column maps for efficient lookups
- currentColumns := make(map[string]*storepb.ColumnMetadata)
- previousColumns := make(map[string]*storepb.ColumnMetadata)
-
- for _, col := range currentTable.Columns {
- currentColumns[col.Name] = col
- }
- for _, col := range previousTable.Columns {
- previousColumns[col.Name] = col
- }
-
- // Extract existing column definitions from AST
- existingColumnDefs := extractColumnDefinitionsWithAST(createStmt)
-
- // Phase 1: Handle column deletions (process in reverse order to maintain token positions)
- for i := len(existingColumnDefs.Order) - 1; i >= 0; i-- {
- columnName := existingColumnDefs.Order[i]
- if _, exists := currentColumns[columnName]; !exists {
- // Column was deleted
- columnDef := existingColumnDefs.Map[columnName]
- err := deleteColumnFromAST(rewriter, columnDef.ASTNode, createStmt)
- if err != nil {
- return errors.Wrapf(err, "failed to delete column %s", columnName)
- }
- }
- }
-
- // Phase 2: Handle column modifications
- for _, columnName := range existingColumnDefs.Order {
- if currentCol, currentExists := currentColumns[columnName]; currentExists {
- if previousCol, previousExists := previousColumns[columnName]; previousExists {
- // Column exists in both - check if modified
- if !columnsEqual(currentCol, previousCol) {
- columnDef := existingColumnDefs.Map[columnName]
- err := modifyColumnInAST(rewriter, columnDef.ASTNode, currentCol, currentTable.Name, sequences)
- if err != nil {
- return errors.Wrapf(err, "failed to modify column %s", columnName)
- }
- }
- }
- }
- }
-
- // Phase 3: Handle column additions (add at the end)
- for _, currentCol := range currentTable.Columns {
- if _, exists := previousColumns[currentCol.Name]; !exists {
- // Column was added
- err := addColumnToAST(rewriter, createStmt, currentCol, currentTable.Name, sequences)
- if err != nil {
- return errors.Wrapf(err, "failed to add column %s", currentCol.Name)
- }
- }
- }
-
- return nil
-}
-
-// applyConstraintChanges applies constraint changes using the provided rewriter without parsing SQL
-func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, currentTable, previousTable *storepb.TableMetadata) error {
- // Create constraint maps for efficient lookups
- currentCheckConstraints := make(map[string]*storepb.CheckConstraintMetadata)
- previousCheckConstraints := make(map[string]*storepb.CheckConstraintMetadata)
- currentFKConstraints := make(map[string]*storepb.ForeignKeyMetadata)
- previousFKConstraints := make(map[string]*storepb.ForeignKeyMetadata)
- currentPKConstraints := make(map[string]*storepb.IndexMetadata)
- previousPKConstraints := make(map[string]*storepb.IndexMetadata)
- currentUKConstraints := make(map[string]*storepb.IndexMetadata)
- previousUKConstraints := make(map[string]*storepb.IndexMetadata)
- currentExcludeConstraints := make(map[string]*storepb.ExcludeConstraintMetadata)
- previousExcludeConstraints := make(map[string]*storepb.ExcludeConstraintMetadata)
-
- // Build constraint maps from metadata
- for _, constraint := range currentTable.CheckConstraints {
- currentCheckConstraints[constraint.Name] = constraint
- }
- for _, constraint := range previousTable.CheckConstraints {
- previousCheckConstraints[constraint.Name] = constraint
- }
- for _, constraint := range currentTable.ForeignKeys {
- currentFKConstraints[constraint.Name] = constraint
- }
- for _, constraint := range previousTable.ForeignKeys {
- previousFKConstraints[constraint.Name] = constraint
- }
- // Build primary key constraint maps
- for _, index := range currentTable.Indexes {
- if index.Primary {
- currentPKConstraints[index.Name] = index
- }
- }
- for _, index := range previousTable.Indexes {
- if index.Primary {
- previousPKConstraints[index.Name] = index
- }
- }
- // Build unique key constraint maps (unique constraints, not just indexes)
- for _, index := range currentTable.Indexes {
- if index.Unique && !index.Primary && index.IsConstraint {
- currentUKConstraints[index.Name] = index
- }
- }
- for _, index := range previousTable.Indexes {
- if index.Unique && !index.Primary && index.IsConstraint {
- previousUKConstraints[index.Name] = index
- }
- }
- // Build EXCLUDE constraint maps
- for _, constraint := range currentTable.ExcludeConstraints {
- currentExcludeConstraints[constraint.Name] = constraint
- }
- for _, constraint := range previousTable.ExcludeConstraints {
- previousExcludeConstraints[constraint.Name] = constraint
- }
-
- // Extract constraint definitions with AST nodes for precise manipulation
- currentCheckDefs := extractCheckConstraintDefinitionsWithAST(createStmt)
- currentFKDefs := extractForeignKeyDefinitionsWithAST(createStmt)
- currentPKDefs := extractPrimaryKeyDefinitionsInOrder(createStmt)
- currentUKDefs := extractUniqueKeyDefinitionsInOrder(createStmt)
- currentExcludeDefs := extractExcludeConstraintDefinitionsWithAST(createStmt)
-
- // Phase 1: Handle constraint deletions (reverse order for stability)
- // Delete check constraints
- for i := len(currentCheckDefs) - 1; i >= 0; i-- {
- checkDef := currentCheckDefs[i]
- if _, exists := currentCheckConstraints[checkDef.Name]; !exists {
- // Constraint was dropped
- err := deleteConstraintFromAST(rewriter, checkDef.ASTNode, createStmt)
- if err != nil {
- return errors.Wrapf(err, "failed to delete check constraint %s", checkDef.Name)
- }
- }
- }
-
- // Delete foreign key constraints
- for i := len(currentFKDefs) - 1; i >= 0; i-- {
- fkDef := currentFKDefs[i]
- if _, exists := currentFKConstraints[fkDef.Name]; !exists {
- // Constraint was dropped
- err := deleteConstraintFromAST(rewriter, fkDef.ASTNode, createStmt)
- if err != nil {
- return errors.Wrapf(err, "failed to delete foreign key constraint %s", fkDef.Name)
- }
- }
- }
-
- // Delete primary key constraints
- for i := len(currentPKDefs) - 1; i >= 0; i-- {
- pkDef := currentPKDefs[i]
- if _, exists := currentPKConstraints[pkDef.Name]; !exists {
- // Constraint was dropped
- err := deleteConstraintFromAST(rewriter, pkDef.ASTNode, createStmt)
- if err != nil {
- return errors.Wrapf(err, "failed to delete primary key constraint %s", pkDef.Name)
- }
- }
- }
-
- // Delete unique key constraints
- for i := len(currentUKDefs) - 1; i >= 0; i-- {
- ukDef := currentUKDefs[i]
- if _, exists := currentUKConstraints[ukDef.Name]; !exists {
- // Constraint was dropped
- err := deleteConstraintFromAST(rewriter, ukDef.ASTNode, createStmt)
- if err != nil {
- return errors.Wrapf(err, "failed to delete unique key constraint %s", ukDef.Name)
- }
- }
- }
-
- // Delete EXCLUDE constraints
- for i := len(currentExcludeDefs) - 1; i >= 0; i-- {
- excludeDef := currentExcludeDefs[i]
- if _, exists := currentExcludeConstraints[excludeDef.Name]; !exists {
- // Constraint was dropped
- err := deleteConstraintFromAST(rewriter, excludeDef.ASTNode, createStmt)
- if err != nil {
- return errors.Wrapf(err, "failed to delete exclude constraint %s", excludeDef.Name)
- }
- }
- }
-
- // Phase 2: Handle constraint modifications
- // Modify check constraints
- for _, checkDef := range currentCheckDefs {
- if currentConstraint, exists := currentCheckConstraints[checkDef.Name]; exists {
- if previousConstraint, wasPresent := previousCheckConstraints[checkDef.Name]; wasPresent {
- // Check if constraint was modified by comparing text
- if !constraintsEqual(currentConstraint, previousConstraint) {
- err := modifyConstraintInAST(rewriter, checkDef.ASTNode, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to modify check constraint %s", checkDef.Name)
- }
- }
- }
- }
- }
-
- // Modify foreign key constraints
- for _, fkDef := range currentFKDefs {
- if currentConstraint, exists := currentFKConstraints[fkDef.Name]; exists {
- if previousConstraint, wasPresent := previousFKConstraints[fkDef.Name]; wasPresent {
- // Check if constraint was modified
- if !fkConstraintsEqual(currentConstraint, previousConstraint) {
- err := modifyConstraintInAST(rewriter, fkDef.ASTNode, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to modify foreign key constraint %s", fkDef.Name)
- }
- }
- }
- }
- }
-
- // Modify primary key constraints
- for _, pkDef := range currentPKDefs {
- if currentConstraint, exists := currentPKConstraints[pkDef.Name]; exists {
- if previousConstraint, wasPresent := previousPKConstraints[pkDef.Name]; wasPresent {
- // Check if constraint was modified
- if !pkConstraintsEqual(currentConstraint, previousConstraint) {
- err := modifyConstraintInAST(rewriter, pkDef.ASTNode, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to modify primary key constraint %s", pkDef.Name)
- }
- }
- }
- }
- }
-
- // Modify unique key constraints
- for _, ukDef := range currentUKDefs {
- if currentConstraint, exists := currentUKConstraints[ukDef.Name]; exists {
- if previousConstraint, wasPresent := previousUKConstraints[ukDef.Name]; wasPresent {
- // Check if constraint was modified
- if !ukConstraintsEqual(currentConstraint, previousConstraint) {
- err := modifyConstraintInAST(rewriter, ukDef.ASTNode, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to modify unique key constraint %s", ukDef.Name)
- }
- }
- }
- }
- }
-
- // Modify EXCLUDE constraints
- for _, excludeDef := range currentExcludeDefs {
- if currentConstraint, exists := currentExcludeConstraints[excludeDef.Name]; exists {
- if previousConstraint, wasPresent := previousExcludeConstraints[excludeDef.Name]; wasPresent {
- // Check if constraint was modified
- if !excludeConstraintsEqual(currentConstraint, previousConstraint) {
- err := modifyConstraintInAST(rewriter, excludeDef.ASTNode, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to modify exclude constraint %s", excludeDef.Name)
- }
- }
- }
- }
- }
-
- // Phase 3: Handle constraint additions
- // Add new check constraints
- for _, currentConstraint := range currentTable.CheckConstraints {
- if _, existed := previousCheckConstraints[currentConstraint.Name]; !existed {
- // New check constraint
- err := addConstraintToAST(rewriter, createStmt, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to add check constraint %s", currentConstraint.Name)
- }
- }
- }
-
- // Add new foreign key constraints
- for _, currentConstraint := range currentTable.ForeignKeys {
- if _, existed := previousFKConstraints[currentConstraint.Name]; !existed {
- // New foreign key constraint
- err := addConstraintToAST(rewriter, createStmt, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to add foreign key constraint %s", currentConstraint.Name)
- }
- }
- }
-
- // Add new primary key constraints
- for _, currentIndex := range currentTable.Indexes {
- if currentIndex.Primary {
- if _, existed := previousPKConstraints[currentIndex.Name]; !existed {
- // New primary key constraint
- err := addConstraintToAST(rewriter, createStmt, currentIndex)
- if err != nil {
- return errors.Wrapf(err, "failed to add primary key constraint %s", currentIndex.Name)
- }
- }
- }
- }
-
- // Add new unique key constraints
- for _, currentIndex := range currentTable.Indexes {
- if currentIndex.Unique && !currentIndex.Primary && currentIndex.IsConstraint {
- if _, existed := previousUKConstraints[currentIndex.Name]; !existed {
- // New unique key constraint
- err := addConstraintToAST(rewriter, createStmt, currentIndex)
- if err != nil {
- return errors.Wrapf(err, "failed to add unique key constraint %s", currentIndex.Name)
- }
- }
- }
- }
-
- // Add new EXCLUDE constraints
- for _, currentConstraint := range currentTable.ExcludeConstraints {
- if _, existed := previousExcludeConstraints[currentConstraint.Name]; !existed {
- // New EXCLUDE constraint
- err := addConstraintToAST(rewriter, createStmt, currentConstraint)
- if err != nil {
- return errors.Wrapf(err, "failed to add exclude constraint %s", currentConstraint.Name)
- }
- }
- }
-
- return nil
-}
-
-// deleteColumnFromAST removes a column definition from the CREATE TABLE statement using token rewriter
-// Improved comma handling: always look for a following comma first, regardless of column position
-func deleteColumnFromAST(rewriter *antlr.TokenStreamRewriter, columnDef parser.IColumnDefContext, _ *parser.CreatestmtContext) error {
- if columnDef == nil {
- return errors.New("column definition is nil")
- }
-
- startToken := columnDef.GetStart()
- stopToken := columnDef.GetStop()
- if startToken == nil || stopToken == nil {
- return errors.New("unable to get column definition tokens")
- }
-
- // Find the actual deletion range including commas and whitespace
- deleteStartIndex := startToken.GetTokenIndex()
- deleteEndIndex := stopToken.GetTokenIndex()
-
- // Strategy: Always try to remove the following comma first
- // This handles cases where there are table constraints after columns
- nextCommaIndex := -1
- nextCommaEndIndex := -1
- for i := stopToken.GetTokenIndex() + 1; i < rewriter.GetTokenStream().Size(); i++ {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetTokenType() == parser.PostgreSQLParserCOMMA {
- nextCommaIndex = i
- // Look for whitespace after the comma to include in deletion
- nextCommaEndIndex = i
- for j := i + 1; j < rewriter.GetTokenStream().Size(); j++ {
- nextToken := rewriter.GetTokenStream().Get(j)
- // Include whitespace and newlines after the comma
- if nextToken.GetChannel() != antlr.TokenDefaultChannel {
- nextCommaEndIndex = j
- } else {
- break
- }
- }
- break
- }
- // Skip whitespace and comments, but stop at other meaningful tokens
- if token.GetChannel() == antlr.TokenDefaultChannel {
- // Found a non-comma token on the default channel, stop searching
- break
- }
- }
-
- if nextCommaIndex != -1 {
- // Found a following comma - remove column, comma, and trailing whitespace
- deleteEndIndex = nextCommaEndIndex
- } else {
- // No following comma found - this might be the last element
- // Try to find a preceding comma to remove
- prevCommaIndex := -1
- prevCommaStartIndex := -1
- for i := startToken.GetTokenIndex() - 1; i >= 0; i-- {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetTokenType() == parser.PostgreSQLParserCOMMA {
- prevCommaIndex = i
- // Look for whitespace before the comma to include in deletion
- prevCommaStartIndex = i
- for j := i - 1; j >= 0; j-- {
- prevToken := rewriter.GetTokenStream().Get(j)
- // Include whitespace and newlines before the comma
- if prevToken.GetChannel() != antlr.TokenDefaultChannel {
- prevCommaStartIndex = j
- } else {
- break
- }
- }
- break
- }
- // Skip whitespace and comments, but stop at other meaningful tokens
- if token.GetChannel() == antlr.TokenDefaultChannel {
- break
- }
- }
-
- if prevCommaIndex != -1 {
- // Found a preceding comma - remove it along with leading whitespace and the column
- deleteStartIndex = prevCommaStartIndex
- } else {
- // No comma found (single column case) - just remove the column
- // But also clean up any trailing whitespace that might leave empty lines
- for i := stopToken.GetTokenIndex() + 1; i < rewriter.GetTokenStream().Size(); i++ {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetChannel() != antlr.TokenDefaultChannel {
- deleteEndIndex = i
- } else {
- break
- }
- }
- }
- }
-
- // Perform the deletion with the computed range
- rewriter.DeleteDefault(deleteStartIndex, deleteEndIndex)
-
- return nil
-}
-
-// modifyColumnInAST modifies an existing column definition using token rewriter
-func modifyColumnInAST(rewriter *antlr.TokenStreamRewriter, columnDef parser.IColumnDefContext, newColumn *storepb.ColumnMetadata, tableName string, sequences []*storepb.SequenceMetadata) error {
- if columnDef == nil || newColumn == nil {
- return errors.New("column definition or new column metadata is nil")
- }
-
- startToken := columnDef.GetStart()
- stopToken := columnDef.GetStop()
- if startToken == nil || stopToken == nil {
- return errors.New("unable to get column definition tokens")
- }
-
- // Generate new column definition SDL
- newColumnSDL := generateColumnSDL(newColumn, tableName, sequences)
-
- // Replace the entire column definition
- rewriter.ReplaceDefault(startToken.GetTokenIndex(), stopToken.GetTokenIndex(), newColumnSDL)
-
- return nil
-}
-
-// addColumnToAST adds a new column definition to the CREATE TABLE statement
-func addColumnToAST(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, newColumn *storepb.ColumnMetadata, tableName string, sequences []*storepb.SequenceMetadata) error {
- if createStmt == nil || newColumn == nil {
- return errors.New("create statement or new column metadata is nil")
- }
-
- // Find the last column definition to insert after it
- columnDefs := extractColumnDefinitionsWithAST(createStmt)
-
- if len(columnDefs.Order) == 0 {
- // No existing columns - need to add first column to empty table
- // Find the opening parenthesis and insert after it
- if createStmt.Opttableelementlist() != nil {
- // Table has element list structure, find the position to insert
- for i := 0; i < rewriter.GetTokenStream().Size(); i++ {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetTokenType() == parser.PostgreSQLParserOPEN_PAREN {
- // Found opening parenthesis, insert new column after it
- newColumnSDL := "\n " + generateColumnSDL(newColumn, tableName, sequences) + "\n"
- rewriter.InsertAfterDefault(i, newColumnSDL)
- return nil
- }
- }
- }
- return errors.New("unable to find position to insert first column")
- }
-
- // Get the last column definition
- lastColumnName := columnDefs.Order[len(columnDefs.Order)-1]
- lastColumnDef := columnDefs.Map[lastColumnName]
-
- stopToken := lastColumnDef.ASTNode.GetStop()
- if stopToken == nil {
- return errors.New("unable to get last column stop token")
- }
-
- // Generate new column definition SDL with leading comma and proper indentation
- newColumnSDL := ",\n " + generateColumnSDL(newColumn, tableName, sequences)
-
- // Insert after the last column
- rewriter.InsertAfterDefault(stopToken.GetTokenIndex(), newColumnSDL)
-
- return nil
-}
-
-// generateColumnSDL generates SDL text for a single column definition using the extracted writeColumnSDL function
-func generateColumnSDL(column *storepb.ColumnMetadata, tableName string, sequences []*storepb.SequenceMetadata) string {
- if column == nil {
- return ""
- }
-
- var buf strings.Builder
- err := writeColumnSDL(&buf, column, tableName, sequences)
- if err != nil {
- // If there's an error writing to the buffer, return empty string
- // This should rarely happen since we're writing to a strings.Builder
- return ""
- }
-
- return buf.String()
-}
-
-// columnsEqual compares two column metadata objects for equality
-func columnsEqual(a, b *storepb.ColumnMetadata) bool {
- if a == nil || b == nil {
- return a == b
- }
-
- return a.Name == b.Name &&
- a.Type == b.Type &&
- a.Nullable == b.Nullable &&
- a.Default == b.Default &&
- a.Collation == b.Collation
-}
-
// currentDatabaseSDLChunks stores pre-computed SDL chunks from current database metadata
// for performance optimization during usability checks
type currentDatabaseSDLChunks struct {
@@ -1227,2717 +404,91 @@ func convertDatabaseSchemaToSDL(dbMetadata *model.DatabaseMetadata) (string, err
return getSDLFormat(metadata)
}
-// deleteConstraintFromAST removes a constraint definition from the CREATE TABLE statement using token rewriter
-func deleteConstraintFromAST(rewriter *antlr.TokenStreamRewriter, constraintAST parser.ITableconstraintContext, _ *parser.CreatestmtContext) error {
- if constraintAST == nil || rewriter == nil {
- return errors.New("constraint AST or rewriter is nil")
- }
-
- // Get start and stop tokens for the constraint
- startToken := constraintAST.GetStart()
- stopToken := constraintAST.GetStop()
-
- if startToken == nil || stopToken == nil {
- return errors.New("unable to get constraint definition tokens")
- }
+// extractCheckConstraintDefinitionsWithAST extracts check constraint definitions with their AST nodes
+// Note: This is a wrapper around the existing function with a different name for clarity
+func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*CheckConstraintDefWithAST {
+ return extractCheckConstraintDefinitionsInOrder(createStmt)
+}
- // Find the actual deletion range including commas and whitespace
- deleteStartIndex := startToken.GetTokenIndex()
- deleteEndIndex := stopToken.GetTokenIndex()
-
- // Strategy: Always try to remove the following comma first
- // This handles cases where there are more constraints after this one
- nextCommaIndex := -1
- nextCommaEndIndex := -1
- for i := stopToken.GetTokenIndex() + 1; i < rewriter.GetTokenStream().Size(); i++ {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetTokenType() == parser.PostgreSQLParserCOMMA {
- nextCommaIndex = i
- // Look for whitespace after the comma to include in deletion
- nextCommaEndIndex = i
- for j := i + 1; j < rewriter.GetTokenStream().Size(); j++ {
- nextToken := rewriter.GetTokenStream().Get(j)
- // Include whitespace and newlines after the comma
- if nextToken.GetChannel() != antlr.TokenDefaultChannel {
- nextCommaEndIndex = j
- } else {
- break
- }
- }
- break
- }
- // Skip whitespace and comments, but stop at other meaningful tokens
- if token.GetChannel() == antlr.TokenDefaultChannel {
- // Found a non-comma token on the default channel, stop searching
- break
- }
- }
-
- if nextCommaIndex != -1 {
- // Found a following comma - remove constraint, comma, and trailing whitespace
- deleteEndIndex = nextCommaEndIndex
- } else {
- // No following comma found - this might be the last element
- // Try to find a preceding comma to remove
- prevCommaIndex := -1
- prevCommaStartIndex := -1
- for i := startToken.GetTokenIndex() - 1; i >= 0; i-- {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetTokenType() == parser.PostgreSQLParserCOMMA {
- prevCommaIndex = i
- // Look for whitespace before the comma to include in deletion
- prevCommaStartIndex = i
- for j := i - 1; j >= 0; j-- {
- prevToken := rewriter.GetTokenStream().Get(j)
- // Include whitespace and newlines before the comma
- if prevToken.GetChannel() != antlr.TokenDefaultChannel {
- prevCommaStartIndex = j
- } else {
- break
- }
- }
- break
- }
- // Skip whitespace and comments, but stop at other meaningful tokens
- if token.GetChannel() == antlr.TokenDefaultChannel {
- break
- }
- }
-
- if prevCommaIndex != -1 {
- // Found a preceding comma - remove it along with leading whitespace and the constraint
- deleteStartIndex = prevCommaStartIndex
- } else {
- // No comma found (single constraint case) - just remove the constraint
- // But also clean up any trailing whitespace that might leave empty lines
- for i := stopToken.GetTokenIndex() + 1; i < rewriter.GetTokenStream().Size(); i++ {
- token := rewriter.GetTokenStream().Get(i)
- if token.GetChannel() != antlr.TokenDefaultChannel {
- deleteEndIndex = i
- } else {
- break
- }
- }
- }
- }
-
- // Perform the deletion with the computed range
- rewriter.DeleteDefault(deleteStartIndex, deleteEndIndex)
-
- return nil
-}
-
-// modifyConstraintInAST modifies a constraint definition using token rewriter
-func modifyConstraintInAST(rewriter *antlr.TokenStreamRewriter, constraintAST parser.ITableconstraintContext, newConstraint any) error {
- if constraintAST == nil || rewriter == nil || newConstraint == nil {
- return errors.New("constraint AST, rewriter, or new constraint is nil")
- }
-
- // Get start and stop tokens for the constraint
- startToken := constraintAST.GetStart()
- stopToken := constraintAST.GetStop()
-
- if startToken == nil || stopToken == nil {
- return errors.New("unable to get constraint definition tokens")
- }
-
- // Generate the new constraint SDL
- var newConstraintSDL string
- switch constraint := newConstraint.(type) {
- case *storepb.CheckConstraintMetadata:
- newConstraintSDL = generateCheckConstraintSDL(constraint)
- case *storepb.ForeignKeyMetadata:
- newConstraintSDL = generateForeignKeyConstraintSDL(constraint)
- case *storepb.IndexMetadata:
- if constraint.Primary {
- newConstraintSDL = generatePrimaryKeyConstraintSDL(constraint)
- } else if constraint.Unique && constraint.IsConstraint {
- newConstraintSDL = generateUniqueKeyConstraintSDL(constraint)
- } else {
- return errors.New("unsupported index constraint type")
- }
- case *storepb.ExcludeConstraintMetadata:
- newConstraintSDL = generateExcludeConstraintSDL(constraint)
- default:
- return errors.New("unsupported constraint type")
- }
-
- // Replace the entire constraint definition
- rewriter.ReplaceDefault(startToken.GetTokenIndex(), stopToken.GetTokenIndex(), newConstraintSDL)
-
- return nil
-}
-
-// addConstraintToAST adds a new constraint to the CREATE TABLE statement using token rewriter
-func addConstraintToAST(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, newConstraint any) error {
- if rewriter == nil || createStmt == nil || newConstraint == nil {
- return errors.New("rewriter, create statement, or new constraint is nil")
- }
-
- // Generate the new constraint SDL
- var newConstraintSDL string
- switch constraint := newConstraint.(type) {
- case *storepb.CheckConstraintMetadata:
- newConstraintSDL = generateCheckConstraintSDL(constraint)
- case *storepb.ForeignKeyMetadata:
- newConstraintSDL = generateForeignKeyConstraintSDL(constraint)
- case *storepb.IndexMetadata:
- if constraint.Primary {
- newConstraintSDL = generatePrimaryKeyConstraintSDL(constraint)
- } else if constraint.Unique && constraint.IsConstraint {
- newConstraintSDL = generateUniqueKeyConstraintSDL(constraint)
- } else {
- return errors.New("unsupported index constraint type")
- }
- case *storepb.ExcludeConstraintMetadata:
- newConstraintSDL = generateExcludeConstraintSDL(constraint)
- default:
- return errors.New("unsupported constraint type")
- }
-
- // Find the position to insert the constraint
- // Look for the closing parenthesis of the CREATE TABLE statement
- optTableElementList := createStmt.Opttableelementlist()
- if optTableElementList == nil {
- return errors.New("CREATE TABLE statement has no table element list")
- }
-
- tableElementList := optTableElementList.Tableelementlist()
- if tableElementList == nil {
- return errors.New("table element list is nil")
- }
-
- // Get all table elements to find the last one
- tableElements := tableElementList.AllTableelement()
- if len(tableElements) == 0 {
- return errors.New("no table elements found")
- }
-
- // Get the last element (could be a column or constraint)
- lastElement := tableElements[len(tableElements)-1]
- stopToken := lastElement.GetStop()
- if stopToken == nil {
- return errors.New("unable to get last table element stop token")
- }
-
- // Generate constraint definition SDL with leading comma and proper indentation
- constraintSDL := ",\n " + newConstraintSDL
-
- // Insert after the last element
- rewriter.InsertAfterDefault(stopToken.GetTokenIndex(), constraintSDL)
-
- return nil
-}
-
-// generateCheckConstraintSDL generates SDL text for a check constraint using the existing writeCheckConstraintSDL function
-func generateCheckConstraintSDL(constraint *storepb.CheckConstraintMetadata) string {
- if constraint == nil {
- return ""
- }
-
- var buf strings.Builder
- err := writeCheckConstraintSDL(&buf, constraint)
- if err != nil {
- // If there's an error writing to the buffer, return empty string
- // This should rarely happen since we're writing to a strings.Builder
- return ""
- }
-
- return buf.String()
-}
-
-// generateForeignKeyConstraintSDL generates SDL text for a foreign key constraint using the existing writeForeignKeyConstraintSDL function
-func generateForeignKeyConstraintSDL(constraint *storepb.ForeignKeyMetadata) string {
- if constraint == nil {
- return ""
- }
-
- var buf strings.Builder
- err := writeForeignKeyConstraintSDL(&buf, constraint)
- if err != nil {
- // If there's an error writing to the buffer, return empty string
- // This should rarely happen since we're writing to a strings.Builder
- return ""
- }
-
- return buf.String()
-}
-
-// generateExcludeConstraintSDL generates SDL text for an EXCLUDE constraint using the existing writeExcludeConstraintSDL function
-func generateExcludeConstraintSDL(constraint *storepb.ExcludeConstraintMetadata) string {
- if constraint == nil {
- return ""
- }
-
- var buf strings.Builder
- err := writeExcludeConstraintSDL(&buf, constraint)
- if err != nil {
- // If there's an error writing to the buffer, return empty string
- // This should rarely happen since we're writing to a strings.Builder
- return ""
- }
-
- return buf.String()
-}
-
-// constraintsEqual compares two check constraint metadata objects for equality
-func constraintsEqual(a, b *storepb.CheckConstraintMetadata) bool {
- if a == nil || b == nil {
- return a == b
- }
-
- return a.Name == b.Name && a.Expression == b.Expression
-}
-
-// fkConstraintsEqual compares two foreign key constraint metadata objects for equality
-func fkConstraintsEqual(a, b *storepb.ForeignKeyMetadata) bool {
- if a == nil || b == nil {
- return a == b
- }
-
- // Compare basic properties
- if a.Name != b.Name ||
- a.ReferencedSchema != b.ReferencedSchema ||
- a.ReferencedTable != b.ReferencedTable ||
- a.OnDelete != b.OnDelete ||
- a.OnUpdate != b.OnUpdate {
- return false
- }
-
- // Compare columns arrays
- if len(a.Columns) != len(b.Columns) ||
- len(a.ReferencedColumns) != len(b.ReferencedColumns) {
- return false
- }
-
- for i := range a.Columns {
- if a.Columns[i] != b.Columns[i] {
- return false
- }
- }
-
- for i := range a.ReferencedColumns {
- if a.ReferencedColumns[i] != b.ReferencedColumns[i] {
- return false
- }
- }
-
- return true
-}
-
-// extractCheckConstraintDefinitionsWithAST extracts check constraint definitions with their AST nodes
-// Note: This is a wrapper around the existing function with a different name for clarity
-func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*CheckConstraintDefWithAST {
- return extractCheckConstraintDefinitionsInOrder(createStmt)
-}
-
-// extractForeignKeyDefinitionsWithAST extracts foreign key constraint definitions with their AST nodes
-// Note: This is a wrapper around the existing function with a different name for clarity
-func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*ForeignKeyDefWithAST {
- return extractForeignKeyDefinitionsInOrder(createStmt)
-}
-
-// extractExcludeConstraintDefinitionsWithAST extracts EXCLUDE constraint definitions with their AST nodes
-// Note: This is a wrapper around the existing function with a different name for clarity
-func extractExcludeConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*ExcludeConstraintDefWithAST {
- return extractExcludeConstraintDefinitionsInOrder(createStmt)
-}
-
-// PrimaryKeyDefWithAST represents a primary key constraint definition with its AST node
-type PrimaryKeyDefWithAST struct {
- Name string
- ASTNode parser.ITableconstraintContext
-}
-
-// UniqueKeyDefWithAST represents a unique key constraint definition with its AST node
-type UniqueKeyDefWithAST struct {
- Name string
- ASTNode parser.ITableconstraintContext
-}
-
-// extractPrimaryKeyDefinitionsInOrder extracts primary key constraint definitions with their AST nodes
-func extractPrimaryKeyDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*PrimaryKeyDefWithAST {
- var pkDefs []*PrimaryKeyDefWithAST
-
- if createStmt == nil {
- return pkDefs
- }
-
- // Navigate through the CREATE TABLE AST to find table constraints
- optTableElementList := createStmt.Opttableelementlist()
- if optTableElementList == nil {
- return pkDefs
- }
-
- tableElementList := optTableElementList.(*parser.OpttableelementlistContext).Tableelementlist()
- if tableElementList == nil {
- return pkDefs
- }
-
- // Iterate through table elements to find constraints
- for _, element := range tableElementList.(*parser.TableelementlistContext).AllTableelement() {
- if tableConstraint := element.(*parser.TableelementContext).Tableconstraint(); tableConstraint != nil {
- constraint, ok := tableConstraint.(*parser.TableconstraintContext)
- if !ok {
- continue
- }
-
- // Check if it's a primary key constraint
- if constraint.Constraintelem() != nil {
- elem, ok := constraint.Constraintelem().(*parser.ConstraintelemContext)
- if !ok {
- continue
- }
- if elem.PRIMARY() != nil && elem.KEY() != nil {
- // Extract constraint name
- constraintName := ""
- if constraint.Name() != nil {
- constraintName = pgparser.NormalizePostgreSQLName(constraint.Name())
- }
-
- if constraintName != "" {
- pkDefs = append(pkDefs, &PrimaryKeyDefWithAST{
- Name: constraintName,
- ASTNode: constraint,
- })
- }
- }
- }
- }
- }
-
- return pkDefs
-}
-
-// extractUniqueKeyDefinitionsInOrder extracts unique key constraint definitions with their AST nodes
-func extractUniqueKeyDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*UniqueKeyDefWithAST {
- var ukDefs []*UniqueKeyDefWithAST
-
- if createStmt == nil {
- return ukDefs
- }
-
- // Navigate through the CREATE TABLE AST to find table constraints
- optTableElementList := createStmt.Opttableelementlist()
- if optTableElementList == nil {
- return ukDefs
- }
-
- tableElementList := optTableElementList.(*parser.OpttableelementlistContext).Tableelementlist()
- if tableElementList == nil {
- return ukDefs
- }
-
- // Iterate through table elements to find constraints
- for _, element := range tableElementList.(*parser.TableelementlistContext).AllTableelement() {
- if tableConstraint := element.(*parser.TableelementContext).Tableconstraint(); tableConstraint != nil {
- constraint, ok := tableConstraint.(*parser.TableconstraintContext)
- if !ok {
- continue
- }
-
- // Check if it's a unique constraint
- if constraint.Constraintelem() != nil {
- elem, ok := constraint.Constraintelem().(*parser.ConstraintelemContext)
- if !ok {
- continue
- }
- if elem.UNIQUE() != nil {
- // Extract constraint name
- constraintName := ""
- if constraint.Name() != nil {
- constraintName = pgparser.NormalizePostgreSQLName(constraint.Name())
- }
-
- if constraintName != "" {
- ukDefs = append(ukDefs, &UniqueKeyDefWithAST{
- Name: constraintName,
- ASTNode: constraint,
- })
- }
- }
- }
- }
- }
-
- return ukDefs
-}
-
-// pkConstraintsEqual checks if two primary key constraints are equal
-func pkConstraintsEqual(a, b *storepb.IndexMetadata) bool {
- if a == nil || b == nil {
- return a == b
- }
-
- // Compare basic properties
- if a.Name != b.Name || a.Primary != b.Primary {
- return false
- }
-
- // Compare expressions (columns)
- if len(a.Expressions) != len(b.Expressions) {
- return false
- }
-
- for i := range a.Expressions {
- if a.Expressions[i] != b.Expressions[i] {
- return false
- }
- }
-
- return true
-}
-
-// ukConstraintsEqual checks if two unique key constraints are equal
-func ukConstraintsEqual(a, b *storepb.IndexMetadata) bool {
- if a == nil || b == nil {
- return a == b
- }
-
- // Compare basic properties
- if a.Name != b.Name || a.Unique != b.Unique || a.IsConstraint != b.IsConstraint {
- return false
- }
-
- // Compare expressions (columns)
- if len(a.Expressions) != len(b.Expressions) {
- return false
- }
-
- for i := range a.Expressions {
- if a.Expressions[i] != b.Expressions[i] {
- return false
- }
- }
-
- return true
-}
-
-// excludeConstraintsEqual compares two EXCLUDE constraint metadata objects for equality
-func excludeConstraintsEqual(a, b *storepb.ExcludeConstraintMetadata) bool {
- if a == nil || b == nil {
- return a == b
- }
-
- return a.Name == b.Name && a.Expression == b.Expression
-}
-
-// generatePrimaryKeyConstraintSDL generates SDL text for a primary key constraint
-func generatePrimaryKeyConstraintSDL(constraint *storepb.IndexMetadata) string {
- if constraint == nil || !constraint.Primary {
- return ""
- }
-
- var buf strings.Builder
- err := writePrimaryKeyConstraintSDL(&buf, constraint)
- if err != nil {
- return ""
- }
- return buf.String()
-}
-
-// generateUniqueKeyConstraintSDL generates SDL text for a unique key constraint
-func generateUniqueKeyConstraintSDL(constraint *storepb.IndexMetadata) string {
- if constraint == nil || !constraint.Unique || constraint.Primary || !constraint.IsConstraint {
- return ""
- }
-
- var buf strings.Builder
- err := writeUniqueKeyConstraintSDL(&buf, constraint)
- if err != nil {
- return ""
- }
- return buf.String()
-}
-
-// extendedIndexMetadata stores index metadata with table and schema context
-type extendedIndexMetadata struct {
- *storepb.IndexMetadata
- SchemaName string
- TableName string // Table name or MaterializedView name
- TargetType string // "table" or "materialized_view"
-}
-
-// applyStandaloneIndexChangesToChunks applies minimal changes to standalone CREATE INDEX chunks
-// This handles creation, modification, and deletion of independent index statements
-func applyStandaloneIndexChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get index differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build index maps for current and previous schemas
- currentIndexes := make(map[string]*extendedIndexMetadata)
- previousIndexes := make(map[string]*extendedIndexMetadata)
-
- // Collect all standalone indexes from current schema (only non-constraint indexes)
- for _, schema := range currentMetadata.Schemas {
- // Collect indexes from tables
- for _, table := range schema.Tables {
- for _, index := range table.Indexes {
- // Only include standalone indexes (not constraints like PRIMARY KEY, UNIQUE CONSTRAINT)
- if !index.IsConstraint && !index.Primary {
- indexKey := formatIndexKey(schema.Name, index.Name)
- // Store extended index metadata with table/schema context
- extendedIndex := &extendedIndexMetadata{
- IndexMetadata: index,
- SchemaName: schema.Name,
- TableName: table.Name,
- TargetType: "table",
- }
- currentIndexes[indexKey] = extendedIndex
- }
- }
- }
-
- // Collect indexes from materialized views
- for _, mv := range schema.MaterializedViews {
- for _, index := range mv.Indexes {
- // Only include standalone indexes (not constraints)
- if !index.IsConstraint && !index.Primary {
- indexKey := formatIndexKey(schema.Name, index.Name)
- // Store extended index metadata with materialized view/schema context
- extendedIndex := &extendedIndexMetadata{
- IndexMetadata: index,
- SchemaName: schema.Name,
- TableName: mv.Name,
- TargetType: "materialized_view",
- }
- currentIndexes[indexKey] = extendedIndex
- }
- }
- }
- }
-
- // Collect all standalone indexes from previous schema
- for _, schema := range previousMetadata.Schemas {
- // Collect indexes from tables
- for _, table := range schema.Tables {
- for _, index := range table.Indexes {
- // Only include standalone indexes (not constraints)
- if !index.IsConstraint && !index.Primary {
- indexKey := formatIndexKey(schema.Name, index.Name)
- extendedIndex := &extendedIndexMetadata{
- IndexMetadata: index,
- SchemaName: schema.Name,
- TableName: table.Name,
- TargetType: "table",
- }
- previousIndexes[indexKey] = extendedIndex
- }
- }
- }
-
- // Collect indexes from materialized views
- for _, mv := range schema.MaterializedViews {
- for _, index := range mv.Indexes {
- // Only include standalone indexes (not constraints)
- if !index.IsConstraint && !index.Primary {
- indexKey := formatIndexKey(schema.Name, index.Name)
- extendedIndex := &extendedIndexMetadata{
- IndexMetadata: index,
- SchemaName: schema.Name,
- TableName: mv.Name,
- TargetType: "materialized_view",
- }
- previousIndexes[indexKey] = extendedIndex
- }
- }
- }
- }
-
- // Process index additions: create new index chunks
- for indexKey, currentIndex := range currentIndexes {
- if _, exists := previousIndexes[indexKey]; !exists {
- // New index - create a chunk for it
- err := createIndexChunk(previousChunks, currentIndex, indexKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create index chunk for %s", indexKey)
- }
- }
- }
-
- // Process index modifications: update existing chunks
- for indexKey, currentIndex := range currentIndexes {
- if previousIndex, exists := previousIndexes[indexKey]; exists {
- // Index exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- // If chunk doesn't exist, skip - we don't force-add database objects that user didn't define
- if _, chunkExists := previousChunks.Indexes[indexKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateIndexChunkIfNeeded(previousChunks, currentIndex, previousIndex, indexKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update index chunk for %s", indexKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this index in SDL
- }
- }
-
- // Process index deletions: remove dropped index chunks
- for indexKey := range previousIndexes {
- if _, exists := currentIndexes[indexKey]; !exists {
- // Index was dropped - remove it from chunks
- deleteIndexChunk(previousChunks, indexKey)
- }
- }
-
- return nil
-}
-
-// formatIndexKey creates a consistent key for index identification
-func formatIndexKey(schemaName, indexName string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- return schemaName + "." + indexName
-}
-
-// createIndexChunk creates a new CREATE INDEX chunk and adds it to the chunks
-func createIndexChunk(chunks *schema.SDLChunks, extIndex *extendedIndexMetadata, indexKey string) error {
- if extIndex == nil || extIndex.IndexMetadata == nil || chunks == nil {
- return nil
- }
-
- // Generate SDL text for the index
- indexSDL := generateCreateIndexSDL(extIndex)
- if indexSDL == "" {
- return errors.New("failed to generate SDL for index")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(indexSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated index SDL: %s", indexSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE INDEX AST node
- var indexASTNode *parser.IndexstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&indexExtractor{
- result: &indexASTNode,
- }, parseResult.Tree)
-
- if indexASTNode == nil {
- return errors.New("failed to extract CREATE INDEX AST node")
- }
-
- // Create and add the chunk
- chunk := &schema.SDLChunk{
- Identifier: indexKey,
- ASTNode: indexASTNode,
- }
-
- // Add COMMENT ON INDEX if the index has a comment
- if extIndex.Comment != "" {
- schemaName := extIndex.SchemaName
- if schemaName == "" {
- schemaName = "public"
- }
- if err := syncObjectCommentStatements(chunk, extIndex.Comment, "INDEX", schemaName, extIndex.Name); err != nil {
- return errors.Wrapf(err, "failed to add COMMENT statements for index %s", indexKey)
- }
- }
-
- if chunks.Indexes == nil {
- chunks.Indexes = make(map[string]*schema.SDLChunk)
- }
- chunks.Indexes[indexKey] = chunk
-
- return nil
-}
-
-// updateIndexChunkIfNeeded updates an existing index chunk if the index definition has changed
-func updateIndexChunkIfNeeded(chunks *schema.SDLChunks, currentIndex, previousIndex *extendedIndexMetadata, indexKey string) error {
- if currentIndex == nil || previousIndex == nil || chunks == nil {
- return nil
- }
-
- // Get the existing chunk
- chunk, exists := chunks.Indexes[indexKey]
- if !exists {
- return errors.Errorf("index chunk not found for key %s", indexKey)
- }
-
- // Check if the CREATE INDEX definition has changed (excluding comment)
- definitionChanged := !indexDefinitionsEqualExcludingComment(currentIndex.IndexMetadata, previousIndex.IndexMetadata)
-
- if definitionChanged {
- // Index definition has changed - regenerate the CREATE INDEX chunk
- indexSDL := generateCreateIndexSDL(currentIndex)
- if indexSDL == "" {
- return errors.New("failed to generate SDL for index")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(indexSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated index SDL: %s", indexSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE INDEX AST node
- var indexASTNode *parser.IndexstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&indexExtractor{
- result: &indexASTNode,
- }, parseResult.Tree)
-
- if indexASTNode == nil {
- return errors.New("failed to extract CREATE INDEX AST node")
- }
-
- // Update the CREATE INDEX AST node
- chunk.ASTNode = indexASTNode
- }
-
- // Synchronize COMMENT ON INDEX statements only if comment has changed
- if currentIndex.Comment != previousIndex.Comment {
- schemaName := currentIndex.SchemaName
- if schemaName == "" {
- schemaName = "public"
- }
- if err := syncObjectCommentStatements(chunk, currentIndex.Comment, "INDEX", schemaName, currentIndex.Name); err != nil {
- return errors.Wrapf(err, "failed to sync COMMENT statements for index %s", indexKey)
- }
- }
-
- return nil
-}
-
-// indexDefinitionsEqualExcludingComment compares two index definitions excluding comments
-func indexDefinitionsEqualExcludingComment(index1, index2 *storepb.IndexMetadata) bool {
- if index1 == nil || index2 == nil {
- return false
- }
-
- // Compare basic properties (excluding comment)
- if index1.Name != index2.Name ||
- index1.Unique != index2.Unique ||
- index1.Type != index2.Type ||
- len(index1.Expressions) != len(index2.Expressions) ||
- len(index1.Descending) != len(index2.Descending) {
- return false
- }
-
- // Compare expressions
- for i, expr := range index1.Expressions {
- if i >= len(index2.Expressions) || expr != index2.Expressions[i] {
- return false
- }
- }
-
- // Compare descending flags
- for i, desc := range index1.Descending {
- if i >= len(index2.Descending) || desc != index2.Descending[i] {
- return false
- }
- }
-
- return true
-}
-
-// deleteIndexChunk removes an index chunk from the chunks
-func deleteIndexChunk(chunks *schema.SDLChunks, indexKey string) {
- if chunks != nil && chunks.Indexes != nil {
- delete(chunks.Indexes, indexKey)
- }
-}
-
-// indexDefinitionsEqual compares two index definitions to see if they are equivalent
-func indexDefinitionsEqual(index1, index2 *storepb.IndexMetadata) bool {
- // First check everything except comment
- if !indexDefinitionsEqualExcludingComment(index1, index2) {
- return false
- }
-
- // Then check comment
- if index1.Comment != index2.Comment {
- return false
- }
-
- return true
-}
-
-// generateCreateIndexSDL generates SDL text for a CREATE INDEX statement using writeIndexSDL
-func generateCreateIndexSDL(extIndex *extendedIndexMetadata) string {
- if extIndex == nil || extIndex.IndexMetadata == nil {
- return ""
- }
-
- var buf strings.Builder
- schemaName := extIndex.SchemaName
- if schemaName == "" {
- schemaName = "public"
- }
-
- // Use the existing writeIndexSDL function from get_database_definition.go
- if err := writeIndexSDL(&buf, schemaName, extIndex.TableName, extIndex.IndexMetadata); err != nil {
- return ""
- }
-
- return buf.String()
-}
-
-// indexExtractor is a walker to extract CREATE INDEX AST nodes
-type indexExtractor struct {
- parser.BasePostgreSQLParserListener
- result **parser.IndexstmtContext
-}
-
-func (e *indexExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
-}
-
-// applyFunctionChangesToChunks applies minimal changes to CREATE FUNCTION chunks
-// This handles creation, modification, and deletion of function statements
-func applyFunctionChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get function differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build function maps for current and previous schemas
- currentFunctions := make(map[string]*storepb.FunctionMetadata)
- previousFunctions := make(map[string]*storepb.FunctionMetadata)
-
- // Collect all functions from current schema
- for _, schema := range currentMetadata.Schemas {
- for _, function := range schema.Functions {
- functionKey := formatFunctionKey(schema.Name, function)
- currentFunctions[functionKey] = function
- }
- }
-
- // Collect all functions from previous schema
- for _, schema := range previousMetadata.Schemas {
- for _, function := range schema.Functions {
- functionKey := formatFunctionKey(schema.Name, function)
- previousFunctions[functionKey] = function
- }
- }
-
- // Process function additions: create new function chunks
- for functionKey, currentFunction := range currentFunctions {
- if _, exists := previousFunctions[functionKey]; !exists {
- // New function - create a chunk for it
- err := createFunctionChunk(previousChunks, currentFunction, functionKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create function chunk for %s", functionKey)
- }
- }
- }
-
- // Process function modifications: update existing chunks
- for functionKey, currentFunction := range currentFunctions {
- if previousFunction, exists := previousFunctions[functionKey]; exists {
- // Function exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- // If chunk doesn't exist, skip - we don't force-add database objects that user didn't define
- if _, chunkExists := previousChunks.Functions[functionKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateFunctionChunkIfNeeded(previousChunks, currentFunction, previousFunction, functionKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update function chunk for %s", functionKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this function in SDL
- }
- }
-
- // Process function deletions: remove dropped function chunks
- for functionKey := range previousFunctions {
- if _, exists := currentFunctions[functionKey]; !exists {
- // Function was dropped - remove it from chunks
- deleteFunctionChunk(previousChunks, functionKey)
- }
- }
-
- return nil
-}
-
-// formatFunctionKey creates a consistent key for function identification using the full signature
-func formatFunctionKey(schemaName string, function *storepb.FunctionMetadata) string {
- if schemaName == "" {
- schemaName = "public"
- }
-
- // Extract the function signature from the definition
- signature := extractFunctionSignatureFromDefinition(function)
- if signature == "" {
- // Fallback to just the function name if signature extraction fails
- signature = function.Name + "()"
- }
-
- return schemaName + "." + signature
-}
-
-// extractFunctionSignatureFromDefinition extracts the function signature from its definition
-func extractFunctionSignatureFromDefinition(function *storepb.FunctionMetadata) string {
- if function == nil || function.Definition == "" {
- return ""
- }
-
- // Parse the function definition to extract signature
- parseResults, err := pgparser.ParsePostgreSQL(function.Definition)
- if err != nil {
- return ""
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return ""
- }
- parseResult := parseResults[0]
-
- tree := parseResult.Tree
-
- // Extract the CREATE FUNCTION node using a walker
- var result *parser.CreatefunctionstmtContext
- extractor := &functionExtractor{result: &result}
- antlr.NewParseTreeWalker().Walk(extractor, tree)
-
- if result == nil {
- return ""
- }
-
- // Use the unified function signature extraction
- return extractFunctionSignatureFromAST(result)
-}
-
-// extractFunctionSignatureFromAST extracts function signature from CREATE FUNCTION AST node
-// This is the unified function used by both chunk extraction and function comparison
-func extractFunctionSignatureFromAST(ctx *parser.CreatefunctionstmtContext) string {
- if ctx == nil {
- return ""
- }
-
- funcNameCtx := ctx.Func_name()
- if funcNameCtx == nil {
- return ""
- }
-
- // Extract function name using proper normalization
- funcNameParts := pgparser.NormalizePostgreSQLFuncName(funcNameCtx)
- if len(funcNameParts) == 0 {
- return ""
- }
-
- // Get the function name (without schema)
- var functionName string
- if len(funcNameParts) == 2 {
- // Schema qualified: schema.function_name
- functionName = funcNameParts[1]
- } else if len(funcNameParts) == 1 {
- // Unqualified: function_name
- functionName = funcNameParts[0]
- } else {
- // Unexpected format
- return ""
- }
-
- if functionName == "" {
- return ""
- }
-
- // Use the existing ExtractFunctionSignature function
- return ExtractFunctionSignature(ctx, functionName)
-}
-
-// createFunctionChunk creates a new CREATE FUNCTION chunk and adds it to the chunks
-func createFunctionChunk(chunks *schema.SDLChunks, function *storepb.FunctionMetadata, functionKey string) error {
- if function == nil || chunks == nil {
- return nil
- }
-
- // Generate function SDL using the existing writeFunctionSDL function
- sdl := generateCreateFunctionSDL(function)
- if sdl == "" {
- return errors.Errorf("failed to generate SDL for function %s", functionKey)
- }
-
- // Parse the SDL to get the AST node
- astNode, err := extractFunctionASTFromSDL(sdl)
- if err != nil {
- return errors.Wrapf(err, "failed to extract AST from generated function SDL for %s", functionKey)
- }
-
- // Create the chunk
- chunk := &schema.SDLChunk{
- Identifier: functionKey,
- ASTNode: astNode,
- }
-
- // Add COMMENT ON FUNCTION/PROCEDURE if the function has a comment
- if function.Comment != "" {
- // Determine if this is a PROCEDURE or FUNCTION by checking the definition
- objectType := "FUNCTION"
- if isDefinitionProcedure(function.Definition) {
- objectType = "PROCEDURE"
- }
- schemaName, functionName := parseIdentifier(functionKey)
- if err := syncObjectCommentStatements(chunk, function.Comment, objectType, schemaName, functionName); err != nil {
- return errors.Wrapf(err, "failed to add COMMENT statements for function %s", functionKey)
- }
- }
-
- // Ensure Functions map is initialized
- if chunks.Functions == nil {
- chunks.Functions = make(map[string]*schema.SDLChunk)
- }
-
- chunks.Functions[functionKey] = chunk
- return nil
-}
-
-// updateFunctionChunkIfNeeded updates a function chunk if the definition has changed
-func updateFunctionChunkIfNeeded(chunks *schema.SDLChunks, currentFunction, previousFunction *storepb.FunctionMetadata, functionKey string) error {
- if currentFunction == nil || previousFunction == nil || chunks == nil {
- return nil
- }
-
- // Get the existing chunk
- chunk, exists := chunks.Functions[functionKey]
- if !exists {
- return errors.Errorf("function chunk not found for key %s", functionKey)
- }
-
- // Check if the CREATE FUNCTION definition has changed (excluding comment)
- definitionChanged := !functionDefinitionsEqualExcludingComment(currentFunction, previousFunction)
-
- if definitionChanged {
- // Function definition has changed - regenerate the CREATE FUNCTION chunk
- sdl := generateCreateFunctionSDL(currentFunction)
- if sdl == "" {
- return errors.Errorf("failed to generate SDL for function %s", functionKey)
- }
-
- // Parse the SDL to get the AST node
- astNode, err := extractFunctionASTFromSDL(sdl)
- if err != nil {
- return errors.Wrapf(err, "failed to extract AST from generated function SDL for %s", functionKey)
- }
-
- // Update the CREATE FUNCTION AST node
- chunk.ASTNode = astNode
- }
-
- // Synchronize COMMENT ON FUNCTION/PROCEDURE statements only if comment has changed
- if currentFunction.Comment != previousFunction.Comment {
- // Determine if this is a PROCEDURE or FUNCTION by checking the definition
- objectType := "FUNCTION"
- if isDefinitionProcedure(currentFunction.Definition) {
- objectType = "PROCEDURE"
- }
- schemaName, functionName := parseIdentifier(functionKey)
- if err := syncObjectCommentStatements(chunk, currentFunction.Comment, objectType, schemaName, functionName); err != nil {
- return errors.Wrapf(err, "failed to sync COMMENT statements for function %s", functionKey)
- }
- }
-
- return nil
-}
-
-// updateFunctionChunk updates an existing function chunk with new definition
-// This function synchronizes the CREATE FUNCTION and COMMENT ON FUNCTION statements
-// deleteFunctionChunk removes a function chunk from the chunks
-func deleteFunctionChunk(chunks *schema.SDLChunks, functionKey string) {
- if chunks != nil && chunks.Functions != nil {
- delete(chunks.Functions, functionKey)
- }
-}
-
-// generateCreateFunctionSDL generates SDL for a CREATE FUNCTION statement
-func generateCreateFunctionSDL(function *storepb.FunctionMetadata) string {
- if function == nil {
- return ""
- }
-
- var buf strings.Builder
- // Use the existing writeFunctionSDL function
- if err := writeFunctionSDL(&buf, "", function); err != nil {
- return ""
- }
-
- return buf.String()
-}
-
-// extractFunctionTextFromAST extracts normalized text from function AST node using token stream
-func extractFunctionTextFromAST(functionAST *parser.CreatefunctionstmtContext) string {
- if functionAST == nil {
- return ""
- }
-
- // Get tokens from the parser
- if parser := functionAST.GetParser(); parser != nil {
- if tokenStream := parser.GetTokenStream(); tokenStream != nil {
- start := functionAST.GetStart()
- stop := functionAST.GetStop()
- if start != nil && stop != nil {
- return tokenStream.GetTextFromTokens(start, stop)
- }
- }
- }
-
- // Fallback to GetText() if tokens are not available
- return functionAST.GetText()
-}
-
-// functionDefinitionsEqual compares two function definitions to see if they are equivalent
-func functionDefinitionsEqual(function1, function2 *storepb.FunctionMetadata) bool {
- // First check everything except comment
- if !functionDefinitionsEqualExcludingComment(function1, function2) {
- return false
- }
-
- // Then check comment
- if function1.Comment != function2.Comment {
- return false
- }
-
- return true
-}
-
-// functionDefinitionsEqualExcludingComment compares two function definitions excluding comments
-func functionDefinitionsEqualExcludingComment(function1, function2 *storepb.FunctionMetadata) bool {
- if function1 == nil && function2 == nil {
- return true
- }
- if function1 == nil || function2 == nil {
- return false
- }
-
- // Compare function names
- if function1.Name != function2.Name {
- return false
- }
-
- // Compare function definitions (most important comparison)
- definition1 := strings.TrimSpace(function1.Definition)
- definition2 := strings.TrimSpace(function2.Definition)
-
- // Normalize definitions for comparison
- definition1 = strings.TrimSuffix(definition1, ";")
- definition2 = strings.TrimSuffix(definition2, ";")
-
- return definition1 == definition2
-}
-
-// extractFunctionASTFromSDL parses a function SDL and extracts the CREATE FUNCTION AST node
-func extractFunctionASTFromSDL(sdl string) (antlr.ParserRuleContext, error) {
- if sdl == "" {
- return nil, errors.New("empty SDL provided")
- }
-
- // Parse the SDL to get AST
- parseResults, err := pgparser.ParsePostgreSQL(sdl)
- if err != nil {
- return nil, errors.Wrap(err, "failed to parse function SDL")
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return nil, errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- tree := parseResult.Tree
-
- // Extract the CREATE FUNCTION node using a walker
- var result *parser.CreatefunctionstmtContext
- extractor := &functionExtractor{result: &result}
- antlr.NewParseTreeWalker().Walk(extractor, tree)
-
- if result == nil {
- return nil, errors.New("no CREATE FUNCTION statement found in SDL")
- }
-
- return result, nil
-}
-
-// functionExtractor is a walker to extract CREATE FUNCTION AST nodes
-type functionExtractor struct {
- parser.BasePostgreSQLParserListener
- result **parser.CreatefunctionstmtContext
-}
-
-func (e *functionExtractor) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
-}
-
-// applySequenceChangesToChunks applies minimal changes to CREATE SEQUENCE chunks
-// This handles creation, modification, and deletion of sequence statements
-func applySequenceChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get sequence differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build sequence maps for current and previous schemas
- currentSequences := make(map[string]*storepb.SequenceMetadata)
- previousSequences := make(map[string]*storepb.SequenceMetadata)
-
- // Collect all sequences from current schema
- for _, schema := range currentMetadata.Schemas {
- for _, sequence := range schema.Sequences {
- sequenceKey := formatSequenceKey(schema.Name, sequence.Name)
- currentSequences[sequenceKey] = sequence
- }
- }
-
- // Collect all sequences from previous schema
- for _, schema := range previousMetadata.Schemas {
- for _, sequence := range schema.Sequences {
- sequenceKey := formatSequenceKey(schema.Name, sequence.Name)
- previousSequences[sequenceKey] = sequence
- }
- }
-
- // Process sequence additions: create new sequence chunks
- for sequenceKey, currentSequence := range currentSequences {
- if _, exists := previousSequences[sequenceKey]; !exists {
- // Skip sequences owned by tables (e.g., SERIAL columns) - they should be managed by their owner tables
- if currentSequence.OwnerTable != "" {
- continue
- }
- // New sequence - create a chunk for it
- err := createSequenceChunk(previousChunks, currentSequence, sequenceKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create sequence chunk for %s", sequenceKey)
- }
- }
- }
-
- // Process sequence modifications: update existing chunks
- for sequenceKey, currentSequence := range currentSequences {
- if previousSequence, exists := previousSequences[sequenceKey]; exists {
- // Sequence exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- // If chunk doesn't exist, skip - we don't force-add database objects that user didn't define
- if _, chunkExists := previousChunks.Sequences[sequenceKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateSequenceChunkIfNeeded(previousChunks, currentSequence, previousSequence, sequenceKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update sequence chunk for %s", sequenceKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this sequence in SDL
- }
- }
-
- // Process sequence deletions: remove dropped sequence chunks
- for sequenceKey := range previousSequences {
- if _, exists := currentSequences[sequenceKey]; !exists {
- // Sequence was dropped - remove it from chunks
- deleteSequenceChunk(previousChunks, sequenceKey)
- }
- }
-
- return nil
-}
-
-// formatSequenceKey creates a consistent key for sequence identification
-func formatSequenceKey(schemaName, sequenceName string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- return schemaName + "." + sequenceName
-}
-
-// extractSchemaFromSequenceKey extracts the schema name from a sequence key
-func extractSchemaFromSequenceKey(sequenceKey string) string {
- parts := strings.SplitN(sequenceKey, ".", 2)
- if len(parts) >= 1 {
- return parts[0]
- }
- return "public"
-}
-
-// createSequenceChunk creates a new CREATE SEQUENCE chunk and adds it to the chunks
-func createSequenceChunk(chunks *schema.SDLChunks, sequence *storepb.SequenceMetadata, sequenceKey string) error {
- if sequence == nil || chunks == nil {
- return nil
- }
-
- // Generate sequence SDL using the existing writeSequenceSDL function
- schemaName := extractSchemaFromSequenceKey(sequenceKey)
- sdl := generateCreateSequenceSDL(schemaName, sequence)
- if sdl == "" {
- return errors.Errorf("failed to generate SDL for sequence %s", sequenceKey)
- }
-
- // Parse the SDL to get the AST node
- astNode, err := extractSequenceASTFromSDL(sdl)
- if err != nil {
- return errors.Wrapf(err, "failed to extract AST from generated sequence SDL for %s", sequenceKey)
- }
-
- // Create the chunk
- chunk := &schema.SDLChunk{
- Identifier: sequenceKey,
- ASTNode: astNode,
- }
-
- // Add COMMENT ON SEQUENCE if the sequence has a comment
- if sequence.Comment != "" {
- if err := syncCommentStatements(chunk, sequence, schemaName); err != nil {
- return errors.Wrapf(err, "failed to add COMMENT statements for sequence %s", sequenceKey)
- }
- }
-
- // Ensure Sequences map is initialized
- if chunks.Sequences == nil {
- chunks.Sequences = make(map[string]*schema.SDLChunk)
- }
-
- chunks.Sequences[sequenceKey] = chunk
- return nil
-}
-
-// updateSequenceChunkIfNeeded updates a sequence chunk if the definition has changed
-func updateSequenceChunkIfNeeded(chunks *schema.SDLChunks, currentSequence, previousSequence *storepb.SequenceMetadata, sequenceKey string) error {
- if currentSequence == nil || previousSequence == nil || chunks == nil {
- return nil
- }
-
- // Get the existing chunk
- chunk, exists := chunks.Sequences[sequenceKey]
- if !exists {
- return errors.Errorf("sequence chunk not found for key %s", sequenceKey)
- }
-
- // Check if the CREATE SEQUENCE definition has changed (excluding comment and owner)
- definitionChanged := !sequenceDefinitionsEqualExcludingCommentAndOwner(currentSequence, previousSequence)
-
- if definitionChanged {
- // Sequence definition has changed - regenerate the CREATE SEQUENCE chunk
- schemaName := extractSchemaFromSequenceKey(sequenceKey)
- sdl := generateCreateSequenceSDL(schemaName, currentSequence)
- if sdl == "" {
- return errors.Errorf("failed to generate SDL for sequence %s", sequenceKey)
- }
-
- // Parse the SDL to get the AST node for CREATE SEQUENCE
- astNode, err := extractSequenceASTFromSDL(sdl)
- if err != nil {
- return errors.Wrapf(err, "failed to extract AST from generated sequence SDL for %s", sequenceKey)
- }
-
- // Update the CREATE SEQUENCE AST node
- chunk.ASTNode = astNode
- }
-
- schemaName := extractSchemaFromSequenceKey(sequenceKey)
-
- // Synchronize ALTER SEQUENCE OWNED BY statements only if owner has changed
- ownerChanged := currentSequence.OwnerTable != previousSequence.OwnerTable ||
- currentSequence.OwnerColumn != previousSequence.OwnerColumn
- if ownerChanged {
- if err := syncAlterSequenceStatements(chunk, currentSequence, schemaName); err != nil {
- return errors.Wrapf(err, "failed to sync ALTER statements for sequence %s", sequenceKey)
- }
- }
-
- // Synchronize COMMENT ON SEQUENCE statements only if comment has changed
- if currentSequence.Comment != previousSequence.Comment {
- if err := syncCommentStatements(chunk, currentSequence, schemaName); err != nil {
- return errors.Wrapf(err, "failed to sync COMMENT statements for sequence %s", sequenceKey)
- }
- }
-
- return nil
-}
-
-// updateSequenceChunk updates an existing sequence chunk with new definition
-// This function synchronizes the CREATE SEQUENCE, ALTER SEQUENCE, and COMMENT ON SEQUENCE statements
-// based on the current sequence metadata from the database
-// syncAlterSequenceStatements synchronizes ALTER SEQUENCE OWNED BY statements in the chunk
-// based on the current OwnerTable and OwnerColumn from sequence metadata
-func syncAlterSequenceStatements(chunk *schema.SDLChunk, sequence *storepb.SequenceMetadata, schemaName string) error {
- if chunk == nil || sequence == nil {
- return nil
- }
-
- // Check if sequence has an owner
- hasOwner := sequence.OwnerTable != "" && sequence.OwnerColumn != ""
-
- if hasOwner {
- // Generate ALTER SEQUENCE OWNED BY statement
- alterSDL := fmt.Sprintf("ALTER SEQUENCE \"%s\".\"%s\" OWNED BY \"%s\".\"%s\";",
- schemaName, sequence.Name, sequence.OwnerTable, sequence.OwnerColumn)
-
- // Parse to get AST node
- alterNode, err := extractAlterSequenceASTFromSDL(alterSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse ALTER SEQUENCE statement")
- }
-
- // Replace all existing ALTER statements with the new one
- // (There should only be one ALTER SEQUENCE OWNED BY statement per sequence)
- chunk.AlterStatements = []antlr.ParserRuleContext{alterNode}
- } else {
- // No owner - remove all ALTER SEQUENCE statements
- chunk.AlterStatements = nil
- }
-
- return nil
-}
-
-// syncCommentStatements synchronizes COMMENT ON SEQUENCE statements in the chunk
-// based on the current Comment field from sequence metadata
-func syncCommentStatements(chunk *schema.SDLChunk, sequence *storepb.SequenceMetadata, schemaName string) error {
- if chunk == nil || sequence == nil {
- return nil
- }
-
- // Use the generic comment sync function
- return syncObjectCommentStatements(chunk, sequence.Comment, "SEQUENCE", schemaName, sequence.Name)
-}
-
-// syncObjectCommentStatements is a generic function to synchronize COMMENT statements for any object type
-// objectType should be "SEQUENCE", "TABLE", "VIEW", "FUNCTION", "INDEX", etc.
-func syncObjectCommentStatements(chunk *schema.SDLChunk, comment, objectType, schemaName, objectName string) error {
- if chunk == nil {
- return nil
- }
-
- // Check if object has a comment
- hasComment := comment != ""
-
- if hasComment {
- // Generate COMMENT ON <objectType> statement
- // Escape single quotes in comment text
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- commentSDL := fmt.Sprintf("COMMENT ON %s \"%s\".\"%s\" IS '%s';",
- objectType, schemaName, objectName, escapedComment)
-
- // Parse to get AST node
- commentNode, err := extractCommentASTFromSDL(commentSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse COMMENT ON %s statement", objectType)
- }
-
- // Replace all existing COMMENT statements with the new one
- // (There should only be one COMMENT ON statement per object)
- chunk.CommentStatements = []antlr.ParserRuleContext{commentNode}
- } else {
- // No comment - remove all COMMENT statements
- chunk.CommentStatements = nil
- }
-
- return nil
-}
-
-// extractAlterSequenceASTFromSDL parses an ALTER SEQUENCE SDL and extracts the AST node
-func extractAlterSequenceASTFromSDL(sdl string) (antlr.ParserRuleContext, error) {
- if sdl == "" {
- return nil, errors.New("empty ALTER SEQUENCE SDL provided")
- }
-
- parseResults, err := pgparser.ParsePostgreSQL(sdl)
- if err != nil {
- return nil, errors.Wrap(err, "failed to parse ALTER SEQUENCE SDL")
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return nil, errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- tree := parseResult.Tree
- if tree == nil {
- return nil, errors.New("parse result tree is nil")
- }
-
- // Extract the ALTER SEQUENCE node
- var result *parser.AlterseqstmtContext
- extractor := &alterSequenceExtractor{result: &result}
- antlr.NewParseTreeWalker().Walk(extractor, tree)
-
- if result == nil {
- return nil, errors.New("failed to extract ALTER SEQUENCE AST node from SDL")
- }
-
- return result, nil
-}
-
-// extractCommentASTFromSDL parses a COMMENT ON SDL and extracts the AST node
-func extractCommentASTFromSDL(sdl string) (antlr.ParserRuleContext, error) {
- if sdl == "" {
- return nil, errors.New("empty COMMENT SDL provided")
- }
-
- parseResults, err := pgparser.ParsePostgreSQL(sdl)
- if err != nil {
- return nil, errors.Wrap(err, "failed to parse COMMENT SDL")
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return nil, errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- tree := parseResult.Tree
- if tree == nil {
- return nil, errors.New("parse result tree is nil")
- }
-
- // Extract the COMMENT node
- var result *parser.CommentstmtContext
- extractor := &commentExtractor{result: &result}
- antlr.NewParseTreeWalker().Walk(extractor, tree)
-
- if result == nil {
- return nil, errors.New("failed to extract COMMENT AST node from SDL")
- }
-
- return result, nil
-}
-
-// alterSequenceExtractor extracts ALTER SEQUENCE statement from AST
-type alterSequenceExtractor struct {
- *parser.BasePostgreSQLParserListener
- result **parser.AlterseqstmtContext
-}
-
-func (e *alterSequenceExtractor) EnterAlterseqstmt(ctx *parser.AlterseqstmtContext) {
- if *e.result == nil {
- *e.result = ctx
- }
-}
-
-// commentExtractor extracts COMMENT statement from AST
-type commentExtractor struct {
- *parser.BasePostgreSQLParserListener
- result **parser.CommentstmtContext
-}
-
-func (e *commentExtractor) EnterCommentstmt(ctx *parser.CommentstmtContext) {
- if *e.result == nil {
- *e.result = ctx
- }
-}
-
-// deleteSequenceChunk removes a sequence chunk from the chunks
-func deleteSequenceChunk(chunks *schema.SDLChunks, sequenceKey string) {
- if chunks != nil && chunks.Sequences != nil {
- delete(chunks.Sequences, sequenceKey)
- }
-}
-
-// generateCreateSequenceSDL generates SDL for a CREATE SEQUENCE statement
-func generateCreateSequenceSDL(schemaName string, sequence *storepb.SequenceMetadata) string {
- if sequence == nil {
- return ""
- }
-
- if schemaName == "" {
- schemaName = "public"
- }
-
- var buf strings.Builder
- // Use the existing writeSequenceSDL function
- if err := writeSequenceSDL(&buf, schemaName, sequence); err != nil {
- return ""
- }
-
- return buf.String()
-}
-
-// sequenceDefinitionsEqual compares two sequence definitions to see if they are equivalent
-func sequenceDefinitionsEqual(sequence1, sequence2 *storepb.SequenceMetadata) bool {
- // First check everything except comment and owner
- if !sequenceDefinitionsEqualExcludingCommentAndOwner(sequence1, sequence2) {
- return false
- }
-
- // Then check owner
- if sequence1.OwnerTable != sequence2.OwnerTable ||
- sequence1.OwnerColumn != sequence2.OwnerColumn {
- return false
- }
-
- // Finally check comment
- if sequence1.Comment != sequence2.Comment {
- return false
- }
-
- return true
-}
-
-// sequenceDefinitionsEqualExcludingCommentAndOwner compares two sequence definitions excluding comments and owner
-func sequenceDefinitionsEqualExcludingCommentAndOwner(sequence1, sequence2 *storepb.SequenceMetadata) bool {
- if sequence1 == nil && sequence2 == nil {
- return true
- }
- if sequence1 == nil || sequence2 == nil {
- return false
- }
-
- // Compare sequence names
- if sequence1.Name != sequence2.Name {
- return false
- }
-
- // Compare sequence parameters (excluding OwnerTable, OwnerColumn, and Comment)
- if sequence1.DataType != sequence2.DataType ||
- sequence1.Start != sequence2.Start ||
- sequence1.Increment != sequence2.Increment ||
- sequence1.MaxValue != sequence2.MaxValue ||
- sequence1.MinValue != sequence2.MinValue ||
- sequence1.CacheSize != sequence2.CacheSize ||
- sequence1.Cycle != sequence2.Cycle {
- return false
- }
-
- return true
-}
-
-// extractSequenceASTFromSDL parses a sequence SDL and extracts the CREATE SEQUENCE AST node
-func extractSequenceASTFromSDL(sdl string) (antlr.ParserRuleContext, error) {
- if sdl == "" {
- return nil, errors.New("empty SDL provided")
- }
-
- // Parse the SDL to get AST
- parseResults, err := pgparser.ParsePostgreSQL(sdl)
- if err != nil {
- return nil, errors.Wrap(err, "failed to parse sequence SDL")
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return nil, errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- tree := parseResult.Tree
-
- // Extract the CREATE SEQUENCE node using a walker
- var result *parser.CreateseqstmtContext
- extractor := &sequenceExtractor{result: &result}
- antlr.NewParseTreeWalker().Walk(extractor, tree)
-
- if result == nil {
- return nil, errors.New("no CREATE SEQUENCE statement found in SDL")
- }
-
- return result, nil
-}
-
-// extractSequenceTextFromAST extracts normalized text from sequence AST node using token stream
-func extractSequenceTextFromAST(sequenceAST *parser.CreateseqstmtContext) string {
- if sequenceAST == nil {
- return ""
- }
-
- // Get tokens from the parser
- if parser := sequenceAST.GetParser(); parser != nil {
- if tokenStream := parser.GetTokenStream(); tokenStream != nil {
- start := sequenceAST.GetStart()
- stop := sequenceAST.GetStop()
- if start != nil && stop != nil {
- return tokenStream.GetTextFromTokens(start, stop)
- }
- }
- }
-
- // Fallback to GetText() if tokens are not available
- return sequenceAST.GetText()
-}
-
-// sequenceExtractor is a walker to extract CREATE SEQUENCE AST nodes
-type sequenceExtractor struct {
- parser.BasePostgreSQLParserListener
- result **parser.CreateseqstmtContext
-}
-
-func (e *sequenceExtractor) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext) {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
-}
-
-// processCommentChanges processes comment changes for all database objects
-// It must be called after all object changes have been processed to determine
-// which objects were created or dropped (those should not generate comment diffs)
-
-// applyViewChangesToChunks applies minimal changes to CREATE VIEW chunks
-// This handles creation, modification, and deletion of view statements
-
-// applyMaterializedViewChangesToChunks applies minimal changes to materialized view chunks based on schema metadata
-func applyMaterializedViewChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get materialized view differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build materialized view maps for current and previous schemas
- currentMaterializedViews := make(map[string]*storepb.MaterializedViewMetadata)
- previousMaterializedViews := make(map[string]*storepb.MaterializedViewMetadata)
-
- // Collect all materialized views from current schema
- for _, schema := range currentMetadata.Schemas {
- for _, mv := range schema.MaterializedViews {
- mvKey := formatViewKey(schema.Name, mv.Name)
- currentMaterializedViews[mvKey] = mv
- }
- }
-
- // Collect all materialized views from previous schema
- for _, schema := range previousMetadata.Schemas {
- for _, mv := range schema.MaterializedViews {
- mvKey := formatViewKey(schema.Name, mv.Name)
- previousMaterializedViews[mvKey] = mv
- }
- }
-
- // Process materialized view additions: create new materialized view chunks
- for mvKey, currentMV := range currentMaterializedViews {
- if _, exists := previousMaterializedViews[mvKey]; !exists {
- // New materialized view - create a chunk for it
- err := createMaterializedViewChunk(previousChunks, currentMV, mvKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create materialized view chunk for %s", mvKey)
- }
- }
- }
-
- // Process materialized view modifications: update existing chunks
- for mvKey, currentMV := range currentMaterializedViews {
- if previousMV, exists := previousMaterializedViews[mvKey]; exists {
- // Materialized view exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- if _, chunkExists := previousChunks.MaterializedViews[mvKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateMaterializedViewChunkIfNeeded(previousChunks, currentMV, previousMV, mvKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update materialized view chunk for %s", mvKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this materialized view in SDL
- }
- }
-
- // Process materialized view deletions: remove dropped materialized view chunks
- for mvKey := range previousMaterializedViews {
- if _, exists := currentMaterializedViews[mvKey]; !exists {
- // Materialized view was dropped - remove it from chunks
- deleteMaterializedViewChunk(previousChunks, mvKey)
- }
- }
-
- return nil
-}
-
-// createMaterializedViewChunk creates a new CREATE MATERIALIZED VIEW chunk and adds it to the chunks
-func createMaterializedViewChunk(chunks *schema.SDLChunks, mv *storepb.MaterializedViewMetadata, mvKey string) error {
- if mv == nil || chunks == nil {
- return nil
- }
-
- // Generate SDL text for the materialized view
- schemaName, _ := parseIdentifier(mvKey)
- mvSDL := generateCreateMaterializedViewSDL(schemaName, mv)
- if mvSDL == "" {
- return errors.New("failed to generate SDL for materialized view")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(mvSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated materialized view SDL: %s", mvSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE MATERIALIZED VIEW AST node
- var mvASTNode *parser.CreatematviewstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&materializedViewExtractor{
- result: &mvASTNode,
- }, parseResult.Tree)
-
- if mvASTNode == nil {
- return errors.New("failed to extract CREATE MATERIALIZED VIEW AST node")
- }
-
- // Create and add the chunk
- chunk := &schema.SDLChunk{
- Identifier: mvKey,
- ASTNode: mvASTNode,
- }
-
- // Add comment if the materialized view has one
- if mv.Comment != "" {
- commentSQL := generateCommentOnMaterializedViewSQL(schemaName, mv.Name, mv.Comment)
- commentParseResult, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil && len(commentParseResult) > 0 && commentParseResult[0].Tree != nil {
- // Extract COMMENT ON MATERIALIZED VIEW AST node
- var commentASTNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentASTNode,
- }, commentParseResult[0].Tree)
-
- if commentASTNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentASTNode}
- }
- }
- }
-
- if chunks.MaterializedViews == nil {
- chunks.MaterializedViews = make(map[string]*schema.SDLChunk)
- }
- chunks.MaterializedViews[mvKey] = chunk
-
- return nil
-}
-
-// updateMaterializedViewChunkIfNeeded updates an existing materialized view chunk if the definition has changed
-func updateMaterializedViewChunkIfNeeded(chunks *schema.SDLChunks, currentMV, previousMV *storepb.MaterializedViewMetadata, mvKey string) error {
- if currentMV == nil || previousMV == nil || chunks == nil {
- return nil
- }
-
- // Get the existing chunk
- chunk, exists := chunks.MaterializedViews[mvKey]
- if !exists {
- return errors.Errorf("materialized view chunk not found for key %s", mvKey)
- }
-
- // Check if the materialized view definition has changed
- if currentMV.Definition != previousMV.Definition {
- // Materialized view definition changed - regenerate the chunk
- schemaName, _ := parseIdentifier(mvKey)
- mvSDL := generateCreateMaterializedViewSDL(schemaName, currentMV)
- if mvSDL == "" {
- return errors.New("failed to generate SDL for materialized view")
- }
-
- // Parse the new SDL to get a fresh AST node
- parseResults, err := pgparser.ParsePostgreSQL(mvSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated materialized view SDL: %s", mvSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE MATERIALIZED VIEW AST node
- var mvASTNode *parser.CreatematviewstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&materializedViewExtractor{
- result: &mvASTNode,
- }, parseResult.Tree)
-
- if mvASTNode == nil {
- return errors.New("failed to extract CREATE MATERIALIZED VIEW AST node")
- }
-
- // Update the chunk's AST node
- chunk.ASTNode = mvASTNode
- }
-
- // Handle comment changes independently of definition changes
- if currentMV.Comment != previousMV.Comment {
- schemaName, _ := parseIdentifier(mvKey)
- if currentMV.Comment != "" {
- // New or updated comment
- commentSQL := generateCommentOnMaterializedViewSQL(schemaName, currentMV.Name, currentMV.Comment)
- commentParseResult, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil && len(commentParseResult) > 0 && commentParseResult[0].Tree != nil {
- // Extract COMMENT ON MATERIALIZED VIEW AST node
- var commentASTNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentASTNode,
- }, commentParseResult[0].Tree)
-
- if commentASTNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentASTNode}
- }
- }
- } else {
- // Comment was removed
- chunk.CommentStatements = nil
- }
- }
-
- return nil
-}
-
-// deleteMaterializedViewChunk removes a materialized view chunk from the chunks
-func deleteMaterializedViewChunk(chunks *schema.SDLChunks, mvKey string) {
- if chunks != nil && chunks.MaterializedViews != nil {
- delete(chunks.MaterializedViews, mvKey)
- }
-}
-
-// generateCreateMaterializedViewSDL generates the SDL text for a CREATE MATERIALIZED VIEW statement
-func generateCreateMaterializedViewSDL(schemaName string, mv *storepb.MaterializedViewMetadata) string {
- if mv == nil {
- return ""
- }
-
- var buf strings.Builder
- if err := writeMaterializedViewSDL(&buf, schemaName, mv); err != nil {
- return ""
- }
-
- return buf.String()
-}
-
-// generateCommentOnMaterializedViewSQL generates a COMMENT ON MATERIALIZED VIEW statement
-func generateCommentOnMaterializedViewSQL(schemaName, mvName, comment string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- // Escape single quotes in comment
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- return fmt.Sprintf("COMMENT ON MATERIALIZED VIEW \"%s\".\"%s\" IS '%s';", schemaName, mvName, escapedComment)
-}
-
-// applyEnumTypeChangesToChunks applies minimal changes to enum type chunks based on schema metadata
-func applyEnumTypeChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get enum type differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build enum type maps for current and previous schemas
- currentEnumTypes := make(map[string]*storepb.EnumTypeMetadata)
- previousEnumTypes := make(map[string]*storepb.EnumTypeMetadata)
-
- // Collect all enum types from current schema
- for _, schema := range currentMetadata.Schemas {
- for _, enumType := range schema.EnumTypes {
- enumKey := schema.Name + "." + enumType.Name
- currentEnumTypes[enumKey] = enumType
- }
- }
-
- // Collect all enum types from previous schema
- for _, schema := range previousMetadata.Schemas {
- for _, enumType := range schema.EnumTypes {
- enumKey := schema.Name + "." + enumType.Name
- previousEnumTypes[enumKey] = enumType
- }
- }
-
- // Process enum type additions: create new enum type chunks
- for enumKey, currentEnum := range currentEnumTypes {
- if _, exists := previousEnumTypes[enumKey]; !exists {
- // New enum type - create a chunk for it
- err := createEnumTypeChunk(previousChunks, currentEnum, enumKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create enum type chunk for %s", enumKey)
- }
- }
- }
-
- // Process enum type modifications: update existing chunks
- for enumKey, currentEnum := range currentEnumTypes {
- if previousEnum, exists := previousEnumTypes[enumKey]; exists {
- // Enum type exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- if _, chunkExists := previousChunks.EnumTypes[enumKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateEnumTypeChunkIfNeeded(previousChunks, currentEnum, previousEnum, enumKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update enum type chunk for %s", enumKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this enum type in SDL
- }
- }
-
- // Process enum type deletions: remove dropped enum type chunks
- for enumKey := range previousEnumTypes {
- if _, exists := currentEnumTypes[enumKey]; !exists {
- // Enum type was dropped - remove it from chunks
- deleteEnumTypeChunk(previousChunks, enumKey)
- }
- }
-
- return nil
-}
-
-// createEnumTypeChunk creates a new CREATE TYPE AS ENUM chunk and adds it to the chunks
-func createEnumTypeChunk(chunks *schema.SDLChunks, enumType *storepb.EnumTypeMetadata, enumKey string) error {
- if enumType == nil || chunks == nil {
- return nil
- }
-
- // Generate SDL text for the enum type
- schemaName, _ := parseIdentifier(enumKey)
- enumSDL := generateCreateEnumTypeSDL(schemaName, enumType)
- if enumSDL == "" {
- return errors.New("failed to generate SDL for enum type")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(enumSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated enum type SDL: %s", enumSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE TYPE AS ENUM AST node
- var enumASTNode *parser.DefinestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&enumTypeExtractor{
- result: &enumASTNode,
- }, parseResult.Tree)
-
- if enumASTNode == nil {
- return errors.New("failed to extract CREATE TYPE AS ENUM AST node")
- }
-
- // Create and add the chunk
- chunk := &schema.SDLChunk{
- Identifier: enumKey,
- ASTNode: enumASTNode,
- }
-
- // Handle comment if present
- if len(enumType.Comment) > 0 {
- commentSQL := generateCommentOnTypeSQL(schemaName, enumType.Name, enumType.Comment)
- commentParseResult, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil {
- var commentNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentNode,
- }, commentParseResult[0].Tree)
- if commentNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentNode}
- }
- }
- }
-
- chunks.EnumTypes[enumKey] = chunk
- return nil
-}
-
-// updateEnumTypeChunkIfNeeded updates an enum type chunk if the definition or comment changed
-func updateEnumTypeChunkIfNeeded(chunks *schema.SDLChunks, currentEnum, previousEnum *storepb.EnumTypeMetadata, enumKey string) error {
- if currentEnum == nil || previousEnum == nil {
- return nil
- }
-
- chunk, exists := chunks.EnumTypes[enumKey]
- if !exists {
- return errors.Errorf("enum type chunk not found for key %s", enumKey)
- }
-
- // Check if the enum definition has changed (values changed)
- definitionChanged := !enumTypesEqual(currentEnum, previousEnum)
-
- if definitionChanged {
- // Enum definition has changed - regenerate the CREATE TYPE chunk
- schemaName, _ := parseIdentifier(enumKey)
- enumSDL := generateCreateEnumTypeSDL(schemaName, currentEnum)
- if enumSDL == "" {
- return errors.New("failed to generate SDL for enum type")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(enumSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated enum type SDL: %s", enumSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE TYPE AS ENUM AST node
- var enumASTNode *parser.DefinestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&enumTypeExtractor{
- result: &enumASTNode,
- }, parseResult.Tree)
-
- if enumASTNode == nil {
- return errors.New("failed to extract CREATE TYPE AS ENUM AST node")
- }
-
- // Update the CREATE TYPE AST node
- chunk.ASTNode = enumASTNode
- }
-
- // Synchronize COMMENT ON TYPE statements only if comment has changed
- if currentEnum.Comment != previousEnum.Comment {
- schemaName, _ := parseIdentifier(enumKey)
- if err := syncObjectCommentStatements(chunk, currentEnum.Comment, "TYPE", schemaName, currentEnum.Name); err != nil {
- return errors.Wrapf(err, "failed to sync COMMENT statements for enum type %s", enumKey)
- }
- }
-
- return nil
-}
-
-// deleteEnumTypeChunk removes an enum type chunk from the chunks
-func deleteEnumTypeChunk(chunks *schema.SDLChunks, enumKey string) {
- if chunks != nil && chunks.EnumTypes != nil {
- delete(chunks.EnumTypes, enumKey)
- }
-}
-
-// enumTypesEqual compares two enum type definitions excluding comments
-func enumTypesEqual(enum1, enum2 *storepb.EnumTypeMetadata) bool {
- if enum1 == nil || enum2 == nil {
- return false
- }
-
- // Compare name
- if enum1.Name != enum2.Name {
- return false
- }
-
- // Compare values
- if len(enum1.Values) != len(enum2.Values) {
- return false
- }
- for i, v1 := range enum1.Values {
- if v1 != enum2.Values[i] {
- return false
- }
- }
-
- return true
-}
-
-// generateCreateEnumTypeSDL generates the SDL text for a CREATE TYPE AS ENUM statement
-func generateCreateEnumTypeSDL(schemaName string, enumType *storepb.EnumTypeMetadata) string {
- if enumType == nil {
- return ""
- }
-
- var buf strings.Builder
- if err := writeEnum(&buf, schemaName, enumType); err != nil {
- return ""
- }
- buf.WriteString(";")
-
- return buf.String()
-}
-
-// generateCommentOnTypeSQL generates a COMMENT ON TYPE statement
-func generateCommentOnTypeSQL(schemaName, typeName, comment string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- // Escape single quotes in comment
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- return fmt.Sprintf("COMMENT ON TYPE \"%s\".\"%s\" IS '%s';", schemaName, typeName, escapedComment)
-}
-
-// enumTypeExtractor is a walker to extract CREATE TYPE AS ENUM AST nodes
-type enumTypeExtractor struct {
- parser.BasePostgreSQLParserListener
- result **parser.DefinestmtContext
-}
-
-func (e *enumTypeExtractor) EnterDefinestmt(ctx *parser.DefinestmtContext) {
- // Only extract CREATE TYPE AS ENUM statements
- if ctx.CREATE() != nil && ctx.TYPE_P() != nil && ctx.AS() != nil && ctx.ENUM_P() != nil {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
- }
-}
-
-// materializedViewExtractor is a walker to extract CREATE MATERIALIZED VIEW AST nodes
-type materializedViewExtractor struct {
- parser.BasePostgreSQLParserListener
- result **parser.CreatematviewstmtContext
-}
-
-func (e *materializedViewExtractor) EnterCreatematviewstmt(ctx *parser.CreatematviewstmtContext) {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
-}
-
-// applyColumnCommentChanges applies minimal changes to column comments based on schema metadata
-// This function only updates COMMENT ON COLUMN statements without modifying CREATE TABLE statements
-func applyColumnCommentChanges(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get table metadata from schemas
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build table maps for current and previous schemas
- currentTables := make(map[string]*storepb.TableMetadata)
- previousTables := make(map[string]*storepb.TableMetadata)
-
- // Collect all tables from current schema
- for _, schema := range currentMetadata.Schemas {
- schemaName := schema.Name
- if schemaName == "" {
- schemaName = "public"
- }
- for _, table := range schema.Tables {
- tableKey := schemaName + "." + table.Name
- currentTables[tableKey] = table
- }
- }
-
- // Collect all tables from previous schema
- for _, schema := range previousMetadata.Schemas {
- schemaName := schema.Name
- if schemaName == "" {
- schemaName = "public"
- }
- for _, table := range schema.Tables {
- tableKey := schemaName + "." + table.Name
- previousTables[tableKey] = table
- }
- }
-
- // Initialize ColumnComments map if needed
- if previousChunks.ColumnComments == nil {
- previousChunks.ColumnComments = make(map[string]map[string]antlr.ParserRuleContext)
- }
-
- // Process tables that exist in both schemas
- for tableKey, currentTable := range currentTables {
- previousTable, exists := previousTables[tableKey]
- if !exists {
- // Table is new, skip (will be handled by table creation)
- continue
- }
-
- // Build column maps
- currentColumns := make(map[string]*storepb.ColumnMetadata)
- previousColumns := make(map[string]*storepb.ColumnMetadata)
-
- for _, col := range currentTable.Columns {
- currentColumns[col.Name] = col
- }
- for _, col := range previousTable.Columns {
- previousColumns[col.Name] = col
- }
-
- // Process columns that exist in both versions
- for columnName, currentColumn := range currentColumns {
- previousColumn, colExists := previousColumns[columnName]
- if !colExists {
- // Column is new, skip (will be handled by column addition)
- continue
- }
-
- // Check if comment has changed
- if currentColumn.Comment != previousColumn.Comment {
- err := syncColumnComment(previousChunks, tableKey, columnName, currentColumn.Comment)
- if err != nil {
- return errors.Wrapf(err, "failed to sync comment for column %s.%s", tableKey, columnName)
- }
- }
- }
-
- // Process columns that were dropped - remove their comments
- for columnName := range previousColumns {
- if _, exists := currentColumns[columnName]; !exists {
- // Column was dropped - remove its comment
- if previousChunks.ColumnComments[tableKey] != nil {
- delete(previousChunks.ColumnComments[tableKey], columnName)
- if len(previousChunks.ColumnComments[tableKey]) == 0 {
- delete(previousChunks.ColumnComments, tableKey)
- }
- }
- }
- }
- }
-
- return nil
-}
-
-// syncColumnComment synchronizes a single column comment in the chunks
-func syncColumnComment(chunks *schema.SDLChunks, tableKey, columnName, comment string) error {
- if chunks == nil {
- return nil
- }
-
- // Parse table key to get schema and table names
- schemaName, tableName := parseIdentifier(tableKey)
-
- // If comment is empty, remove the comment statement
- if comment == "" {
- if chunks.ColumnComments[tableKey] != nil {
- delete(chunks.ColumnComments[tableKey], columnName)
- if len(chunks.ColumnComments[tableKey]) == 0 {
- delete(chunks.ColumnComments, tableKey)
- }
- }
- return nil
- }
-
- // Generate COMMENT ON COLUMN statement
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- commentSDL := fmt.Sprintf("COMMENT ON COLUMN \"%s\".\"%s\".\"%s\" IS '%s';",
- schemaName, tableName, columnName, escapedComment)
-
- // Parse the SDL to get AST node
- commentNode, err := extractCommentASTFromSDL(commentSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse column comment SDL: %s", commentSDL)
- }
-
- // Initialize maps if needed
- if chunks.ColumnComments == nil {
- chunks.ColumnComments = make(map[string]map[string]antlr.ParserRuleContext)
- }
- if chunks.ColumnComments[tableKey] == nil {
- chunks.ColumnComments[tableKey] = make(map[string]antlr.ParserRuleContext)
- }
-
- // Update the comment node
- chunks.ColumnComments[tableKey][columnName] = commentNode
-
- return nil
+// extractForeignKeyDefinitionsWithAST extracts foreign key constraint definitions with their AST nodes
+// Note: This is a wrapper around the existing function with a different name for clarity
+func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*ForeignKeyDefWithAST {
+ return extractForeignKeyDefinitionsInOrder(createStmt)
}
-// processEnumTypeChanges analyzes enum type changes between current and previous chunks
-// Enum types use DROP + CREATE pattern for modifications (PostgreSQL doesn't support ALTER TYPE ... RENAME VALUE)
-
-// processExtensionChanges processes extension changes between current and previous chunks
-
-// processEventTriggerChanges processes event trigger changes between current and previous chunks
-
-// processSchemaChanges processes explicit CREATE SCHEMA statements in the SDL
-
-// applyExtensionChangesToChunks applies minimal changes to extension chunks based on schema differences
-// Extensions are database-level objects (not schema-scoped)
-func applyExtensionChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get extension differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build extension maps for current and previous schemas
- // Extensions are database-level, stored directly in DatabaseSchemaMetadata
- currentExtensions := make(map[string]*storepb.ExtensionMetadata)
- previousExtensions := make(map[string]*storepb.ExtensionMetadata)
-
- // Collect all extensions from current schema
- for _, extension := range currentMetadata.Extensions {
- // Extension key is just the name (database-level, no schema prefix)
- currentExtensions[extension.Name] = extension
- }
-
- // Collect all extensions from previous schema
- for _, extension := range previousMetadata.Extensions {
- previousExtensions[extension.Name] = extension
- }
-
- // Process extension additions: create new extension chunks
- for extensionName, currentExtension := range currentExtensions {
- if _, exists := previousExtensions[extensionName]; !exists {
- // New extension - create a chunk for it
- err := createExtensionChunk(previousChunks, currentExtension)
- if err != nil {
- return errors.Wrapf(err, "failed to create extension chunk for %s", extensionName)
- }
- }
- }
-
- // Process extension modifications: update existing chunks
- for extensionName, currentExtension := range currentExtensions {
- if previousExtension, exists := previousExtensions[extensionName]; exists {
- // Extension exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- if _, chunkExists := previousChunks.Extensions[extensionName]; chunkExists {
- // Chunk exists - update if needed
- err := updateExtensionChunkIfNeeded(previousChunks, currentExtension, previousExtension)
- if err != nil {
- return errors.Wrapf(err, "failed to update extension chunk for %s", extensionName)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this extension in SDL
- }
- }
-
- // Process extension deletions: remove dropped extension chunks
- for extensionName := range previousExtensions {
- if _, exists := currentExtensions[extensionName]; !exists {
- // Extension was dropped - remove it from chunks
- deleteExtensionChunk(previousChunks, extensionName)
- }
- }
-
- return nil
+// PrimaryKeyDefWithAST represents a primary key constraint definition with its AST node
+type PrimaryKeyDefWithAST struct {
+ Name string
+ ASTNode parser.ITableconstraintContext
}
-// createExtensionChunk creates a new CREATE EXTENSION chunk and adds it to the chunks
-func createExtensionChunk(chunks *schema.SDLChunks, extension *storepb.ExtensionMetadata) error {
- if extension == nil || chunks == nil {
- return nil
- }
-
- // Generate SDL text for the extension
- extensionSDL := generateCreateExtensionSQL(extension)
- if extensionSDL == "" {
- return errors.New("failed to generate SDL for extension")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(extensionSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated extension SDL: %s", extensionSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE EXTENSION AST node
- var extensionASTNode *parser.CreateextensionstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&extensionExtractor{
- result: &extensionASTNode,
- }, parseResult.Tree)
-
- if extensionASTNode == nil {
- return errors.New("failed to extract CREATE EXTENSION AST node")
- }
-
- // Create and add the chunk
- chunk := &schema.SDLChunk{
- Identifier: extension.Name, // Extensions are database-level, no schema prefix
- ASTNode: extensionASTNode,
- }
-
- // Handle comment if present (description field is the comment)
- if len(extension.Description) > 0 {
- commentSQL := generateCommentOnExtensionSQL(extension.Name, extension.Description)
- commentParseResult, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil {
- var commentNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentNode,
- }, commentParseResult[0].Tree)
- if commentNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentNode}
- }
- }
- }
-
- chunks.Extensions[extension.Name] = chunk
- return nil
+// UniqueKeyDefWithAST represents a unique key constraint definition with its AST node
+type UniqueKeyDefWithAST struct {
+ Name string
+ ASTNode parser.ITableconstraintContext
}
-// updateExtensionChunkIfNeeded updates an extension chunk if the definition or comment changed
-func updateExtensionChunkIfNeeded(chunks *schema.SDLChunks, currentExtension, previousExtension *storepb.ExtensionMetadata) error {
- if currentExtension == nil || previousExtension == nil {
- return nil
- }
-
- chunk, exists := chunks.Extensions[currentExtension.Name]
- if !exists {
- return errors.Errorf("extension chunk not found for %s", currentExtension.Name)
- }
-
- // Check if the extension definition has changed (schema, version, or description)
- definitionChanged := !extensionsEqual(currentExtension, previousExtension)
-
- if definitionChanged {
- // Extension definition has changed - regenerate the CREATE EXTENSION chunk
- extensionSDL := generateCreateExtensionSQL(currentExtension)
- if extensionSDL == "" {
- return errors.New("failed to generate SDL for extension")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(extensionSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated extension SDL: %s", extensionSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE EXTENSION AST node
- var extensionASTNode *parser.CreateextensionstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&extensionExtractor{
- result: &extensionASTNode,
- }, parseResult.Tree)
-
- if extensionASTNode == nil {
- return errors.New("failed to extract CREATE EXTENSION AST node")
- }
-
- // Update the AST node in the chunk
- chunk.ASTNode = extensionASTNode
- }
-
- // Handle comment changes (description field)
- commentChanged := currentExtension.Description != previousExtension.Description
-
- if commentChanged {
- // Remove old comment statements
- chunk.CommentStatements = nil
-
- // Add new comment if present
- if len(currentExtension.Description) > 0 {
- commentSQL := generateCommentOnExtensionSQL(currentExtension.Name, currentExtension.Description)
- commentParseResult, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil {
- var commentNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentNode,
- }, commentParseResult[0].Tree)
- if commentNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentNode}
- }
- }
- }
+// extractFunctionSignatureFromAST extracts function signature from CREATE FUNCTION AST node
+// This is the unified function used by both chunk extraction and function comparison
+func extractFunctionSignatureFromAST(ctx *parser.CreatefunctionstmtContext) string {
+ if ctx == nil {
+ return ""
}
- return nil
-}
-
-// deleteExtensionChunk removes an extension chunk from the chunks map
-func deleteExtensionChunk(chunks *schema.SDLChunks, extensionName string) {
- if chunks == nil {
- return
+ funcNameCtx := ctx.Func_name()
+ if funcNameCtx == nil {
+ return ""
}
- delete(chunks.Extensions, extensionName)
-}
-// generateCreateExtensionSQL generates a CREATE EXTENSION IF NOT EXISTS statement
-func generateCreateExtensionSQL(extension *storepb.ExtensionMetadata) string {
- if extension == nil {
+ // Extract function name using proper normalization
+ funcNameParts := pgparser.NormalizePostgreSQLFuncName(funcNameCtx)
+ if len(funcNameParts) == 0 {
return ""
}
- var buf strings.Builder
- buf.WriteString(`CREATE EXTENSION IF NOT EXISTS "`)
- buf.WriteString(extension.Name)
- buf.WriteString(`"`)
-
- // Add WITH SCHEMA clause if schema is specified
- if extension.Schema != "" {
- buf.WriteString(` WITH SCHEMA "`)
- buf.WriteString(extension.Schema)
- buf.WriteString(`"`)
+ // Get the function name (without schema)
+ var functionName string
+ if len(funcNameParts) == 2 {
+ // Schema qualified: schema.function_name
+ functionName = funcNameParts[1]
+ } else if len(funcNameParts) == 1 {
+ // Unqualified: function_name
+ functionName = funcNameParts[0]
+ } else {
+ // Unexpected format
+ return ""
}
- // Add VERSION clause if version is specified
- if extension.Version != "" {
- buf.WriteString(` VERSION '`)
- buf.WriteString(extension.Version)
- buf.WriteString(`'`)
+ if functionName == "" {
+ return ""
}
- buf.WriteString(`;`)
-
- return buf.String()
-}
-
-// generateCommentOnExtensionSQL generates a COMMENT ON EXTENSION statement
-func generateCommentOnExtensionSQL(extensionName, comment string) string {
- // Escape single quotes in comment
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- return fmt.Sprintf("COMMENT ON EXTENSION \"%s\" IS '%s';", extensionName, escapedComment)
+ // Use the existing ExtractFunctionSignature function
+ return ExtractFunctionSignature(ctx, functionName)
}
-// extensionExtractor is a walker to extract CREATE EXTENSION AST nodes
-type extensionExtractor struct {
+// functionExtractor is a walker to extract CREATE FUNCTION AST nodes
+type functionExtractor struct {
parser.BasePostgreSQLParserListener
- result **parser.CreateextensionstmtContext
+ result **parser.CreatefunctionstmtContext
}
-func (e *extensionExtractor) EnterCreateextensionstmt(ctx *parser.CreateextensionstmtContext) {
- if e.result != nil {
+func (e *functionExtractor) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {
+ if e.result != nil && *e.result == nil {
*e.result = ctx
}
}
-// extensionsEqual compares two extension metadata for equality (excluding comments)
-func extensionsEqual(a, b *storepb.ExtensionMetadata) bool {
- if a == nil && b == nil {
- return true
- }
- if a == nil || b == nil {
- return false
- }
+// processCommentChanges processes comment changes for all database objects
+// It must be called after all object changes have been processed to determine
+// which objects were created or dropped (those should not generate comment diffs)
- return a.Name == b.Name &&
- a.Schema == b.Schema &&
- a.Version == b.Version &&
- a.Description == b.Description
-}
+// processEnumTypeChanges analyzes enum type changes between current and previous chunks
+// Enum types use DROP + CREATE pattern for modifications (PostgreSQL doesn't support ALTER TYPE ... RENAME VALUE)
+
+// processExtensionChanges processes extension changes between current and previous chunks
+
+// processEventTriggerChanges processes event trigger changes between current and previous chunks
// extractTableNameFromTrigger extracts the fully qualified table name from CREATE TRIGGER ... ON table
// Returns schema.table format, defaulting to public schema if not specified
@@ -3966,293 +517,3 @@ func extractTableNameFromTrigger(ctx *parser.CreatetrigstmtContext) string {
// Schema is specified
return strings.Join(qualifiedNameParts, ".")
}
-
-// applyTriggerChangesToChunks applies minimal changes to trigger chunks based on schema metadata
-func applyTriggerChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get trigger differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build trigger maps for current and previous schemas
- // Key format: schema.table.trigger_name (table-scoped)
- currentTriggers := make(map[string]*triggerWithContext)
- previousTriggers := make(map[string]*triggerWithContext)
-
- // Collect all triggers from current schema
- for _, schemaObj := range currentMetadata.Schemas {
- schemaName := schemaObj.Name
- if schemaName == "" {
- schemaName = "public"
- }
- for _, table := range schemaObj.Tables {
- for _, trigger := range table.Triggers {
- // Use table-scoped identifier: schema.table.trigger_name
- triggerKey := schemaName + "." + table.Name + "." + trigger.Name
- currentTriggers[triggerKey] = &triggerWithContext{
- trigger: trigger,
- schemaName: schemaName,
- tableName: table.Name,
- }
- }
- }
- }
-
- // Collect all triggers from previous schema
- for _, schemaObj := range previousMetadata.Schemas {
- schemaName := schemaObj.Name
- if schemaName == "" {
- schemaName = "public"
- }
- for _, table := range schemaObj.Tables {
- for _, trigger := range table.Triggers {
- // Use table-scoped identifier: schema.table.trigger_name
- triggerKey := schemaName + "." + table.Name + "." + trigger.Name
- previousTriggers[triggerKey] = &triggerWithContext{
- trigger: trigger,
- schemaName: schemaName,
- tableName: table.Name,
- }
- }
- }
- }
-
- // Process trigger additions: create new trigger chunks
- for triggerKey, currentTrigger := range currentTriggers {
- if _, exists := previousTriggers[triggerKey]; !exists {
- // New trigger - create a chunk for it
- err := createTriggerChunk(previousChunks, currentTrigger, triggerKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create trigger chunk for %s", triggerKey)
- }
- }
- }
-
- // Process trigger modifications: update existing chunks
- for triggerKey, currentTrigger := range currentTriggers {
- if previousTrigger, exists := previousTriggers[triggerKey]; exists {
- // Trigger exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- // If chunk doesn't exist, skip - we don't force-add database objects that user didn't define
- if _, chunkExists := previousChunks.Triggers[triggerKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateTriggerChunkIfNeeded(previousChunks, currentTrigger, previousTrigger, triggerKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update trigger chunk for %s", triggerKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this trigger in SDL
- }
- }
-
- // Process trigger deletions: remove dropped trigger chunks
- for triggerKey := range previousTriggers {
- if _, exists := currentTriggers[triggerKey]; !exists {
- // Trigger was dropped - remove it from chunks
- deleteTriggerChunk(previousChunks, triggerKey)
- }
- }
-
- return nil
-}
-
-// triggerWithContext holds trigger metadata with its schema and table context
-type triggerWithContext struct {
- trigger *storepb.TriggerMetadata
- schemaName string
- tableName string
-}
-
-// createTriggerChunk creates a new CREATE TRIGGER chunk and adds it to the chunks
-func createTriggerChunk(chunks *schema.SDLChunks, triggerCtx *triggerWithContext, triggerKey string) error {
- if triggerCtx == nil || triggerCtx.trigger == nil || chunks == nil {
- return nil
- }
-
- trigger := triggerCtx.trigger
- schemaName := triggerCtx.schemaName
- tableName := triggerCtx.tableName
-
- // Generate SDL text for the trigger
- triggerSDL := generateCreateTriggerSDL(schemaName, tableName, trigger)
- if triggerSDL == "" {
- return errors.New("failed to generate SDL for trigger")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(triggerSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated trigger SDL: %s", triggerSDL)
- }
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE TRIGGER AST node
- var triggerASTNode *parser.CreatetrigstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&triggerExtractor{
- result: &triggerASTNode,
- }, parseResult.Tree)
-
- if triggerASTNode == nil {
- return errors.New("failed to extract CREATE TRIGGER AST node")
- }
-
- // Create and add the chunk
- chunk := &schema.SDLChunk{
- Identifier: triggerKey,
- ASTNode: triggerASTNode,
- }
-
- // Add comment if the trigger has one
- if trigger.Comment != "" {
- commentSQL := generateCommentOnTriggerSQL(schemaName, tableName, trigger.Name, trigger.Comment)
- commentParseResults, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil && len(commentParseResults) > 0 && commentParseResults[0].Tree != nil {
- commentParseResult := commentParseResults[0]
- // Extract COMMENT ON TRIGGER AST node
- var commentASTNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentASTNode,
- }, commentParseResult.Tree)
-
- if commentASTNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentASTNode}
- }
- }
- }
-
- if chunks.Triggers == nil {
- chunks.Triggers = make(map[string]*schema.SDLChunk)
- }
- chunks.Triggers[triggerKey] = chunk
-
- return nil
-}
-
-// updateTriggerChunkIfNeeded updates an existing trigger chunk if the definition has changed
-func updateTriggerChunkIfNeeded(chunks *schema.SDLChunks, currentTriggerCtx, previousTriggerCtx *triggerWithContext, triggerKey string) error {
- if currentTriggerCtx == nil || previousTriggerCtx == nil || chunks == nil {
- return nil
- }
-
- currentTrigger := currentTriggerCtx.trigger
- previousTrigger := previousTriggerCtx.trigger
- schemaName := currentTriggerCtx.schemaName
- tableName := currentTriggerCtx.tableName
-
- // Get the existing chunk
- chunk, exists := chunks.Triggers[triggerKey]
- if !exists {
- return errors.Errorf("trigger chunk not found for key %s", triggerKey)
- }
-
- // Check if the trigger definition has changed
- // Trigger.Body contains the complete CREATE TRIGGER statement
- if currentTrigger.Body != previousTrigger.Body {
- // Trigger definition changed - regenerate the chunk
- triggerSDL := generateCreateTriggerSDL(schemaName, tableName, currentTrigger)
- if triggerSDL == "" {
- return errors.New("failed to generate SDL for trigger")
- }
-
- // Parse the new SDL to get a fresh AST node
- parseResults, err := pgparser.ParsePostgreSQL(triggerSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated trigger SDL: %s", triggerSDL)
- }
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE TRIGGER AST node
- var triggerASTNode *parser.CreatetrigstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&triggerExtractor{
- result: &triggerASTNode,
- }, parseResult.Tree)
-
- if triggerASTNode == nil {
- return errors.New("failed to extract CREATE TRIGGER AST node")
- }
-
- // Update the chunk's AST node
- chunk.ASTNode = triggerASTNode
- }
-
- // Handle comment changes independently of definition changes
- if currentTrigger.Comment != previousTrigger.Comment {
- if currentTrigger.Comment != "" {
- // New or updated comment
- commentSQL := generateCommentOnTriggerSQL(schemaName, tableName, currentTrigger.Name, currentTrigger.Comment)
- commentParseResults, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil && len(commentParseResults) > 0 && commentParseResults[0].Tree != nil {
- commentParseResult := commentParseResults[0]
- // Extract COMMENT ON TRIGGER AST node
- var commentASTNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentASTNode,
- }, commentParseResult.Tree)
-
- if commentASTNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentASTNode}
- }
- }
- } else {
- // Comment was removed
- chunk.CommentStatements = nil
- }
- }
-
- return nil
-}
-
-// deleteTriggerChunk removes a trigger chunk from the chunks
-func deleteTriggerChunk(chunks *schema.SDLChunks, triggerKey string) {
- if chunks != nil && chunks.Triggers != nil {
- delete(chunks.Triggers, triggerKey)
- }
-}
-
-// generateCreateTriggerSDL generates the SDL text for a CREATE TRIGGER statement
-func generateCreateTriggerSDL(schemaName, tableName string, trigger *storepb.TriggerMetadata) string {
- if trigger == nil {
- return ""
- }
-
- var buf strings.Builder
- if err := writeTriggerSDL(&buf, schemaName, tableName, trigger); err != nil {
- return ""
- }
-
- return buf.String()
-}
-
-// generateCommentOnTriggerSQL generates a COMMENT ON TRIGGER statement
-func generateCommentOnTriggerSQL(schemaName, tableName, triggerName, comment string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- // Escape single quotes in comment
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- return fmt.Sprintf("COMMENT ON TRIGGER \"%s\" ON \"%s\".\"%s\" IS '%s';", triggerName, schemaName, tableName, escapedComment)
-}
-
-// triggerExtractor extracts CREATE TRIGGER AST nodes
-type triggerExtractor struct {
- *parser.BasePostgreSQLParserListener
- result **parser.CreatetrigstmtContext
-}
-
-func (e *triggerExtractor) EnterCreatetrigstmt(ctx *parser.CreatetrigstmtContext) {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
-}
diff --git a/backend/plugin/schema/pg/get_sdl_diff_comment_test.go b/backend/plugin/schema/pg/get_sdl_diff_comment_test.go
index ed54e6df16..7600e7cd19 100644
--- a/backend/plugin/schema/pg/get_sdl_diff_comment_test.go
+++ b/backend/plugin/schema/pg/get_sdl_diff_comment_test.go
@@ -106,7 +106,7 @@ COMMENT ON TABLE users IS 'Same comment';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -204,7 +204,7 @@ COMMENT ON COLUMN users.email IS 'Email address';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -246,7 +246,7 @@ COMMENT ON VIEW user_view IS 'User view description';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -285,7 +285,7 @@ COMMENT ON SEQUENCE user_id_seq IS 'User ID sequence';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -332,7 +332,7 @@ COMMENT ON FUNCTION add_numbers(INT, INT) IS 'Adds two numbers';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -386,7 +386,7 @@ COMMENT ON COLUMN users.name IS 'User name';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -439,7 +439,7 @@ COMMENT ON COLUMN users.name IS 'User name';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -504,7 +504,7 @@ COMMENT ON COLUMN users.name IS 'New name';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -545,7 +545,7 @@ COMMENT ON TABLE users IS 'New comment';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -596,7 +596,7 @@ Line 2';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -651,7 +651,7 @@ COMMENT ON COLUMN myschema.users.name IS 'User name';`,
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/get_sdl_diff_test.go b/backend/plugin/schema/pg/get_sdl_diff_test.go
index 55e765639e..de7d967feb 100644
--- a/backend/plugin/schema/pg/get_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/get_sdl_diff_test.go
@@ -1,17 +1,11 @@
package pg
import (
- "fmt"
- "strings"
"testing"
- "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- parser "github.com/bytebase/parser/postgresql"
-
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -147,7 +141,7 @@ func TestGetSDLDiff_InitializationScenario(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDLText, tt.previousUserSDLText, tt.currentSchema, tt.previousSchema)
+ diff, err := GetSDLDiff(tt.currentSDLText, tt.previousUserSDLText, tt.currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -344,32 +338,8 @@ func TestGetSDLDiff_MinimalChangesScenario(t *testing.T) {
false,
)
- previousSchema := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- )
-
// Test that the function runs without error when schemas are provided
- diff, err := GetSDLDiff(currentSDLText, previousUserSDLText, currentSchema, previousSchema)
+ diff, err := GetSDLDiff(currentSDLText, previousUserSDLText, currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -380,4950 +350,3 @@ func TestGetSDLDiff_MinimalChangesScenario(t *testing.T) {
t.Logf("Change %d: %s %s", i+1, change.Action, change.TableName)
}
}
-
-func TestApplyMinimalChangesToChunks(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedTables []string
- shouldContainSerial bool
- shouldContainIdentity bool
- }{
- {
- name: "add_new_table_to_existing_chunks",
- previousUserSDLText: `CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
- );`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- {
- Name: "posts",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "title", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTables: []string{"public.users", "public.posts"},
- shouldContainSerial: false,
- },
- {
- name: "add_table_with_serial_column",
- previousUserSDLText: `CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
- );`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "bigint",
- Nullable: false,
- Default: "nextval('products_id_seq'::regclass)",
- },
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "products_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTables: []string{"public.users", "public.products"},
- shouldContainSerial: true,
- },
- {
- name: "add_table_with_identity_column",
- previousUserSDLText: `CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
- );`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- IdentityGeneration: storepb.ColumnMetadata_BY_DEFAULT,
- },
- {Name: "total", Type: "numeric(10,2)", Nullable: false},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "orders_id_seq",
- DataType: "integer",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "2147483647",
- Cycle: false,
- OwnerTable: "orders",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTables: []string{"public.users", "public.orders"},
- shouldContainIdentity: true,
- },
- {
- name: "multi_schema_with_same_table_names",
- previousUserSDLText: `CREATE TABLE public.users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
- );`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- },
- {
- Name: "admin",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users", // Same table name but different schema
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "role", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTables: []string{"public.users", "admin.users"},
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse the SDL text into chunks
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
-
- // Apply minimal changes to chunks
- err = applyMinimalChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Check that all expected tables are present in the chunks
- require.Equal(t, len(tt.expectedTables), len(previousChunks.Tables))
- for _, expectedTable := range tt.expectedTables {
- chunk, exists := previousChunks.Tables[expectedTable]
- require.True(t, exists, "Expected table %s not found in chunks", expectedTable)
-
- // Check that we can get text from the chunk
- text := chunk.GetText()
- require.NotEmpty(t, text)
- require.Contains(t, strings.ToUpper(text), "CREATE TABLE")
-
- // Check for serial if expected (only for products table)
- if tt.shouldContainSerial && expectedTable == "public.products" {
- upperText := strings.ToUpper(text)
- require.Contains(t, upperText, "SERIAL", "Expected serial type in products table")
- }
-
- // Check for identity if expected (only for orders table)
- if tt.shouldContainIdentity && expectedTable == "public.orders" {
- upperText := strings.ToUpper(text)
- require.Contains(t, upperText, "GENERATED", "Expected GENERATED keyword in orders table")
- require.Contains(t, upperText, "AS IDENTITY", "Expected AS IDENTITY in orders table")
- }
- }
- })
- }
-}
-
-// TestGetSDLDiff_UsabilityHandling tests the usability feature that skips diffs
-// when current SDL chunk matches the SDL generated from current database metadata
-func TestGetSDLDiff_UsabilityHandling(t *testing.T) {
- tests := []struct {
- name string
- currentSDLText string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- expectedTableChanges int
- expectedViewChanges int
- expectedFunctionChanges int
- expectedSequenceChanges int
- description string
- }{
- {
- name: "table_format_difference_but_same_structure",
- currentSDLText: `CREATE TABLE "public"."users" (
- "id" integer DEFAULT nextval('users_id_seq'::regclass) NOT NULL,
- "name" text NOT NULL,
- CONSTRAINT "users_pkey" PRIMARY KEY (id)
-);`,
- previousUserSDLText: `CREATE TABLE public.users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "users_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"id"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0, // Should skip because current SDL matches database metadata
- expectedViewChanges: 0,
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When current SDL matches database metadata format, skip diff even if previous format was different",
- },
- {
- name: "view_format_difference_but_same_definition",
- currentSDLText: `CREATE VIEW "public"."user_view" AS SELECT users.id, users.name FROM public.users;`,
- previousUserSDLText: `CREATE VIEW user_view AS SELECT id, name FROM users;`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "user_view",
- Definition: "SELECT users.id, users.name FROM public.users;",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0,
- expectedViewChanges: 0, // Should skip because current SDL matches database metadata
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When current view SDL matches database metadata format, skip diff even if previous format was different",
- },
- {
- name: "actual_structure_change_should_not_skip",
- currentSDLText: `CREATE TABLE public.users (
- id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
- name text NOT NULL,
- email text,
- CONSTRAINT users_pkey PRIMARY KEY (id)
-);`,
- previousUserSDLText: `CREATE TABLE public.users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "users_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"id"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 1, // Should NOT skip because there is an actual structural difference (email column)
- expectedViewChanges: 0,
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When there is actual structural difference, do not skip diff even if formats are different",
- },
- {
- name: "pk_uk_column_quotes_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."users" (
- "id" integer DEFAULT nextval('users_id_seq'::regclass) NOT NULL,
- "name" text NOT NULL,
- "email" text,
- CONSTRAINT "users_pkey" PRIMARY KEY (id)
-);
-
-CREATE UNIQUE INDEX "users_email_key" ON ONLY "public"."users" (email);`,
- previousUserSDLText: `CREATE TABLE "public"."users" (
- "id" integer DEFAULT nextval('users_id_seq'::regclass) NOT NULL,
- "name" text NOT NULL,
- "email" text,
- CONSTRAINT "users_pkey" PRIMARY KEY ("id")
-);
-
-CREATE UNIQUE INDEX "users_email_key" ON ONLY "public"."users" ("email");`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- {
- Name: "email",
- Type: "text",
- Nullable: true,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "users_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"id"},
- },
- {
- Name: "users_email_key",
- Unique: true,
- Primary: false,
- KeyLength: []int64{},
- Expressions: []string{"email"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0, // Should skip because only PK/UK column quotes differ, same structure
- expectedViewChanges: 0,
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When current SDL matches database metadata except for PK/UK column quotes (old vs new format), should skip diff",
- },
- {
- name: "pk_column_quotes_only_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."orders" (
- "order_id" bigint DEFAULT nextval('orders_order_id_seq'::regclass) NOT NULL,
- "customer_name" text NOT NULL,
- CONSTRAINT "orders_pkey" PRIMARY KEY (order_id)
-);`,
- previousUserSDLText: `CREATE TABLE "public"."orders" (
- "order_id" bigint DEFAULT nextval('orders_order_id_seq'::regclass) NOT NULL,
- "customer_name" text NOT NULL,
- CONSTRAINT "orders_pkey" PRIMARY KEY ("order_id")
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "order_id",
- Type: "bigint",
- Nullable: false,
- Default: "nextval('orders_order_id_seq'::regclass)",
- },
- {
- Name: "customer_name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "orders_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"order_id"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0, // Should skip because only PK column quotes differ (new format vs old format)
- expectedViewChanges: 0,
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When current SDL matches database metadata except for PK column quotes only (new vs old Bytebase format), should skip diff",
- },
- {
- name: "fine_grained_column_level_usability_handling",
- currentSDLText: `CREATE TABLE "public"."products" (
- "id" integer DEFAULT nextval('products_id_seq'::regclass) NOT NULL,
- "name" text NOT NULL,
- "price" numeric(10,2)
-);`,
- previousUserSDLText: `CREATE TABLE products (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL,
- price DECIMAL(10,2)
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('products_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- {
- Name: "price",
- Type: "numeric(10,2)",
- Nullable: true,
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0, // Should skip column-level changes because current columns match database metadata
- expectedViewChanges: 0,
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When individual columns match database metadata format, skip column-level diffs even if table format differs",
- },
- {
- name: "fine_grained_constraint_level_usability_handling",
- currentSDLText: `CREATE TABLE "public"."orders" (
- "order_id" bigint DEFAULT nextval('orders_order_id_seq'::regclass) NOT NULL,
- "customer_name" text NOT NULL,
- CONSTRAINT "orders_pkey" PRIMARY KEY (order_id),
- CONSTRAINT "orders_customer_name_check" CHECK (length(customer_name) > 0)
-);`,
- previousUserSDLText: `CREATE TABLE orders (
- order_id BIGSERIAL PRIMARY KEY,
- customer_name TEXT NOT NULL CHECK (length(customer_name) > 0)
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "order_id",
- Type: "bigint",
- Nullable: false,
- Default: "nextval('orders_order_id_seq'::regclass)",
- },
- {
- Name: "customer_name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "orders_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"order_id"},
- },
- },
- CheckConstraints: []*storepb.CheckConstraintMetadata{
- {
- Name: "orders_customer_name_check",
- Expression: "(length(customer_name) > 0)",
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0, // Should skip constraint-level changes because current constraints match database metadata
- expectedViewChanges: 0,
- expectedFunctionChanges: 0,
- expectedSequenceChanges: 0,
- description: "When individual constraints match database metadata format, skip constraint-level diffs even if table format differs",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Call GetSDLDiff
- diff, err := GetSDLDiff(tt.currentSDLText, tt.previousUserSDLText, tt.currentSchema, nil)
- require.NoError(t, err)
- require.NotNil(t, diff)
-
- // Check the number of changes
- require.Equal(t, tt.expectedTableChanges, len(diff.TableChanges),
- "Expected %d table changes but got %d", tt.expectedTableChanges, len(diff.TableChanges))
- require.Equal(t, tt.expectedViewChanges, len(diff.ViewChanges),
- "Expected %d view changes but got %d", tt.expectedViewChanges, len(diff.ViewChanges))
- require.Equal(t, tt.expectedFunctionChanges, len(diff.FunctionChanges),
- "Expected %d function changes but got %d", tt.expectedFunctionChanges, len(diff.FunctionChanges))
- require.Equal(t, tt.expectedSequenceChanges, len(diff.SequenceChanges),
- "Expected %d sequence changes but got %d", tt.expectedSequenceChanges, len(diff.SequenceChanges))
-
- // Log the detected changes for debugging
- if len(diff.TableChanges) > 0 {
- t.Log("Detected table changes:")
- for i, change := range diff.TableChanges {
- t.Logf(" %d. Table: %s.%s, Action: %v", i+1, change.SchemaName, change.TableName, change.Action)
- }
- }
- })
- }
-}
-
-// TestShouldSkipChunkDiffForUsability tests the core usability logic
-func TestShouldSkipChunkDiffForUsability(t *testing.T) {
- // Create a test schema
- testSchema := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "users_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"id"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- )
-
- tests := []struct {
- name string
- chunkText string
- chunkID string
- currentSchema *model.DatabaseMetadata
- expectedSkip bool
- description string
- }{
- {
- name: "matching_table_should_skip",
- chunkText: `CREATE TABLE "public"."users" (
- "id" integer DEFAULT nextval('users_id_seq'::regclass) NOT NULL,
- "name" text NOT NULL,
- CONSTRAINT "users_pkey" PRIMARY KEY (id)
-)`,
- chunkID: "public.users",
- currentSchema: testSchema,
- expectedSkip: true,
- description: "Chunk text matches database metadata SDL, should skip",
- },
- {
- name: "different_table_should_not_skip",
- chunkText: `CREATE TABLE public.users (
- id SERIAL PRIMARY KEY,
- name TEXT NOT NULL,
- email TEXT
-);`,
- chunkID: "public.users",
- currentSchema: testSchema,
- expectedSkip: false,
- description: "Chunk text differs from database metadata SDL, should not skip",
- },
- {
- name: "nil_schema_should_not_skip",
- chunkText: "CREATE TABLE users (id SERIAL PRIMARY KEY);",
- chunkID: "public.users",
- currentSchema: nil,
- expectedSkip: false,
- description: "When no current schema provided, should not skip",
- },
- {
- name: "unknown_chunk_should_not_skip",
- chunkText: "CREATE TABLE nonexistent (id SERIAL PRIMARY KEY);",
- chunkID: "public.nonexistent",
- currentSchema: testSchema,
- expectedSkip: false,
- description: "When chunk doesn't exist in database metadata, should not skip",
- },
- }
-
- // Create a schema with table comment for testing comment-related scenarios
- testSchemaWithComment := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Comment: "Product catalog table",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "products_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"id"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- )
-
- // Additional tests for comment-related scenarios
- commentTests := []struct {
- name string
- chunkText string
- chunkID string
- currentSchema *model.DatabaseMetadata
- expectedSkip bool
- description string
- }{
- {
- name: "table_with_same_structure_but_comment_format_differs_should_skip",
- chunkText: `CREATE TABLE "public"."products" (
- "id" integer NOT NULL,
- "name" text NOT NULL,
- CONSTRAINT "products_pkey" PRIMARY KEY (id)
-)`,
- chunkID: "public.products",
- currentSchema: testSchemaWithComment,
- expectedSkip: true,
- description: "Table structure is identical (both from database and user SDL). In real usage, GetTextWithoutComments() is called before shouldSkipChunkDiffForUsability, so COMMENT is already excluded. This test verifies that identical structure should skip diff.",
- },
- }
-
- // Combine original tests with comment tests
- tests = append(tests, commentTests...)
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Build current database SDL chunks
- currentDBSDLChunks, err := buildCurrentDatabaseSDLChunks(tt.currentSchema)
- require.NoError(t, err)
-
- result := currentDBSDLChunks.shouldSkipChunkDiffForUsability(tt.chunkText, tt.chunkID)
- require.Equal(t, tt.expectedSkip, result,
- "Expected skip=%v but got skip=%v", tt.expectedSkip, result)
- })
- }
-}
-
-// TestCurrentDatabaseSDLChunksPerformance validates that the current database SDL chunks provide performance benefits
-func TestCurrentDatabaseSDLChunksPerformance(t *testing.T) {
- // Create a simple test schema
- testSchema := model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "users_pkey",
- Unique: true,
- Primary: true,
- KeyLength: []int64{},
- Expressions: []string{"id"},
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- )
-
- // Build current database SDL chunks once
- currentDBSDLChunks, err := buildCurrentDatabaseSDLChunks(testSchema)
- require.NoError(t, err)
- require.NotNil(t, currentDBSDLChunks)
-
- // Verify that SDL chunks contain expected entries
- require.Greater(t, len(currentDBSDLChunks.chunks), 0, "SDL chunks should contain chunks")
- t.Logf("Current database SDL chunks contains %d chunks", len(currentDBSDLChunks.chunks))
-
- // Test that cache lookup is fast (should be O(1))
- testChunkText := `CREATE TABLE "public"."users" (
- "id" integer DEFAULT nextval('users_id_seq'::regclass) NOT NULL,
- "name" text NOT NULL,
- CONSTRAINT "users_pkey" PRIMARY KEY (id)
-)`
-
- // Multiple lookups should be fast
- found := false
- for i := 0; i < 100; i++ {
- result := currentDBSDLChunks.shouldSkipChunkDiffForUsability(testChunkText, "public.users")
- if result {
- found = true
- }
- }
-
- // At least verify the SDL chunks work
- require.True(t, found, "Current database SDL chunks should have found a match at least once")
- t.Log("Performance test completed successfully - current database SDL chunks provide O(1) lookups")
-}
-
-func TestApplyMinimalChangesToChunks_MultipleTableCorruption(t *testing.T) {
- testCases := []struct {
- name string
- description string
- currentSDL string
- previousSDL string
- }{
- {
- name: "simple_constraint_deletion_test",
- description: "Test constraint deletion logic with a simple table",
- currentSDL: `CREATE TABLE "test"."simple_table" (
- "id" integer NOT NULL,
- "name" text NOT NULL
-);`,
- previousSDL: `CREATE TABLE "test"."simple_table" (
- "id" integer NOT NULL,
- "name" text NOT NULL,
- CONSTRAINT "simple_table_pkey" PRIMARY KEY (id)
-);`,
- },
- {
- name: "simple_column_deletion_test",
- description: "Test column deletion logic when deleting the last column",
- currentSDL: `CREATE TABLE "test"."simple_table" (
- "id" integer NOT NULL
-);`,
- previousSDL: `CREATE TABLE "test"."simple_table" (
- "id" integer NOT NULL,
- "name" text NOT NULL
-);`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- t.Logf("Test description: %s", tc.description)
-
- // Parse current and previous SDL
- currentChunks, err := ChunkSDLText(tc.currentSDL)
- require.NoError(t, err)
-
- previousChunks, err := ChunkSDLText(tc.previousSDL)
- require.NoError(t, err)
-
- // Log original chunks
- t.Log("=== Current SDL Chunks ===")
- for id, chunk := range currentChunks.Tables {
- t.Logf("Table %s: %s", id, chunk.GetText())
- }
- t.Log("=== Previous SDL Chunks ===")
- for id, chunk := range previousChunks.Tables {
- t.Logf("Table %s: %s", id, chunk.GetText())
- }
-
- // Create mock schemas for applyMinimalChangesToChunks based on test case
- var currentSchema, previousSchema *model.DatabaseMetadata
-
- switch tc.name {
- case "simple_constraint_deletion_test":
- currentSchema = createMockDatabaseSchema() // No constraints
- previousSchema = createMockDatabaseSchemaWithoutTestColumn() // Has primary key constraint
- case "simple_column_deletion_test":
- currentSchema = createMockDatabaseSchemaForColumnDeletion() // Only has id column
- previousSchema = createMockDatabaseSchema() // Has id and name columns
- default:
- currentSchema = createMockDatabaseSchema()
- previousSchema = createMockDatabaseSchemaWithoutTestColumn()
- }
-
- // Apply minimal changes - this should test both the chunk mapping logic and rewriter fix
- err = applyMinimalChangesToChunks(previousChunks, currentSchema, previousSchema)
- require.NoError(t, err)
-
- // Log chunks after minimal changes
- t.Log("=== Previous SDL Chunks After Minimal Changes ===")
- for id, chunk := range previousChunks.Tables {
- t.Logf("Table %s: %s", id, chunk.GetText())
- }
-
- // Verify that each chunk identifier matches its content
- for identifier, chunk := range previousChunks.Tables {
- chunkText := chunk.GetText()
- t.Logf("Checking identifier '%s'", identifier)
-
- // The chunk text should contain the correct table name based on the identifier
- expectedTableName := identifier
- if strings.Contains(expectedTableName, ".") {
- parts := strings.Split(expectedTableName, ".")
- expectedTableName = parts[len(parts)-1] // Get table name part
- }
-
- // Check that the chunk text contains the expected table name
- assert.Contains(t, chunkText, expectedTableName,
- "Chunk with identifier '%s' should contain table name '%s' but got: %s",
- identifier, expectedTableName, chunkText)
-
- // More specific check: chunk should contain CREATE TABLE with the correct qualified name
- // PostgreSQL can format identifiers in different ways: "schema.table", schema.table, "schema"."table"
- parts := strings.Split(identifier, ".")
- if len(parts) == 2 {
- schema, table := parts[0], parts[1]
-
- // Check various valid formats
- formats := []string{
- fmt.Sprintf(`CREATE TABLE "%s"."%s"`, schema, table), // "schema"."table"
- fmt.Sprintf(`CREATE TABLE "%s"`, identifier), // "schema.table"
- fmt.Sprintf(`CREATE TABLE %s`, identifier), // schema.table
- fmt.Sprintf(`CREATE TABLE %s.%s`, schema, table), // schema.table
- }
-
- hasValidFormat := false
- for _, format := range formats {
- if strings.Contains(chunkText, format) {
- hasValidFormat = true
- break
- }
- }
-
- assert.True(t, hasValidFormat,
- "Chunk with identifier '%s' should contain CREATE TABLE in a valid format but got: %s",
- identifier, chunkText)
- }
- }
- })
- }
-}
-
-// TestProcessCheckConstraintChanges tests check constraint modify/create/drop logic
-func TestProcessCheckConstraintChanges(t *testing.T) {
- tests := []struct {
- name string
- currentSDL string
- previousSDL string
- expectedDrops int
- expectedCreates int
- expectedModifies int // modify = drop + create
- description string
- }{
- {
- name: "create_new_check_constraint",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- CONSTRAINT "users_age_check" CHECK (age > 0)
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer
-);`,
- expectedDrops: 0,
- expectedCreates: 1,
- expectedModifies: 0,
- description: "Adding a new check constraint should create one CREATE operation",
- },
- {
- name: "drop_check_constraint",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- CONSTRAINT "users_age_check" CHECK (age > 0)
-);`,
- expectedDrops: 1,
- expectedCreates: 0,
- expectedModifies: 0,
- description: "Removing a check constraint should create one DROP operation",
- },
- {
- name: "modify_check_constraint",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- CONSTRAINT "users_age_check" CHECK (age >= 18)
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- CONSTRAINT "users_age_check" CHECK (age > 0)
-);`,
- expectedDrops: 1,
- expectedCreates: 1,
- expectedModifies: 1,
- description: "Modifying a check constraint should create one DROP and one CREATE operation",
- },
- {
- name: "multiple_constraint_operations",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- "name" text,
- CONSTRAINT "users_age_check" CHECK (age >= 21),
- CONSTRAINT "users_name_check" CHECK (length(name) > 0)
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- "email" text,
- CONSTRAINT "users_age_check" CHECK (age > 0),
- CONSTRAINT "users_email_check" CHECK (email LIKE '%@%')
-);`,
- expectedDrops: 2, // drop old age_check + drop email_check
- expectedCreates: 2, // create new age_check + create name_check
- expectedModifies: 1, // modify age_check
- description: "Multiple operations: modify age_check, drop email_check, create name_check",
- },
- {
- name: "no_changes",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- CONSTRAINT "users_age_check" CHECK (age > 0)
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "age" integer,
- CONSTRAINT "users_age_check" CHECK (age > 0)
-);`,
- expectedDrops: 0,
- expectedCreates: 0,
- expectedModifies: 0,
- description: "No changes should result in no operations",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Parse current and previous SDL
- currentChunks, err := ChunkSDLText(tt.currentSDL)
- require.NoError(t, err)
- previousChunks, err := ChunkSDLText(tt.previousSDL)
- require.NoError(t, err)
-
- // Get table chunks
- require.Len(t, currentChunks.Tables, 1, "Should have exactly one current table")
- require.Len(t, previousChunks.Tables, 1, "Should have exactly one previous table")
-
- var currentChunk, previousChunk *schema.SDLChunk
- for _, chunk := range currentChunks.Tables {
- currentChunk = chunk
- break
- }
- for _, chunk := range previousChunks.Tables {
- previousChunk = chunk
- break
- }
-
- // Extract AST nodes
- currentAST, ok := currentChunk.ASTNode.(*parser.CreatestmtContext)
- require.True(t, ok, "Current chunk should be a CREATE TABLE statement")
- previousAST, ok := previousChunk.ASTNode.(*parser.CreatestmtContext)
- require.True(t, ok, "Previous chunk should be a CREATE TABLE statement")
-
- // Process check constraint changes (no usability chunks needed for this test)
- checkDiffs := processCheckConstraintChanges(previousAST, currentAST, nil, "test.users")
-
- // Count operations
- actualDrops := 0
- actualCreates := 0
- for _, diff := range checkDiffs {
- switch diff.Action {
- case schema.MetadataDiffActionDrop:
- actualDrops++
- case schema.MetadataDiffActionCreate:
- actualCreates++
- default:
- // Unknown action - should not happen in normal cases
- }
- }
-
- // Verify results
- assert.Equal(t, tt.expectedDrops, actualDrops, "Number of DROP operations should match")
- assert.Equal(t, tt.expectedCreates, actualCreates, "Number of CREATE operations should match")
-
- // Log operations for debugging
- t.Logf("Generated %d DROP and %d CREATE operations:", actualDrops, actualCreates)
- for i, diff := range checkDiffs {
- t.Logf(" %d. Action: %s", i+1, diff.Action)
- }
- })
- }
-}
-
-// TestProcessForeignKeyChanges tests foreign key constraint modify/create/drop logic
-func TestProcessForeignKeyChanges(t *testing.T) {
- tests := []struct {
- name string
- currentSDL string
- previousSDL string
- expectedDrops int
- expectedCreates int
- description string
- }{
- {
- name: "create_new_foreign_key",
- currentSDL: `CREATE TABLE "test"."orders" (
- "id" integer NOT NULL,
- "user_id" integer,
- CONSTRAINT "orders_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
-);`,
- previousSDL: `CREATE TABLE "test"."orders" (
- "id" integer NOT NULL,
- "user_id" integer
-);`,
- expectedDrops: 0,
- expectedCreates: 1,
- description: "Adding a new foreign key should create one CREATE operation",
- },
- {
- name: "drop_foreign_key",
- currentSDL: `CREATE TABLE "test"."orders" (
- "id" integer NOT NULL,
- "user_id" integer
-);`,
- previousSDL: `CREATE TABLE "test"."orders" (
- "id" integer NOT NULL,
- "user_id" integer,
- CONSTRAINT "orders_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
-);`,
- expectedDrops: 1,
- expectedCreates: 0,
- description: "Removing a foreign key should create one DROP operation",
- },
- {
- name: "modify_foreign_key",
- currentSDL: `CREATE TABLE "test"."orders" (
- "id" integer NOT NULL,
- "user_id" integer,
- CONSTRAINT "orders_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);`,
- previousSDL: `CREATE TABLE "test"."orders" (
- "id" integer NOT NULL,
- "user_id" integer,
- CONSTRAINT "orders_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
-);`,
- expectedDrops: 1,
- expectedCreates: 1,
- description: "Modifying a foreign key should create one DROP and one CREATE operation",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Parse current and previous SDL
- currentChunks, err := ChunkSDLText(tt.currentSDL)
- require.NoError(t, err)
- previousChunks, err := ChunkSDLText(tt.previousSDL)
- require.NoError(t, err)
-
- // Get table chunks
- require.Len(t, currentChunks.Tables, 1, "Should have exactly one current table")
- require.Len(t, previousChunks.Tables, 1, "Should have exactly one previous table")
-
- var currentChunk, previousChunk *schema.SDLChunk
- for _, chunk := range currentChunks.Tables {
- currentChunk = chunk
- break
- }
- for _, chunk := range previousChunks.Tables {
- previousChunk = chunk
- break
- }
-
- // Extract AST nodes
- currentAST, ok := currentChunk.ASTNode.(*parser.CreatestmtContext)
- require.True(t, ok, "Current chunk should be a CREATE TABLE statement")
- previousAST, ok := previousChunk.ASTNode.(*parser.CreatestmtContext)
- require.True(t, ok, "Previous chunk should be a CREATE TABLE statement")
-
- // Process foreign key changes
- fkDiffs := processForeignKeyChanges(previousAST, currentAST, nil, "test.orders")
-
- // Count operations
- actualDrops := 0
- actualCreates := 0
- for _, diff := range fkDiffs {
- switch diff.Action {
- case schema.MetadataDiffActionDrop:
- actualDrops++
- case schema.MetadataDiffActionCreate:
- actualCreates++
- default:
- // Unknown action - should not happen in normal cases
- }
- }
-
- // Verify results
- assert.Equal(t, tt.expectedDrops, actualDrops, "Number of DROP operations should match")
- assert.Equal(t, tt.expectedCreates, actualCreates, "Number of CREATE operations should match")
-
- // Log operations for debugging
- t.Logf("Generated %d DROP and %d CREATE operations:", actualDrops, actualCreates)
- for i, diff := range fkDiffs {
- t.Logf(" %d. Action: %s", i+1, diff.Action)
- }
- })
- }
-}
-
-// TestProcessUniqueConstraintChanges tests unique constraint modify/create/drop logic
-func TestProcessUniqueConstraintChanges(t *testing.T) {
- tests := []struct {
- name string
- currentSDL string
- previousSDL string
- expectedDrops int
- expectedCreates int
- description string
- }{
- {
- name: "create_new_unique_constraint",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "email" text,
- CONSTRAINT "users_email_key" UNIQUE (email)
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "email" text
-);`,
- expectedDrops: 0,
- expectedCreates: 1,
- description: "Adding a new unique constraint should create one CREATE operation",
- },
- {
- name: "drop_unique_constraint",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "email" text
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "email" text,
- CONSTRAINT "users_email_key" UNIQUE (email)
-);`,
- expectedDrops: 1,
- expectedCreates: 0,
- description: "Removing a unique constraint should create one DROP operation",
- },
- {
- name: "modify_unique_constraint",
- currentSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "email" text,
- "username" text,
- CONSTRAINT "users_email_username_key" UNIQUE (email, username)
-);`,
- previousSDL: `CREATE TABLE "test"."users" (
- "id" integer NOT NULL,
- "email" text,
- "username" text,
- CONSTRAINT "users_email_username_key" UNIQUE (email)
-);`,
- expectedDrops: 1,
- expectedCreates: 1,
- description: "Modifying a unique constraint should create one DROP and one CREATE operation",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Parse current and previous SDL
- currentChunks, err := ChunkSDLText(tt.currentSDL)
- require.NoError(t, err)
- previousChunks, err := ChunkSDLText(tt.previousSDL)
- require.NoError(t, err)
-
- // Get table chunks
- require.Len(t, currentChunks.Tables, 1, "Should have exactly one current table")
- require.Len(t, previousChunks.Tables, 1, "Should have exactly one previous table")
-
- var currentChunk, previousChunk *schema.SDLChunk
- for _, chunk := range currentChunks.Tables {
- currentChunk = chunk
- break
- }
- for _, chunk := range previousChunks.Tables {
- previousChunk = chunk
- break
- }
-
- // Extract AST nodes
- currentAST, ok := currentChunk.ASTNode.(*parser.CreatestmtContext)
- require.True(t, ok, "Current chunk should be a CREATE TABLE statement")
- previousAST, ok := previousChunk.ASTNode.(*parser.CreatestmtContext)
- require.True(t, ok, "Previous chunk should be a CREATE TABLE statement")
-
- // Process unique constraint changes
- ukDiffs := processUniqueConstraintChanges(previousAST, currentAST, nil, "test.users")
-
- // Count operations
- actualDrops := 0
- actualCreates := 0
- for _, diff := range ukDiffs {
- switch diff.Action {
- case schema.MetadataDiffActionDrop:
- actualDrops++
- case schema.MetadataDiffActionCreate:
- actualCreates++
- default:
- // Unknown action - should not happen in normal cases
- }
- }
-
- // Verify results
- assert.Equal(t, tt.expectedDrops, actualDrops, "Number of DROP operations should match")
- assert.Equal(t, tt.expectedCreates, actualCreates, "Number of CREATE operations should match")
-
- // Log operations for debugging
- t.Logf("Generated %d DROP and %d CREATE operations:", actualDrops, actualCreates)
- for i, diff := range ukDiffs {
- t.Logf(" %d. Action: %s", i+1, diff.Action)
- }
- })
- }
-}
-
-func createMockDatabaseSchema() *model.DatabaseMetadata {
- metadata := &storepb.DatabaseSchemaMetadata{
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "test",
- Tables: []*storepb.TableMetadata{
- {
- Name: "simple_table",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- // No constraints in current schema
- },
- },
- },
- },
- }
-
- return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_POSTGRES, false)
-}
-
-func createMockDatabaseSchemaWithoutTestColumn() *model.DatabaseMetadata {
- metadata := &storepb.DatabaseSchemaMetadata{
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "test",
- Tables: []*storepb.TableMetadata{
- {
- Name: "simple_table",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Nullable: false},
- {Name: "name", Type: "text", Nullable: false},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "simple_table_pkey",
- Primary: true,
- Unique: true,
- IsConstraint: true,
- Expressions: []string{"id"},
- },
- },
- },
- },
- },
- },
- }
-
- return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_POSTGRES, false)
-}
-
-func createMockDatabaseSchemaForColumnDeletion() *model.DatabaseMetadata {
- // Create schema for column deletion test - only has id column (name column deleted)
- metadata := &storepb.DatabaseSchemaMetadata{
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "employees",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- },
- // Only id column - this represents the state after name column deletion
- },
- },
- },
- },
- },
- }
-
- return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_POSTGRES, false)
-}
-
-// TestGetSDLDiff_SerialAndIdentityColumns tests serial and identity column handling in SDL diff
-func TestGetSDLDiff_SerialAndIdentityColumns(t *testing.T) {
- tests := []struct {
- name string
- currentSDLText string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- expectedTableChanges int
- description string
- }{
- {
- name: "serial_column_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."users" (
- "id" serial,
- "name" text NOT NULL
-);`,
- previousUserSDLText: `CREATE TABLE public.users (
- id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
- name TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "users_id_seq",
- DataType: "integer",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "2147483647",
- Cycle: false,
- OwnerTable: "users",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0,
- description: "Serial vs expanded nextval format should not create diff when representing same structure",
- },
- {
- name: "bigserial_column_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."orders" (
- "order_id" bigserial,
- "customer_name" text NOT NULL
-);`,
- previousUserSDLText: `CREATE TABLE public.orders (
- order_id bigint NOT NULL DEFAULT nextval('orders_order_id_seq'::regclass),
- customer_name TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "order_id",
- Type: "bigint",
- Nullable: false,
- Default: "nextval('orders_order_id_seq'::regclass)",
- },
- {
- Name: "customer_name",
- Type: "text",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "orders_order_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- OwnerTable: "orders",
- OwnerColumn: "order_id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0,
- description: "Bigserial vs expanded bigint+nextval format should not create diff",
- },
- {
- name: "smallserial_column_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."items" (
- "item_id" smallserial,
- "item_name" text NOT NULL
-);`,
- previousUserSDLText: `CREATE TABLE public.items (
- item_id smallint NOT NULL DEFAULT nextval('items_item_id_seq'::regclass),
- item_name TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "items",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "item_id",
- Type: "smallint",
- Nullable: false,
- Default: "nextval('items_item_id_seq'::regclass)",
- },
- {
- Name: "item_name",
- Type: "text",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "items_item_id_seq",
- DataType: "smallint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "32767",
- Cycle: false,
- OwnerTable: "items",
- OwnerColumn: "item_id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0,
- description: "Smallserial vs expanded smallint+nextval format should not create diff",
- },
- {
- name: "identity_always_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."products" (
- "id" bigint GENERATED ALWAYS AS IDENTITY,
- "name" text NOT NULL
-);`,
- previousUserSDLText: `CREATE TABLE public.products (
- id bigint NOT NULL,
- name TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "bigint",
- Nullable: false,
- IdentityGeneration: storepb.ColumnMetadata_ALWAYS,
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "products_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0,
- description: "GENERATED ALWAYS AS IDENTITY vs plain bigint should not create diff when metadata matches",
- },
- {
- name: "identity_by_default_with_options_format_difference_should_skip",
- currentSDLText: `CREATE TABLE "public"."invoices" (
- "id" integer GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 5),
- "amount" numeric(10,2) NOT NULL
-);`,
- previousUserSDLText: `CREATE TABLE public.invoices (
- id integer NOT NULL,
- amount DECIMAL(10,2) NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "invoices",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- IdentityGeneration: storepb.ColumnMetadata_BY_DEFAULT,
- },
- {
- Name: "amount",
- Type: "numeric(10,2)",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "invoices_id_seq",
- DataType: "integer",
- Start: "100",
- Increment: "5",
- MinValue: "1",
- MaxValue: "2147483647",
- Cycle: false,
- OwnerTable: "invoices",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedTableChanges: 0,
- description: "GENERATED BY DEFAULT AS IDENTITY with options should not create diff when metadata matches",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Call GetSDLDiff
- diff, err := GetSDLDiff(tt.currentSDLText, tt.previousUserSDLText, tt.currentSchema, nil)
- require.NoError(t, err)
- require.NotNil(t, diff)
-
- // Check the number of table changes
- require.Equal(t, tt.expectedTableChanges, len(diff.TableChanges),
- "Expected %d table changes but got %d", tt.expectedTableChanges, len(diff.TableChanges))
-
- // Log the detected changes for debugging
- if len(diff.TableChanges) > 0 {
- t.Log("Detected table changes:")
- for i, change := range diff.TableChanges {
- t.Logf(" %d. Table: %s.%s, Action: %v", i+1, change.SchemaName, change.TableName, change.Action)
- }
- }
- })
- }
-}
-
-// TestConvertDatabaseSchemaToSDL_SerialAndIdentitySequences tests that serial and identity sequences
-// are properly merged into column definitions and not generated separately
-func TestConvertDatabaseSchemaToSDL_SerialAndIdentitySequences(t *testing.T) {
- tests := []struct {
- name string
- dbMetadata *model.DatabaseMetadata
- shouldContainSerial bool
- shouldContainIdentity bool
- shouldNotContainSequence []string
- shouldNotContainNextval bool
- description string
- }{
- {
- name: "serial_column_should_not_generate_separate_sequence",
- dbMetadata: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('users_id_seq'::regclass)",
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "users_id_seq",
- DataType: "integer",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "2147483647",
- Cycle: false,
- OwnerTable: "users",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- shouldContainSerial: true,
- shouldNotContainSequence: []string{"users_id_seq"},
- shouldNotContainNextval: true,
- description: "Serial column should use serial type and not generate separate sequence",
- },
- {
- name: "identity_column_should_not_generate_separate_sequence",
- dbMetadata: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "bigint",
- Nullable: false,
- IdentityGeneration: storepb.ColumnMetadata_ALWAYS,
- },
- {
- Name: "name",
- Type: "text",
- Nullable: false,
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "products_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- shouldContainIdentity: true,
- shouldNotContainSequence: []string{"products_id_seq"},
- description: "Identity column should use GENERATED AS IDENTITY and not generate separate sequence",
- },
- {
- name: "independent_sequence_should_still_be_generated",
- dbMetadata: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {
- Name: "id",
- Type: "integer",
- Nullable: false,
- Default: "nextval('orders_id_seq'::regclass)",
- },
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "orders_id_seq",
- DataType: "integer",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "2147483647",
- Cycle: false,
- OwnerTable: "orders",
- OwnerColumn: "id",
- },
- {
- Name: "independent_seq",
- DataType: "integer",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "2147483647",
- Cycle: false,
- OwnerTable: "", // No owner - independent sequence
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- shouldContainSerial: true,
- shouldNotContainSequence: []string{"orders_id_seq"},
- description: "Independent sequence (not owned by column) should still be generated separately",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Logf("Test description: %s", tt.description)
-
- // Convert database schema to SDL
- result, err := convertDatabaseSchemaToSDL(tt.dbMetadata)
- require.NoError(t, err)
- require.NotEmpty(t, result)
-
- t.Logf("Generated SDL:\n%s", result)
-
- // Check for serial type if expected
- if tt.shouldContainSerial {
- require.Contains(t, result, "serial", "SDL should contain serial type")
- }
-
- // Check for identity syntax if expected
- if tt.shouldContainIdentity {
- require.Contains(t, result, "GENERATED", "SDL should contain GENERATED keyword")
- require.Contains(t, result, "AS IDENTITY", "SDL should contain AS IDENTITY")
- }
-
- // Check that specified sequences are NOT generated separately
- for _, seqName := range tt.shouldNotContainSequence {
- // The sequence name should not appear in a CREATE SEQUENCE statement
- require.NotContains(t, result, fmt.Sprintf(`CREATE SEQUENCE "%s"`, seqName),
- "SDL should not contain separate CREATE SEQUENCE for %s", seqName)
- require.NotContains(t, result, fmt.Sprintf(`CREATE SEQUENCE "public"."%s"`, seqName),
- "SDL should not contain separate CREATE SEQUENCE for public.%s", seqName)
- }
-
- // Check that nextval is not used if shouldNotContainNextval is true
- if tt.shouldNotContainNextval {
- require.NotContains(t, result, "nextval", "SDL should not contain nextval() when using serial")
- }
-
- // Check that independent sequences ARE generated (if present)
- if strings.Contains(tt.description, "independent") {
- require.Contains(t, result, "independent_seq", "SDL should contain independent sequence")
- require.Contains(t, result, "CREATE SEQUENCE", "SDL should have CREATE SEQUENCE for independent sequence")
- }
- })
- }
-}
-
-func TestApplySequenceChangesToChunks_PreservesAlterAndComment(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- shouldPreserveAlter bool
- shouldPreserveComment bool
- expectedAlterCount int
- expectedCommentCount int
- expectedSequenceProperties map[string]string // Properties that should change
- }{
- {
- name: "preserve_alter_sequence_on_metadata_change",
- previousUserSDLText: `CREATE SEQUENCE public.my_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-ALTER SEQUENCE public.my_seq OWNED BY public.users.id;
-
-COMMENT ON SEQUENCE public.my_seq IS 'User ID sequence';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "my_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "2", // Changed from 1 to 2
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "users",
- OwnerColumn: "id",
- Comment: "User ID sequence",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "my_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "users",
- OwnerColumn: "id",
- Comment: "User ID sequence",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- shouldPreserveAlter: true,
- shouldPreserveComment: true,
- expectedAlterCount: 1,
- expectedCommentCount: 1,
- expectedSequenceProperties: map[string]string{
- "INCREMENT": "2",
- },
- },
- {
- name: "preserve_comment_only",
- previousUserSDLText: `CREATE SEQUENCE public.counter_seq
- START WITH 100
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-COMMENT ON SEQUENCE public.counter_seq IS 'Global counter';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "counter_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "5", // Changed
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "Global counter",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "counter_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "Global counter",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- shouldPreserveAlter: false,
- shouldPreserveComment: true,
- expectedAlterCount: 0,
- expectedCommentCount: 1,
- expectedSequenceProperties: map[string]string{
- "INCREMENT": "5",
- },
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Sequences {
- t.Logf("Sequence %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" AlterStatements count: %d", len(chunk.AlterStatements))
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applySequenceChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Sequences {
- t.Logf("Sequence %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" AlterStatements count: %d", len(chunk.AlterStatements))
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Verify sequence exists
- sequenceChunk := previousChunks.Sequences["public.my_seq"]
- if tt.name == "preserve_comment_only" {
- sequenceChunk = previousChunks.Sequences["public.counter_seq"]
- }
- require.NotNil(t, sequenceChunk, "Sequence chunk should exist after drift handling")
-
- // Get full text
- fullText := sequenceChunk.GetText()
- t.Logf("Full sequence text:\n%s", fullText)
-
- // Verify ALTER statements are preserved
- if tt.shouldPreserveAlter {
- assert.Equal(t, tt.expectedAlterCount, len(sequenceChunk.AlterStatements),
- "ALTER statements should be preserved during drift handling")
- if tt.expectedAlterCount > 0 {
- assert.Contains(t, fullText, "ALTER SEQUENCE",
- "Full text should contain ALTER SEQUENCE statement")
- assert.Contains(t, fullText, "OWNED BY",
- "Full text should contain OWNED BY clause")
- }
- } else {
- assert.Equal(t, tt.expectedAlterCount, len(sequenceChunk.AlterStatements),
- "Should have expected number of ALTER statements")
- }
-
- // Verify COMMENT statements are preserved
- if tt.shouldPreserveComment {
- assert.Equal(t, tt.expectedCommentCount, len(sequenceChunk.CommentStatements),
- "COMMENT statements should be preserved during drift handling")
- if tt.expectedCommentCount > 0 {
- assert.Contains(t, fullText, "COMMENT ON SEQUENCE",
- "Full text should contain COMMENT ON SEQUENCE statement")
- }
- } else {
- assert.Equal(t, tt.expectedCommentCount, len(sequenceChunk.CommentStatements),
- "Should have expected number of COMMENT statements")
- }
-
- // Verify that sequence properties were updated
- createText := extractTextFromNode(sequenceChunk.ASTNode)
- for property, expectedValue := range tt.expectedSequenceProperties {
- assert.Contains(t, createText, expectedValue,
- "CREATE SEQUENCE should reflect the new %s value", property)
- }
- })
- }
-}
-
-func TestApplySequenceChangesToChunks_OwnerDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedAlterStatements int
- expectedOwnerTable string
- expectedOwnerColumn string
- }{
- {
- name: "sequence_owner_drifted_from_users_to_posts",
- previousUserSDLText: `CREATE SEQUENCE public.my_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-ALTER SEQUENCE public.my_seq OWNED BY public.users.id;`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "my_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "posts", // Changed from "users"
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "my_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "users",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedAlterStatements: 1,
- expectedOwnerTable: "posts",
- expectedOwnerColumn: "id",
- },
- {
- name: "sequence_owner_removed",
- previousUserSDLText: `CREATE SEQUENCE public.counter_seq
- START WITH 100
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-ALTER SEQUENCE public.counter_seq OWNED BY public.users.id;`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "counter_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "", // Owner removed
- OwnerColumn: "",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "counter_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "users",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedAlterStatements: 0, // Should be removed
- expectedOwnerTable: "",
- expectedOwnerColumn: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Sequences {
- t.Logf("Sequence %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" AlterStatements count: %d", len(chunk.AlterStatements))
- }
-
- // Apply drift handling
- err = applySequenceChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Sequences {
- t.Logf("Sequence %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" AlterStatements count: %d", len(chunk.AlterStatements))
- }
-
- // Get the sequence chunk
- var sequenceChunk *schema.SDLChunk
- for _, chunk := range previousChunks.Sequences {
- sequenceChunk = chunk
- break
- }
- require.NotNil(t, sequenceChunk, "Sequence chunk should exist after drift handling")
-
- // Get full text
- fullText := sequenceChunk.GetText()
- t.Logf("Full sequence text:\n%s", fullText)
-
- // Verify ALTER statements count
- assert.Equal(t, tt.expectedAlterStatements, len(sequenceChunk.AlterStatements),
- "ALTER statements count should match expected")
-
- // Verify the ALTER statement content matches the expected owner
- if tt.expectedAlterStatements > 0 {
- // Should contain ALTER SEQUENCE with correct owner
- // The owner reference can be in format: "table"."column" or table.column
- assert.Contains(t, fullText, "ALTER SEQUENCE",
- "Full text should contain ALTER SEQUENCE statement")
- assert.Contains(t, fullText, "OWNED BY",
- "ALTER SEQUENCE should contain OWNED BY clause")
- // Check that it references the correct table and column (with or without quotes/schema)
- assert.Contains(t, fullText, tt.expectedOwnerTable,
- "ALTER SEQUENCE should reference the correct owner table: %s", tt.expectedOwnerTable)
- assert.Contains(t, fullText, tt.expectedOwnerColumn,
- "ALTER SEQUENCE should reference the correct owner column: %s", tt.expectedOwnerColumn)
- } else {
- // Should NOT contain ALTER SEQUENCE
- assert.NotContains(t, fullText, "ALTER SEQUENCE",
- "Full text should NOT contain ALTER SEQUENCE when owner is removed")
- }
- })
- }
-}
-
-func TestApplySequenceChangesToChunks_CommentDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedCommentStatements int
- expectedCommentText string
- }{
- {
- name: "comment_changed_but_sequence_definition_unchanged",
- previousUserSDLText: `CREATE SEQUENCE public.my_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-COMMENT ON SEQUENCE public.my_seq IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "my_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "New comment", // Changed
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "my_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment",
- },
- {
- name: "comment_added_when_previously_none",
- previousUserSDLText: `CREATE SEQUENCE public.new_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "new_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "New comment added", // Added
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "new_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "", // No comment before
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment added",
- },
- {
- name: "comment_removed",
- previousUserSDLText: `CREATE SEQUENCE public.counter_seq
- START WITH 100
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-COMMENT ON SEQUENCE public.counter_seq IS 'Some comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "counter_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "", // Removed
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "counter_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "Some comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 0,
- expectedCommentText: "",
- },
- {
- name: "comment_unchanged_should_preserve_original_format",
- previousUserSDLText: `CREATE SEQUENCE public.preserve_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-COMMENT ON SEQUENCE public.preserve_seq IS 'Unchanged comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "preserve_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "Unchanged comment", // Same as before
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "preserve_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- Comment: "Unchanged comment", // Same
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "Unchanged comment",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Sequences {
- t.Logf("Sequence %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applySequenceChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Sequences {
- t.Logf("Sequence %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Get the sequence chunk
- var sequenceChunk *schema.SDLChunk
- for _, chunk := range previousChunks.Sequences {
- sequenceChunk = chunk
- break
- }
- require.NotNil(t, sequenceChunk, "Sequence chunk should exist after drift handling")
-
- // Get full text
- fullText := sequenceChunk.GetText()
- t.Logf("Full sequence text:\n%s", fullText)
-
- // Verify COMMENT statements count
- assert.Equal(t, tt.expectedCommentStatements, len(sequenceChunk.CommentStatements),
- "COMMENT statements count should match expected")
-
- // Verify the COMMENT statement content
- if tt.expectedCommentStatements > 0 && tt.expectedCommentText != "" {
- // Use Contains with "COMMENT" and "SEQUENCE" to be flexible with formatting
- assert.Contains(t, fullText, "COMMENT",
- "Full text should contain COMMENT statement")
- assert.Contains(t, fullText, "SEQUENCE",
- "Full text should mention SEQUENCE")
- assert.Contains(t, fullText, tt.expectedCommentText,
- "COMMENT should contain the expected text: %s", tt.expectedCommentText)
- } else if tt.expectedCommentText == "" && tt.expectedCommentStatements == 0 {
- // Either no comment or empty comment
- assert.NotContains(t, fullText, "COMMENT ON SEQUENCE",
- "Full text should NOT contain COMMENT ON SEQUENCE when comment is removed")
- }
- })
- }
-}
-
-func TestApplySequenceChangesToChunks_OwnedSequenceNotInSDL(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectSequenceChunk bool
- sequenceKey string
- }{
- {
- name: "serial_sequence_not_in_sdl_should_not_create_chunk",
- // User SDL only contains CREATE TABLE, not the sequence created by SERIAL
- previousUserSDLText: `CREATE TABLE public.users (
- id SERIAL PRIMARY KEY,
- name TEXT
-);`,
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Default: "nextval('users_id_seq'::regclass)"},
- {Name: "name", Type: "text"},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "users_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "users",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Default: "nextval('users_id_seq'::regclass)"},
- {Name: "name", Type: "text"},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "users_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "2", // Changed increment
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "users",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectSequenceChunk: false,
- sequenceKey: "public.users_id_seq",
- },
- {
- name: "identity_sequence_not_in_sdl_should_not_create_chunk",
- // User SDL only contains CREATE TABLE with IDENTITY column, not the sequence
- previousUserSDLText: `CREATE TABLE public.products (
- id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
- name TEXT
-);`,
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Default: "nextval('products_id_seq'::regclass)"},
- {Name: "name", Type: "text"},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "products_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Default: "nextval('products_id_seq'::regclass)"},
- {Name: "name", Type: "text"},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "products_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "5", // Changed increment
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectSequenceChunk: false,
- sequenceKey: "public.products_id_seq",
- },
- {
- name: "owned_sequence_explicitly_in_sdl_should_update_chunk",
- // User explicitly defined the sequence in SDL, so it should be updated
- previousUserSDLText: `CREATE SEQUENCE public.orders_id_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
-
-CREATE TABLE public.orders (
- id INT DEFAULT nextval('orders_id_seq'),
- amount DECIMAL
-);
-
-ALTER SEQUENCE public.orders_id_seq OWNED BY public.orders.id;`,
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Default: "nextval('orders_id_seq'::regclass)"},
- {Name: "amount", Type: "numeric"},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "orders_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "orders",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer", Default: "nextval('orders_id_seq'::regclass)"},
- {Name: "amount", Type: "numeric"},
- },
- },
- },
- Sequences: []*storepb.SequenceMetadata{
- {
- Name: "orders_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "10", // Changed increment
- MinValue: "1",
- MaxValue: "9223372036854775807",
- Cycle: false,
- CacheSize: "1",
- OwnerTable: "orders",
- OwnerColumn: "id",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectSequenceChunk: true,
- sequenceKey: "public.orders_id_seq",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL text into chunks
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
-
- // Apply sequence changes to chunks (this is what happens during drift handling)
- err = applySequenceChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Verify whether sequence chunk was created/updated
- _, exists := previousChunks.Sequences[tt.sequenceKey]
- if tt.expectSequenceChunk {
- require.True(t, exists, "Expected sequence chunk to exist for %s", tt.sequenceKey)
- } else {
- require.False(t, exists, "Expected sequence chunk NOT to exist for %s (owned sequences not in SDL should not be created)", tt.sequenceKey)
- }
- })
- }
-}
-
-func TestApplyFunctionChangesToChunks_CommentDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedCommentStatements int
- expectedCommentText string
- }{
- {
- name: "function_comment_changed_but_definition_unchanged",
- previousUserSDLText: `CREATE FUNCTION public.calculate_total(amount INTEGER) RETURNS INTEGER AS $$
-BEGIN
- RETURN amount * 2;
-END;
-$$ LANGUAGE plpgsql;
-COMMENT ON FUNCTION public.calculate_total(INTEGER) IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Functions: []*storepb.FunctionMetadata{
- {
- Name: "calculate_total",
- Definition: "CREATE FUNCTION public.calculate_total(amount INTEGER) RETURNS INTEGER AS $$\nBEGIN\n RETURN amount * 2;\nEND;\n$$ LANGUAGE plpgsql",
- Comment: "New comment", // Changed from "Old comment"
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Functions: []*storepb.FunctionMetadata{
- {
- Name: "calculate_total",
- Definition: "CREATE FUNCTION public.calculate_total(amount INTEGER) RETURNS INTEGER AS $$\nBEGIN\n RETURN amount * 2;\nEND;\n$$ LANGUAGE plpgsql",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment",
- },
- {
- name: "function_comment_added_when_previously_none",
- previousUserSDLText: `CREATE FUNCTION public.add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER AS $$
-BEGIN
- RETURN a + b;
-END;
-$$ LANGUAGE plpgsql;`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Functions: []*storepb.FunctionMetadata{
- {
- Name: "add_numbers",
- Definition: "CREATE FUNCTION public.add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER AS $$\nBEGIN\n RETURN a + b;\nEND;\n$$ LANGUAGE plpgsql",
- Comment: "Adds two numbers", // Added
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Functions: []*storepb.FunctionMetadata{
- {
- Name: "add_numbers",
- Definition: "CREATE FUNCTION public.add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER AS $$\nBEGIN\n RETURN a + b;\nEND;\n$$ LANGUAGE plpgsql",
- Comment: "", // No comment before
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "Adds two numbers",
- },
- {
- name: "function_comment_removed",
- previousUserSDLText: `CREATE FUNCTION public.process_data(input_text TEXT) RETURNS TEXT AS $$
-BEGIN
- RETURN upper(input_text);
-END;
-$$ LANGUAGE plpgsql;
-COMMENT ON FUNCTION public.process_data(TEXT) IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Functions: []*storepb.FunctionMetadata{
- {
- Name: "process_data",
- Definition: "CREATE FUNCTION public.process_data(input_text TEXT) RETURNS TEXT AS $$\nBEGIN\n RETURN upper(input_text);\nEND;\n$$ LANGUAGE plpgsql",
- Comment: "", // Comment removed
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Functions: []*storepb.FunctionMetadata{
- {
- Name: "process_data",
- Definition: "CREATE FUNCTION public.process_data(input_text TEXT) RETURNS TEXT AS $$\nBEGIN\n RETURN upper(input_text);\nEND;\n$$ LANGUAGE plpgsql",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 0,
- expectedCommentText: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Functions {
- t.Logf("Function %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applyFunctionChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Functions {
- t.Logf("Function %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Get the function chunk
- var functionChunk *schema.SDLChunk
- for _, chunk := range previousChunks.Functions {
- functionChunk = chunk
- break
- }
- require.NotNil(t, functionChunk, "Function chunk should exist after drift handling")
-
- // Get full text
- fullText := functionChunk.GetText()
- t.Logf("Full function text:\n%s", fullText)
-
- // Verify COMMENT statements count
- assert.Equal(t, tt.expectedCommentStatements, len(functionChunk.CommentStatements),
- "COMMENT statements count should match expected")
-
- // Verify COMMENT content
- if tt.expectedCommentStatements > 0 {
- assert.Contains(t, fullText, "COMMENT ON FUNCTION",
- "Full text should contain COMMENT ON FUNCTION statement")
- assert.Contains(t, fullText, tt.expectedCommentText,
- "COMMENT should contain the expected text: %s", tt.expectedCommentText)
- } else {
- // Should NOT contain COMMENT ON FUNCTION
- assert.NotContains(t, fullText, "COMMENT ON FUNCTION",
- "Full text should NOT contain COMMENT ON FUNCTION when comment is removed")
- }
- })
- }
-}
-
-func TestApplyIndexChangesToChunks_CommentDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedCommentStatements int
- expectedCommentText string
- }{
- {
- name: "index_comment_changed_but_definition_unchanged",
- previousUserSDLText: `CREATE TABLE public.users (
- id INTEGER PRIMARY KEY,
- email TEXT
-);
-
-CREATE INDEX idx_users_email ON public.users (email);
-
-COMMENT ON INDEX public.idx_users_email IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "email", Type: "text"},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "idx_users_email",
- Expressions: []string{"email"},
- Type: "btree",
- Unique: false,
- Primary: false,
- Comment: "New comment", // Changed from "Old comment"
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "email", Type: "text"},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "idx_users_email",
- Expressions: []string{"email"},
- Type: "btree",
- Unique: false,
- Primary: false,
- Comment: "Old comment",
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment",
- },
- {
- name: "index_comment_added_when_previously_none",
- previousUserSDLText: `CREATE TABLE public.products (
- id INTEGER PRIMARY KEY,
- name TEXT
-);
-
-CREATE INDEX idx_products_name ON public.products (name);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "name", Type: "text"},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "idx_products_name",
- Expressions: []string{"name"},
- Type: "btree",
- Unique: false,
- Primary: false,
- Comment: "Index for product names", // Added
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "name", Type: "text"},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "idx_products_name",
- Expressions: []string{"name"},
- Type: "btree",
- Unique: false,
- Primary: false,
- Comment: "", // No comment before
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "Index for product names",
- },
- {
- name: "index_comment_removed",
- previousUserSDLText: `CREATE TABLE public.posts (
- id INTEGER PRIMARY KEY,
- title TEXT
-);
-
-CREATE UNIQUE INDEX idx_posts_title ON public.posts (title);
-
-COMMENT ON INDEX public.idx_posts_title IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "posts",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "title", Type: "text"},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "idx_posts_title",
- Expressions: []string{"title"},
- Type: "btree",
- Unique: true,
- Primary: false,
- Comment: "", // Comment removed
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "posts",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "title", Type: "text"},
- },
- Indexes: []*storepb.IndexMetadata{
- {
- Name: "idx_posts_title",
- Expressions: []string{"title"},
- Type: "btree",
- Unique: true,
- Primary: false,
- Comment: "Old comment",
- },
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 0,
- expectedCommentText: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Indexes {
- t.Logf("Index %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applyStandaloneIndexChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Indexes {
- t.Logf("Index %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Get the index chunk
- var indexChunk *schema.SDLChunk
- for _, chunk := range previousChunks.Indexes {
- indexChunk = chunk
- break
- }
- require.NotNil(t, indexChunk, "Index chunk should exist after drift handling")
-
- // Get full text
- fullText := indexChunk.GetText()
- t.Logf("Full index text:\n%s", fullText)
-
- // Verify COMMENT statements count
- assert.Equal(t, tt.expectedCommentStatements, len(indexChunk.CommentStatements),
- "COMMENT statements count should match expected")
-
- // Verify COMMENT content
- if tt.expectedCommentStatements > 0 {
- assert.Contains(t, fullText, "COMMENT ON INDEX",
- "Full text should contain COMMENT ON INDEX statement")
- assert.Contains(t, fullText, tt.expectedCommentText,
- "COMMENT should contain the expected text: %s", tt.expectedCommentText)
- } else {
- // Should NOT contain COMMENT ON INDEX
- assert.NotContains(t, fullText, "COMMENT ON INDEX",
- "Full text should NOT contain COMMENT ON INDEX when comment is removed")
- }
- })
- }
-}
-
-func TestApplyViewChangesToChunks_CommentDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedCommentStatements int
- expectedCommentText string
- }{
- {
- name: "view_comment_changed_but_definition_unchanged",
- previousUserSDLText: `CREATE VIEW public.user_emails AS
-SELECT id, email FROM users;
-
-COMMENT ON VIEW public.user_emails IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "user_emails",
- Definition: "SELECT id, email FROM users",
- Comment: "New comment", // Changed from "Old comment"
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "user_emails",
- Definition: "SELECT id, email FROM users",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment",
- },
- {
- name: "view_comment_added_when_previously_none",
- previousUserSDLText: `CREATE VIEW public.admin_users AS
-SELECT * FROM users WHERE role = 'admin';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "admin_users",
- Definition: "SELECT * FROM users WHERE role = 'admin'",
- Comment: "View of admin users", // Added
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "admin_users",
- Definition: "SELECT * FROM users WHERE role = 'admin'",
- Comment: "", // No comment before
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "View of admin users",
- },
- {
- name: "view_comment_removed",
- previousUserSDLText: `CREATE VIEW public.active_users AS
-SELECT * FROM users WHERE active = true;
-
-COMMENT ON VIEW public.active_users IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "active_users",
- Definition: "SELECT * FROM users WHERE active = true",
- Comment: "", // Comment removed
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Views: []*storepb.ViewMetadata{
- {
- Name: "active_users",
- Definition: "SELECT * FROM users WHERE active = true",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 0,
- expectedCommentText: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Views {
- t.Logf("View %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applyViewChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Views {
- t.Logf("View %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Get the view chunk
- var viewChunk *schema.SDLChunk
- for _, chunk := range previousChunks.Views {
- viewChunk = chunk
- break
- }
- require.NotNil(t, viewChunk, "View chunk should exist after drift handling")
-
- // Get full text
- fullText := viewChunk.GetText()
- t.Logf("Full view text:\n%s", fullText)
-
- // Verify COMMENT statements count
- assert.Equal(t, tt.expectedCommentStatements, len(viewChunk.CommentStatements),
- "COMMENT statements count should match expected")
-
- // Verify COMMENT content
- if tt.expectedCommentStatements > 0 {
- assert.Contains(t, fullText, "COMMENT ON VIEW",
- "Full text should contain COMMENT ON VIEW statement")
- assert.Contains(t, fullText, tt.expectedCommentText,
- "COMMENT should contain the expected text: %s", tt.expectedCommentText)
- } else {
- // Should NOT contain COMMENT ON VIEW
- assert.NotContains(t, fullText, "COMMENT ON VIEW",
- "Full text should NOT contain COMMENT ON VIEW when comment is removed")
- }
- })
- }
-}
-
-func TestApplyMaterializedViewChangesToChunks_CommentDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedCommentStatements int
- expectedCommentText string
- }{
- {
- name: "materialized_view_comment_changed_but_definition_unchanged",
- previousUserSDLText: `CREATE TABLE public.users (
- id INTEGER PRIMARY KEY,
- email TEXT NOT NULL
-);
-
-CREATE MATERIALIZED VIEW public.user_emails_mv AS
-SELECT id, email FROM users;
-
-COMMENT ON MATERIALIZED VIEW public.user_emails_mv IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "email", Type: "text", Nullable: false},
- },
- },
- },
- MaterializedViews: []*storepb.MaterializedViewMetadata{
- {
- Name: "user_emails_mv",
- Definition: "SELECT id, email FROM users",
- Comment: "New comment", // Changed from "Old comment"
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "email", Type: "text", Nullable: false},
- },
- },
- },
- MaterializedViews: []*storepb.MaterializedViewMetadata{
- {
- Name: "user_emails_mv",
- Definition: "SELECT id, email FROM users",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment",
- },
- {
- name: "materialized_view_comment_added_when_previously_none",
- previousUserSDLText: `CREATE TABLE public.users (
- id INTEGER PRIMARY KEY,
- role TEXT
-);
-
-CREATE MATERIALIZED VIEW public.admin_users_mv AS
-SELECT * FROM users WHERE role = 'admin';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "role", Type: "text"},
- },
- },
- },
- MaterializedViews: []*storepb.MaterializedViewMetadata{
- {
- Name: "admin_users_mv",
- Definition: "SELECT * FROM users WHERE role = 'admin'",
- Comment: "Materialized view of admin users", // Added
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "role", Type: "text"},
- },
- },
- },
- MaterializedViews: []*storepb.MaterializedViewMetadata{
- {
- Name: "admin_users_mv",
- Definition: "SELECT * FROM users WHERE role = 'admin'",
- Comment: "", // No comment before
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "Materialized view of admin users",
- },
- {
- name: "materialized_view_comment_removed",
- previousUserSDLText: `CREATE TABLE public.users (
- id INTEGER PRIMARY KEY,
- active BOOLEAN
-);
-
-CREATE MATERIALIZED VIEW public.active_users_mv AS
-SELECT * FROM users WHERE active = true;
-
-COMMENT ON MATERIALIZED VIEW public.active_users_mv IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "active", Type: "boolean"},
- },
- },
- },
- MaterializedViews: []*storepb.MaterializedViewMetadata{
- {
- Name: "active_users_mv",
- Definition: "SELECT * FROM users WHERE active = true",
- Comment: "", // Comment removed
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "active", Type: "boolean"},
- },
- },
- },
- MaterializedViews: []*storepb.MaterializedViewMetadata{
- {
- Name: "active_users_mv",
- Definition: "SELECT * FROM users WHERE active = true",
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 0,
- expectedCommentText: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.MaterializedViews {
- t.Logf("Materialized View %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applyMaterializedViewChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.MaterializedViews {
- t.Logf("Materialized View %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Get the materialized view chunk
- var mvChunk *schema.SDLChunk
- for _, chunk := range previousChunks.MaterializedViews {
- mvChunk = chunk
- break
- }
- require.NotNil(t, mvChunk, "Materialized view chunk should exist after drift handling")
-
- // Get full text
- fullText := mvChunk.GetText()
- t.Logf("Full materialized view text:\n%s", fullText)
-
- // Verify COMMENT statements count
- assert.Equal(t, tt.expectedCommentStatements, len(mvChunk.CommentStatements),
- "COMMENT statements count should match expected")
-
- // Verify COMMENT content
- if tt.expectedCommentStatements > 0 {
- assert.Contains(t, fullText, "COMMENT ON MATERIALIZED VIEW",
- "Full text should contain COMMENT ON MATERIALIZED VIEW statement")
- assert.Contains(t, fullText, tt.expectedCommentText,
- "COMMENT should contain the expected text: %s", tt.expectedCommentText)
- } else {
- // Should NOT contain COMMENT ON MATERIALIZED VIEW
- assert.NotContains(t, fullText, "COMMENT ON MATERIALIZED VIEW",
- "Full text should NOT contain COMMENT ON MATERIALIZED VIEW when comment is removed")
- }
- })
- }
-}
-
-func TestApplyTableChangesToChunk_CommentDrift(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedCommentStatements int
- expectedCommentText string
- }{
- {
- name: "table_comment_changed_but_definition_unchanged",
- previousUserSDLText: `CREATE TABLE public.products (
- id INTEGER PRIMARY KEY,
- name TEXT NOT NULL
-);
-
-COMMENT ON TABLE public.products IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "name", Type: "text", Nullable: false},
- },
- Comment: "New comment", // Changed from "Old comment"
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "name", Type: "text", Nullable: false},
- },
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "New comment",
- },
- {
- name: "table_comment_added_when_previously_none",
- previousUserSDLText: `CREATE TABLE public.customers (
- id INTEGER PRIMARY KEY,
- email TEXT NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "customers",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "email", Type: "text", Nullable: false},
- },
- Comment: "Customer information table", // Added
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "customers",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "email", Type: "text", Nullable: false},
- },
- Comment: "", // No comment before
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 1,
- expectedCommentText: "Customer information table",
- },
- {
- name: "table_comment_removed",
- previousUserSDLText: `CREATE TABLE public.orders (
- order_id INTEGER PRIMARY KEY,
- total NUMERIC
-);
-
-COMMENT ON TABLE public.orders IS 'Old comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "order_id", Type: "integer"},
- {Name: "total", Type: "numeric"},
- },
- Comment: "", // Comment removed
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "order_id", Type: "integer"},
- {Name: "total", Type: "numeric"},
- },
- Comment: "Old comment",
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedCommentStatements: 0,
- expectedCommentText: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Tables {
- t.Logf("Table %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Apply drift handling
- err = applyMinimalChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Tables {
- t.Logf("Table %s:", identifier)
- t.Logf(" Text: %s", chunk.GetText())
- t.Logf(" CommentStatements count: %d", len(chunk.CommentStatements))
- }
-
- // Get the table chunk
- var tableChunk *schema.SDLChunk
- for _, chunk := range previousChunks.Tables {
- tableChunk = chunk
- break
- }
- require.NotNil(t, tableChunk, "Table chunk should exist after drift handling")
-
- // Get full text
- fullText := tableChunk.GetText()
- t.Logf("Full table text:\n%s", fullText)
-
- // Verify COMMENT statements count
- assert.Equal(t, tt.expectedCommentStatements, len(tableChunk.CommentStatements),
- "COMMENT statements count should match expected")
-
- // Verify COMMENT content
- if tt.expectedCommentStatements > 0 {
- assert.Contains(t, fullText, "COMMENT ON TABLE",
- "Full text should contain COMMENT ON TABLE statement")
- assert.Contains(t, fullText, tt.expectedCommentText,
- "COMMENT should contain the expected text: %s", tt.expectedCommentText)
- } else {
- // Should NOT contain COMMENT ON TABLE
- assert.NotContains(t, fullText, "COMMENT ON TABLE",
- "Full text should NOT contain COMMENT ON TABLE when comment is removed")
- }
- })
- }
-}
-
-func TestApplyColumnCommentChanges(t *testing.T) {
- tests := []struct {
- name string
- previousUserSDLText string
- currentSchema *model.DatabaseMetadata
- previousSchema *model.DatabaseMetadata
- expectedColumnComments map[string]map[string]string // tableKey -> columnName -> comment
- shouldContainCommentOn []string // Expected COMMENT ON COLUMN statements
- shouldNotContainCommentOn []string // Should not contain these
- }{
- {
- name: "column_comment_changed_but_table_definition_unchanged",
- previousUserSDLText: `CREATE TABLE public.products (
- id INTEGER PRIMARY KEY,
- name TEXT NOT NULL
-);
-
-COMMENT ON COLUMN public.products.name IS 'Old column comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "name", Type: "text", Nullable: false, Comment: "New column comment"},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "products",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "name", Type: "text", Nullable: false, Comment: "Old column comment"},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedColumnComments: map[string]map[string]string{
- "public.products": {
- "name": "New column comment",
- },
- },
- shouldContainCommentOn: []string{
- `COMMENT ON COLUMN "public"."products"."name" IS 'New column comment'`,
- },
- },
- {
- name: "column_comment_added_when_previously_none",
- previousUserSDLText: `CREATE TABLE public.inventory (
- id INTEGER PRIMARY KEY,
- quantity INTEGER NOT NULL
-);`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "inventory",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "quantity", Type: "integer", Nullable: false, Comment: "Available quantity"}, // Added
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "inventory",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "quantity", Type: "integer", Nullable: false, Comment: ""}, // No comment before
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedColumnComments: map[string]map[string]string{
- "public.inventory": {
- "quantity": "Available quantity",
- },
- },
- shouldContainCommentOn: []string{
- `COMMENT ON COLUMN "public"."inventory"."quantity" IS 'Available quantity'`,
- },
- },
- {
- name: "column_comment_removed",
- previousUserSDLText: `CREATE TABLE public.orders (
- order_id INTEGER PRIMARY KEY,
- total NUMERIC
-);
-
-COMMENT ON COLUMN public.orders.total IS 'Old column comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "order_id", Type: "integer"},
- {Name: "total", Type: "numeric", Comment: ""}, // Comment removed
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "orders",
- Columns: []*storepb.ColumnMetadata{
- {Name: "order_id", Type: "integer"},
- {Name: "total", Type: "numeric", Comment: "Old column comment"},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedColumnComments: map[string]map[string]string{},
- shouldNotContainCommentOn: []string{
- `COMMENT ON COLUMN "public"."orders"."total"`,
- },
- },
- {
- name: "multiple_column_comments_changed",
- previousUserSDLText: `CREATE TABLE public.users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-COMMENT ON COLUMN public.users.username IS 'Old username comment';
-COMMENT ON COLUMN public.users.email IS 'Old email comment';`,
- currentSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "username", Type: "character varying", Nullable: false, Comment: "New username comment"},
- {Name: "email", Type: "character varying", Nullable: false, Comment: "New email comment"},
- {Name: "created_at", Type: "timestamp without time zone"},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- previousSchema: model.NewDatabaseMetadata(
- &storepb.DatabaseSchemaMetadata{
- Name: "test_db",
- Schemas: []*storepb.SchemaMetadata{
- {
- Name: "public",
- Tables: []*storepb.TableMetadata{
- {
- Name: "users",
- Columns: []*storepb.ColumnMetadata{
- {Name: "id", Type: "integer"},
- {Name: "username", Type: "character varying", Nullable: false, Comment: "Old username comment"},
- {Name: "email", Type: "character varying", Nullable: false, Comment: "Old email comment"},
- {Name: "created_at", Type: "timestamp without time zone"},
- },
- },
- },
- },
- },
- },
- nil,
- nil,
- storepb.Engine_POSTGRES,
- false,
- ),
- expectedColumnComments: map[string]map[string]string{
- "public.users": {
- "username": "New username comment",
- "email": "New email comment",
- },
- },
- shouldContainCommentOn: []string{
- `COMMENT ON COLUMN "public"."users"."username" IS 'New username comment'`,
- `COMMENT ON COLUMN "public"."users"."email" IS 'New email comment'`,
- },
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Parse previous SDL
- previousChunks, err := ChunkSDLText(tt.previousUserSDLText)
- require.NoError(t, err)
- require.NotNil(t, previousChunks)
-
- // Log original chunks
- t.Log("=== Previous SDL Chunks (Before Drift Handling) ===")
- for identifier, chunk := range previousChunks.Tables {
- t.Logf("Table %s:", identifier)
- t.Logf(" CREATE TABLE text: %s", chunk.GetText())
- }
- if len(previousChunks.ColumnComments) > 0 {
- t.Logf("ColumnComments count: %d", len(previousChunks.ColumnComments))
- for tableKey, cols := range previousChunks.ColumnComments {
- t.Logf(" Table %s: %d columns with comments", tableKey, len(cols))
- for colName, colComment := range cols {
- t.Logf(" Column %s: %s", colName, colComment.GetText())
- }
- }
- }
-
- // Apply drift handling
- err = applyMinimalChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)
- require.NoError(t, err)
-
- // Log chunks after drift handling
- t.Log("=== Previous SDL Chunks (After Drift Handling) ===")
- for identifier, chunk := range previousChunks.Tables {
- t.Logf("Table %s:", identifier)
- t.Logf(" CREATE TABLE text: %s", chunk.GetText())
- }
- if len(previousChunks.ColumnComments) > 0 {
- t.Logf("ColumnComments count: %d", len(previousChunks.ColumnComments))
- for tableKey, cols := range previousChunks.ColumnComments {
- t.Logf(" Table %s: %d columns with comments", tableKey, len(cols))
- for colName, colComment := range cols {
- t.Logf(" Column %s: %s", colName, colComment.GetText())
- }
- }
- }
-
- // Verify column comments
- for tableKey, expectedCols := range tt.expectedColumnComments {
- actualCols, exists := previousChunks.ColumnComments[tableKey]
- assert.True(t, exists, "Table %s should have column comments", tableKey)
-
- for colName, expectedComment := range expectedCols {
- commentNode, exists := actualCols[colName]
- assert.True(t, exists, "Column %s should have a comment", colName)
- if exists {
- commentText := commentNode.GetText()
- t.Logf("Column %s comment text: %s", colName, commentText)
- assert.Contains(t, commentText, expectedComment,
- "Column comment should contain expected text")
- }
- }
-
- // Verify expected columns count
- assert.Equal(t, len(expectedCols), len(actualCols),
- "Number of column comments should match")
- }
-
- // If no column comments expected, verify map is empty or table key doesn't exist
- if len(tt.expectedColumnComments) == 0 {
- for _, shouldNotContain := range tt.shouldNotContainCommentOn {
- found := false
- for _, cols := range previousChunks.ColumnComments {
- for _, commentNode := range cols {
- if strings.Contains(commentNode.GetText(), shouldNotContain) {
- found = true
- break
- }
- }
- if found {
- break
- }
- }
- assert.False(t, found, "Should not contain: %s", shouldNotContain)
- }
- }
-
- // Verify CREATE TABLE statement is preserved and contains expected COMMENT statements
- for tableKey := range tt.expectedColumnComments {
- tableChunk, exists := previousChunks.Tables[tableKey]
- assert.True(t, exists, "Table chunk should exist")
- if exists {
- tableText := tableChunk.GetText()
- t.Logf("Table text:\n%s", tableText)
-
- // Verify CREATE TABLE is preserved (should start with CREATE TABLE)
- assert.Contains(t, tableText, "CREATE TABLE",
- "CREATE TABLE statement should be preserved")
-
- // Verify it contains expected COMMENT statements
- for _, expectedComment := range tt.shouldContainCommentOn {
- // Check in ColumnComments map
- // Note: GetText() removes whitespace, so we normalize both strings for comparison
- normalizedExpected := strings.ReplaceAll(expectedComment, " ", "")
- found := false
- if cols, ok := previousChunks.ColumnComments[tableKey]; ok {
- for _, commentNode := range cols {
- normalizedActual := strings.ReplaceAll(commentNode.GetText(), " ", "")
- if strings.Contains(normalizedActual, normalizedExpected) {
- found = true
- break
- }
- }
- }
- assert.True(t, found, "Should contain COMMENT: %s", expectedComment)
- }
- }
- }
- })
- }
-}
diff --git a/backend/plugin/schema/pg/index_rewrite_test.go b/backend/plugin/schema/pg/index_rewrite_test.go
deleted file mode 100644
index 06c243ba83..0000000000
--- a/backend/plugin/schema/pg/index_rewrite_test.go
+++ /dev/null
@@ -1,441 +0,0 @@
-package pg
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/schema"
-)
-
-// TestIndexRewriteOperations tests the ANTLR TokenStreamRewriter functionality
-// for standalone CREATE INDEX operations including add, modify, delete
-func TestIndexRewriteOperations(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- currentIndexes []*extendedIndexMetadata
- previousIndexes []*extendedIndexMetadata
- expectedIndexCount int
- description string
- }{
- {
- name: "Add new standalone index",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);`,
- currentIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_users_email",
- Expressions: []string{"email"},
- Type: "btree",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "users",
- },
- },
- previousIndexes: []*extendedIndexMetadata{},
- expectedIndexCount: 1,
- description: "Should add new standalone index to chunks",
- },
- {
- name: "Add unique index",
- originalSDL: `CREATE TABLE products (
- id INTEGER NOT NULL,
- code VARCHAR(50) NOT NULL
-);`,
- currentIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_products_code_unique",
- Expressions: []string{"code"},
- Type: "btree",
- Unique: true,
- },
- SchemaName: "public",
- TableName: "products",
- },
- },
- previousIndexes: []*extendedIndexMetadata{},
- expectedIndexCount: 1,
- description: "Should add new unique index to chunks",
- },
- {
- name: "Drop standalone index",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);
-
-CREATE INDEX idx_users_email ON users(email);`,
- currentIndexes: []*extendedIndexMetadata{},
- previousIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_users_email",
- Expressions: []string{"email"},
- Type: "btree",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "users",
- },
- },
- expectedIndexCount: 0,
- description: "Should remove standalone index from chunks",
- },
- {
- name: "Modify index (change type)",
- originalSDL: `CREATE TABLE documents (
- id INTEGER NOT NULL,
- content TEXT
-);
-
-CREATE INDEX idx_documents_content ON documents(content);`,
- currentIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_documents_content",
- Expressions: []string{"content"},
- Type: "gin",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "documents",
- },
- },
- previousIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_documents_content",
- Expressions: []string{"content"},
- Type: "btree",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "documents",
- },
- },
- expectedIndexCount: 1,
- description: "Should modify existing index when type changes",
- },
- {
- name: "Multiple index operations",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- customer_id INTEGER,
- total DECIMAL(10,2),
- status VARCHAR(20)
-);
-
-CREATE INDEX idx_orders_customer ON orders(customer_id);`,
- currentIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_orders_total",
- Expressions: []string{"total"},
- Type: "btree",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "orders",
- },
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_orders_status",
- Expressions: []string{"status"},
- Type: "btree",
- Unique: true,
- },
- SchemaName: "public",
- TableName: "orders",
- },
- },
- previousIndexes: []*extendedIndexMetadata{
- {
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_orders_customer",
- Expressions: []string{"customer_id"},
- Type: "btree",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "orders",
- },
- },
- expectedIndexCount: 2,
- description: "Should handle multiple index operations (drop old, add new)",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the original SDL to create chunks
- chunks, err := ChunkSDLText(tc.originalSDL)
- require.NoError(t, err, "Failed to parse original SDL")
-
- // Create index maps for simulation
- currentIndexes := make(map[string]*extendedIndexMetadata)
- previousIndexes := make(map[string]*extendedIndexMetadata)
-
- for _, idx := range tc.currentIndexes {
- key := formatIndexKey(idx.SchemaName, idx.Name)
- currentIndexes[key] = idx
- }
-
- for _, idx := range tc.previousIndexes {
- key := formatIndexKey(idx.SchemaName, idx.Name)
- previousIndexes[key] = idx
- }
-
- // Apply index changes directly to test the core logic
- err = applyStandaloneIndexChangesInternal(chunks, currentIndexes, previousIndexes)
- require.NoError(t, err, "Failed to apply index changes")
-
- // Verify the expected number of indexes
- assert.Len(t, chunks.Indexes, tc.expectedIndexCount,
- "Expected %d indexes, got %d", tc.expectedIndexCount, len(chunks.Indexes))
-
- // Verify each current index is present
- for key, extIdx := range currentIndexes {
- chunk, exists := chunks.Indexes[key]
- assert.True(t, exists, "Expected index %s not found in chunks", key)
- if exists {
- assert.NotNil(t, chunk.ASTNode, "Index chunk should have AST node")
- // Verify we can get text from the chunk
- text := chunk.GetText()
- assert.NotEmpty(t, text, "Index chunk should have non-empty text")
- assert.Contains(t, text, "CREATE", "Index text should contain CREATE")
- assert.Contains(t, text, "INDEX", "Index text should contain INDEX")
- assert.Contains(t, text, extIdx.Name, "Index text should contain index name")
- }
- }
-
- // Verify previous indexes that shouldn't exist are removed
- for key := range previousIndexes {
- if _, stillExists := currentIndexes[key]; !stillExists {
- _, exists := chunks.Indexes[key]
- assert.False(t, exists, "Index %s should have been removed from chunks", key)
- }
- }
-
- t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
- })
- }
-}
-
-// applyStandaloneIndexChangesInternal is a test helper that directly applies index changes to chunks
-func applyStandaloneIndexChangesInternal(chunks *schema.SDLChunks, currentIndexes, previousIndexes map[string]*extendedIndexMetadata) error {
- if chunks == nil {
- return nil
- }
-
- // Process index additions: create new index chunks
- for indexKey, currentIndex := range currentIndexes {
- if _, exists := previousIndexes[indexKey]; !exists {
- // New index - create a chunk for it
- err := createIndexChunk(chunks, currentIndex, indexKey)
- if err != nil {
- return err
- }
- }
- }
-
- // Process index modifications: update existing chunks
- for indexKey, currentIndex := range currentIndexes {
- if previousIndex, exists := previousIndexes[indexKey]; exists {
- // Index exists in both - check if it needs modification
- err := updateIndexChunkIfNeeded(chunks, currentIndex, previousIndex, indexKey)
- if err != nil {
- return err
- }
- }
- }
-
- // Process index deletions: remove dropped index chunks
- for indexKey := range previousIndexes {
- if _, exists := currentIndexes[indexKey]; !exists {
- // Index was dropped - remove it from chunks
- deleteIndexChunk(chunks, indexKey)
- }
- }
-
- return nil
-}
-
-// TestGenerateCreateIndexSDL tests the SDL generation for CREATE INDEX statements
-func TestGenerateCreateIndexSDL(t *testing.T) {
- testCases := []struct {
- name string
- extIndex *extendedIndexMetadata
- expectedSDL string
- }{
- {
- name: "Simple btree index",
- extIndex: &extendedIndexMetadata{
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_users_email",
- Expressions: []string{"email"},
- Type: "btree",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "users",
- },
- expectedSDL: `CREATE INDEX "idx_users_email" ON ONLY "public"."users" (email)`,
- },
- {
- name: "Unique index",
- extIndex: &extendedIndexMetadata{
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_products_code",
- Expressions: []string{"code"},
- Type: "btree",
- Unique: true,
- },
- SchemaName: "public",
- TableName: "products",
- },
- expectedSDL: `CREATE UNIQUE INDEX "idx_products_code" ON ONLY "public"."products" (code)`,
- },
- {
- name: "GIN index",
- extIndex: &extendedIndexMetadata{
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_documents_content",
- Expressions: []string{"content"},
- Type: "gin",
- Unique: false,
- },
- SchemaName: "public",
- TableName: "documents",
- },
- expectedSDL: `CREATE INDEX "idx_documents_content" ON ONLY "public"."documents" USING GIN (content)`,
- },
- {
- name: "Multi-column index with DESC",
- extIndex: &extendedIndexMetadata{
- IndexMetadata: &storepb.IndexMetadata{
- Name: "idx_orders_complex",
- Expressions: []string{"customer_id", "created_at", "total"},
- Type: "btree",
- Unique: false,
- Descending: []bool{false, true, false},
- },
- SchemaName: "public",
- TableName: "orders",
- },
- expectedSDL: `CREATE INDEX "idx_orders_complex" ON ONLY "public"."orders" (customer_id, created_at DESC, total)`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := generateCreateIndexSDL(tc.extIndex)
- assert.Equal(t, tc.expectedSDL, result)
- })
- }
-}
-
-// TestIndexDefinitionsEqual tests the index comparison logic
-func TestIndexDefinitionsEqual(t *testing.T) {
- testCases := []struct {
- name string
- index1 *storepb.IndexMetadata
- index2 *storepb.IndexMetadata
- expected bool
- }{
- {
- name: "Identical indexes",
- index1: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- index2: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- expected: true,
- },
- {
- name: "Different names",
- index1: &storepb.IndexMetadata{
- Name: "idx_test1",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- index2: &storepb.IndexMetadata{
- Name: "idx_test2",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- expected: false,
- },
- {
- name: "Different types",
- index1: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- index2: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "gin",
- Unique: false,
- },
- expected: false,
- },
- {
- name: "Different uniqueness",
- index1: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- index2: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: true,
- },
- expected: false,
- },
- {
- name: "Different expressions",
- index1: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col1"},
- Type: "btree",
- Unique: false,
- },
- index2: &storepb.IndexMetadata{
- Name: "idx_test",
- Expressions: []string{"col2"},
- Type: "btree",
- Unique: false,
- },
- expected: false,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := indexDefinitionsEqual(tc.index1, tc.index2)
- assert.Equal(t, tc.expected, result)
- })
- }
-}
diff --git a/backend/plugin/schema/pg/materialized_view_index_test.go b/backend/plugin/schema/pg/materialized_view_index_test.go
index 1ace6e0523..a230117604 100644
--- a/backend/plugin/schema/pg/materialized_view_index_test.go
+++ b/backend/plugin/schema/pg/materialized_view_index_test.go
@@ -264,7 +264,7 @@ func TestMaterializedViewIndexDependencyOrdering(t *testing.T) {
CREATE INDEX "idx_customer_seg_spending" ON "public"."customer_segmentation_mv" (total_spending);`
// Get SDL diff (simulates bb rollout behavior)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/materialized_view_sdl_diff_test.go b/backend/plugin/schema/pg/materialized_view_sdl_diff_test.go
index d3c47f562e..9c47d97de8 100644
--- a/backend/plugin/schema/pg/materialized_view_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/materialized_view_sdl_diff_test.go
@@ -197,7 +197,7 @@ func TestMaterializedViewSDLDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -406,7 +406,7 @@ func TestMaterializedViewMigrationGeneration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -526,7 +526,7 @@ func TestMaterializedViewCommentMigrationGeneration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -644,7 +644,7 @@ func TestMaterializedViewDependencyOrder(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/procedure_comment_roundtrip_test.go b/backend/plugin/schema/pg/procedure_comment_roundtrip_test.go
index 217de91bb0..05c9e84f6e 100644
--- a/backend/plugin/schema/pg/procedure_comment_roundtrip_test.go
+++ b/backend/plugin/schema/pg/procedure_comment_roundtrip_test.go
@@ -103,7 +103,7 @@ $function$;`,
t.Logf("Current SDL (procedure removed):\n%s", currentSDL)
// Step 4: Generate diff and migration
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err, "Failed to generate SDL diff")
// Log the diff for debugging
diff --git a/backend/plugin/schema/pg/procedure_sdl_diff_test.go b/backend/plugin/schema/pg/procedure_sdl_diff_test.go
index b7e4da130a..0558fdee05 100644
--- a/backend/plugin/schema/pg/procedure_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/procedure_sdl_diff_test.go
@@ -183,7 +183,7 @@ func TestProcedureSDLDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -338,7 +338,7 @@ func TestProcedureSDLDiff_CommentOnProcedure(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -465,7 +465,7 @@ func TestDropColumnWithComment_NoCommentGeneration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -563,7 +563,7 @@ COMMENT ON PROCEDURE "public"."log_message"(msg text) IS 'New comment';
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/schema_implicit_creation_test.go b/backend/plugin/schema/pg/schema_implicit_creation_test.go
index 9e8ba82c86..3371246034 100644
--- a/backend/plugin/schema/pg/schema_implicit_creation_test.go
+++ b/backend/plugin/schema/pg/schema_implicit_creation_test.go
@@ -301,7 +301,7 @@ CREATE TABLE schema_b.table_b(
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Get SDL diff
- diff, err := GetSDLDiff(tt.currentSDLText, tt.previousUserSDLText, tt.currentSchema, nil)
+ diff, err := GetSDLDiff(tt.currentSDLText, tt.previousUserSDLText, tt.currentSchema)
require.NoError(t, err, "GetSDLDiff should not return error")
require.NotNil(t, diff, "Diff should not be nil")
diff --git a/backend/plugin/schema/pg/sdl_diff_table_test.go b/backend/plugin/schema/pg/sdl_diff_table_test.go
index 8b261efc9d..2fae4d16a1 100644
--- a/backend/plugin/schema/pg/sdl_diff_table_test.go
+++ b/backend/plugin/schema/pg/sdl_diff_table_test.go
@@ -107,7 +107,7 @@ func TestTableDiffScenarios(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil)
require.NoError(t, err)
// Count different action types
diff --git a/backend/plugin/schema/pg/sdl_table.go b/backend/plugin/schema/pg/sdl_table.go
index 48f6c60bc7..62ef3ca52d 100644
--- a/backend/plugin/schema/pg/sdl_table.go
+++ b/backend/plugin/schema/pg/sdl_table.go
@@ -10,7 +10,7 @@ import (
"github.com/bytebase/bytebase/backend/store/model"
)
-func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata, currentDBSDLChunks *currentDatabaseSDLChunks, diff *schema.MetadataDiff) error {
+func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currentSchema *model.DatabaseMetadata, currentDBSDLChunks *currentDatabaseSDLChunks, diff *schema.MetadataDiff) error {
// Process current table chunks to find created and modified tables
for _, currentChunk := range currentChunks.Tables {
schemaName, tableName := parseIdentifier(currentChunk.Identifier)
@@ -34,7 +34,7 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren
return errors.Errorf("expected CreatestmtContext for current table %s", currentChunk.Identifier)
}
- columnChanges := processColumnChanges(oldASTNode, newASTNode, currentSchema, previousSchema, currentDBSDLChunks, currentChunk.Identifier)
+ columnChanges := processColumnChanges(oldASTNode, newASTNode, currentSchema, currentDBSDLChunks, currentChunk.Identifier)
foreignKeyChanges := processForeignKeyChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)
checkConstraintChanges := processCheckConstraintChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)
excludeConstraintChanges := processExcludeConstraintChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)
@@ -169,13 +169,13 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren
// processColumnChanges analyzes column changes between old and new table definitions
// Following the same pattern as processTableChanges: compare text first, then analyze differences
// If schemas are nil, operates in AST-only mode without metadata extraction
-func processColumnChanges(oldTable, newTable *parser.CreatestmtContext, currentSchema, previousSchema *model.DatabaseMetadata, currentDBSDLChunks *currentDatabaseSDLChunks, tableIdentifier string) []*schema.ColumnDiff {
+func processColumnChanges(oldTable, newTable *parser.CreatestmtContext, currentSchema *model.DatabaseMetadata, currentDBSDLChunks *currentDatabaseSDLChunks, tableIdentifier string) []*schema.ColumnDiff {
if oldTable == nil || newTable == nil {
return []*schema.ColumnDiff{}
}
// Detect AST-only mode: when both schemas are nil, operate without metadata extraction
- astOnlyMode := currentSchema == nil && previousSchema == nil
+ astOnlyMode := currentSchema == nil
// Step 1: Extract all column definitions with their AST nodes for text comparison
oldColumns := extractColumnDefinitionsWithAST(oldTable)
diff --git a/backend/plugin/schema/pg/sdl_view.go b/backend/plugin/schema/pg/sdl_view.go
index 3536ef6799..fe782f3773 100644
--- a/backend/plugin/schema/pg/sdl_view.go
+++ b/backend/plugin/schema/pg/sdl_view.go
@@ -1,18 +1,7 @@
package pg
import (
- "fmt"
- "strings"
-
- "github.com/antlr4-go/antlr/v4"
- "github.com/pkg/errors"
-
- parser "github.com/bytebase/parser/postgresql"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
"github.com/bytebase/bytebase/backend/plugin/schema"
- "github.com/bytebase/bytebase/backend/store/model"
)
func processViewChanges(currentChunks, previousChunks *schema.SDLChunks, currentDBSDLChunks *currentDatabaseSDLChunks, diff *schema.MetadataDiff) {
@@ -113,266 +102,3 @@ func processViewChanges(currentChunks, previousChunks *schema.SDLChunks, current
}
}
}
-
-func applyViewChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseMetadata) error {
- if currentSchema == nil || previousSchema == nil || previousChunks == nil {
- return nil
- }
-
- // Get view differences by comparing schema metadata
- currentMetadata := currentSchema.GetProto()
- previousMetadata := previousSchema.GetProto()
- if currentMetadata == nil || previousMetadata == nil {
- return nil
- }
-
- // Build view maps for current and previous schemas
- currentViews := make(map[string]*storepb.ViewMetadata)
- previousViews := make(map[string]*storepb.ViewMetadata)
-
- // Collect all views from current schema
- for _, schema := range currentMetadata.Schemas {
- for _, view := range schema.Views {
- viewKey := formatViewKey(schema.Name, view.Name)
- currentViews[viewKey] = view
- }
- }
-
- // Collect all views from previous schema
- for _, schema := range previousMetadata.Schemas {
- for _, view := range schema.Views {
- viewKey := formatViewKey(schema.Name, view.Name)
- previousViews[viewKey] = view
- }
- }
-
- // Process view additions: create new view chunks
- for viewKey, currentView := range currentViews {
- if _, exists := previousViews[viewKey]; !exists {
- // New view - create a chunk for it
- err := createViewChunk(previousChunks, currentView, viewKey)
- if err != nil {
- return errors.Wrapf(err, "failed to create view chunk for %s", viewKey)
- }
- }
- }
-
- // Process view modifications: update existing chunks
- for viewKey, currentView := range currentViews {
- if previousView, exists := previousViews[viewKey]; exists {
- // View exists in both metadata
- // Only update if chunk exists in SDL (user explicitly defined it)
- // If chunk doesn't exist, skip - we don't force-add database objects that user didn't define
- if _, chunkExists := previousChunks.Views[viewKey]; chunkExists {
- // Chunk exists - update if needed
- err := updateViewChunkIfNeeded(previousChunks, currentView, previousView, viewKey)
- if err != nil {
- return errors.Wrapf(err, "failed to update view chunk for %s", viewKey)
- }
- }
- // If chunk doesn't exist, skip - user didn't define this view in SDL
- }
- }
-
- // Process view deletions: remove dropped view chunks
- for viewKey := range previousViews {
- if _, exists := currentViews[viewKey]; !exists {
- // View was dropped - remove it from chunks
- deleteViewChunk(previousChunks, viewKey)
- }
- }
-
- return nil
-}
-
-// formatViewKey creates a consistent key for view identification
-func formatViewKey(schemaName, viewName string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- return schemaName + "." + viewName
-}
-
-// createViewChunk creates a new CREATE VIEW chunk and adds it to the chunks
-func createViewChunk(chunks *schema.SDLChunks, view *storepb.ViewMetadata, viewKey string) error {
- if view == nil || chunks == nil {
- return nil
- }
-
- // Generate SDL text for the view
- schemaName, _ := parseIdentifier(viewKey)
- viewSDL := generateCreateViewSDL(schemaName, view)
- if viewSDL == "" {
- return errors.New("failed to generate SDL for view")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(viewSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated view SDL: %s", viewSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE VIEW AST node
- var viewASTNode *parser.ViewstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&viewExtractor{
- result: &viewASTNode,
- }, parseResult.Tree)
-
- if viewASTNode == nil {
- return errors.New("failed to extract CREATE VIEW AST node")
- }
-
- // Create and add the chunk
- chunk := &schema.SDLChunk{
- Identifier: viewKey,
- ASTNode: viewASTNode,
- }
-
- // Add comment if the view has one
- if view.Comment != "" {
- commentSQL := generateCommentOnViewSQL(schemaName, view.Name, view.Comment)
- commentParseResult, err := pgparser.ParsePostgreSQL(commentSQL)
- if err == nil && len(commentParseResult) > 0 && commentParseResult[0].Tree != nil {
- // Extract COMMENT ON VIEW AST node
- var commentASTNode *parser.CommentstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&commentExtractor{
- result: &commentASTNode,
- }, commentParseResult[0].Tree)
-
- if commentASTNode != nil {
- chunk.CommentStatements = []antlr.ParserRuleContext{commentASTNode}
- }
- }
- }
-
- if chunks.Views == nil {
- chunks.Views = make(map[string]*schema.SDLChunk)
- }
- chunks.Views[viewKey] = chunk
-
- return nil
-}
-
-// updateViewChunkIfNeeded updates an existing view chunk if the view definition has changed
-func updateViewChunkIfNeeded(chunks *schema.SDLChunks, currentView, previousView *storepb.ViewMetadata, viewKey string) error {
- if currentView == nil || previousView == nil || chunks == nil {
- return nil
- }
-
- // Get the existing chunk
- chunk, exists := chunks.Views[viewKey]
- if !exists {
- return errors.Errorf("view chunk not found for key %s", viewKey)
- }
-
- // Check if the CREATE VIEW definition has changed (excluding comment)
- definitionChanged := !viewDefinitionsEqualExcludingComment(currentView, previousView)
-
- if definitionChanged {
- // View definition has changed - regenerate the CREATE VIEW chunk
- schemaName, _ := parseIdentifier(viewKey)
- viewSDL := generateCreateViewSDL(schemaName, currentView)
- if viewSDL == "" {
- return errors.New("failed to generate SDL for view")
- }
-
- // Parse the SDL to get AST node
- parseResults, err := pgparser.ParsePostgreSQL(viewSDL)
- if err != nil {
- return errors.Wrapf(err, "failed to parse generated view SDL: %s", viewSDL)
- }
-
- // Expect single statement
- if len(parseResults) != 1 {
- return errors.Errorf("expected exactly one statement, got %d", len(parseResults))
- }
- parseResult := parseResults[0]
-
- // Extract the CREATE VIEW AST node
- var viewASTNode *parser.ViewstmtContext
- antlr.ParseTreeWalkerDefault.Walk(&viewExtractor{
- result: &viewASTNode,
- }, parseResult.Tree)
-
- if viewASTNode == nil {
- return errors.New("failed to extract CREATE VIEW AST node")
- }
-
- // Update the CREATE VIEW AST node
- chunk.ASTNode = viewASTNode
- }
-
- // Synchronize COMMENT ON VIEW statements only if comment has changed
- if currentView.Comment != previousView.Comment {
- schemaName, _ := parseIdentifier(viewKey)
- if err := syncObjectCommentStatements(chunk, currentView.Comment, "VIEW", schemaName, currentView.Name); err != nil {
- return errors.Wrapf(err, "failed to sync COMMENT statements for view %s", viewKey)
- }
- }
-
- return nil
-}
-
-// deleteViewChunk removes a view chunk from the chunks
-func deleteViewChunk(chunks *schema.SDLChunks, viewKey string) {
- if chunks != nil && chunks.Views != nil {
- delete(chunks.Views, viewKey)
- }
-}
-
-// viewDefinitionsEqualExcludingComment compares two view definitions excluding comments
-func viewDefinitionsEqualExcludingComment(view1, view2 *storepb.ViewMetadata) bool {
- if view1 == nil || view2 == nil {
- return false
- }
-
- // Compare name and definition (excluding comment)
- if view1.Name != view2.Name ||
- view1.Definition != view2.Definition {
- return false
- }
-
- return true
-}
-
-// generateCreateViewSDL generates SDL text for a CREATE VIEW statement
-func generateCreateViewSDL(schemaName string, view *storepb.ViewMetadata) string {
- if view == nil {
- return ""
- }
-
- var buf strings.Builder
- if err := writeViewSDL(&buf, schemaName, view); err != nil {
- return ""
- }
-
- return buf.String()
-}
-
-// generateCommentOnViewSQL generates a COMMENT ON VIEW statement
-func generateCommentOnViewSQL(schemaName, viewName, comment string) string {
- if schemaName == "" {
- schemaName = "public"
- }
- // Escape single quotes in comment
- escapedComment := strings.ReplaceAll(comment, "'", "''")
- return fmt.Sprintf("COMMENT ON VIEW \"%s\".\"%s\" IS '%s';", schemaName, viewName, escapedComment)
-}
-
-// viewExtractor is a walker to extract CREATE VIEW AST nodes
-type viewExtractor struct {
- parser.BasePostgreSQLParserListener
- result **parser.ViewstmtContext
-}
-
-func (e *viewExtractor) EnterViewstmt(ctx *parser.ViewstmtContext) {
- if e.result != nil && *e.result == nil {
- *e.result = ctx
- }
-}
diff --git a/backend/plugin/schema/pg/sequence_migration_integration_test.go b/backend/plugin/schema/pg/sequence_migration_integration_test.go
index f87e43276e..f7df426841 100644
--- a/backend/plugin/schema/pg/sequence_migration_integration_test.go
+++ b/backend/plugin/schema/pg/sequence_migration_integration_test.go
@@ -123,7 +123,7 @@ CREATE SEQUENCE seq_c START WITH 1;
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Step 1: Get SDL diff using AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -188,7 +188,7 @@ func TestSequenceMigrationASTOnlyModeValidation(t *testing.T) {
`
// Get diff without metadata extraction
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -230,7 +230,7 @@ func TestMultipleSequencesHandling(t *testing.T) {
`
// Get diff without metadata extraction (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -367,7 +367,7 @@ func TestSequenceOwnershipMigrationIntegration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Get SDL diff
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/sequence_rewrite_test.go b/backend/plugin/schema/pg/sequence_rewrite_test.go
deleted file mode 100644
index cc0cfe2a47..0000000000
--- a/backend/plugin/schema/pg/sequence_rewrite_test.go
+++ /dev/null
@@ -1,500 +0,0 @@
-package pg
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- parser "github.com/bytebase/parser/postgresql"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/schema"
-)
-
-// TestSequenceRewriteOperations tests the ANTLR TokenStreamRewriter functionality
-// for standalone CREATE SEQUENCE operations including add, modify, delete
-func TestSequenceRewriteOperations(t *testing.T) {
- testCases := []struct {
- name string
- originalSDL string
- currentSequences []*storepb.SequenceMetadata
- previousSequences []*storepb.SequenceMetadata
- expectedSequenceCount int
- description string
- }{
- {
- name: "Add new standalone sequence",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);`,
- currentSequences: []*storepb.SequenceMetadata{
- {
- Name: "user_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- },
- previousSequences: []*storepb.SequenceMetadata{},
- expectedSequenceCount: 1,
- description: "Should add new standalone sequence to chunks",
- },
- {
- name: "Add sequence with complex options",
- originalSDL: `CREATE TABLE orders (
- id BIGINT NOT NULL,
- amount DECIMAL(10,2) NOT NULL
-);`,
- currentSequences: []*storepb.SequenceMetadata{
- {
- Name: "order_id_seq",
- DataType: "bigint",
- Start: "1000000",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- CacheSize: "50",
- Cycle: false,
- OwnerTable: "orders",
- OwnerColumn: "id",
- },
- },
- previousSequences: []*storepb.SequenceMetadata{},
- expectedSequenceCount: 1,
- description: "Should add new sequence with complex options to chunks",
- },
- {
- name: "Drop standalone sequence",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);
-
-CREATE SEQUENCE user_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;`,
- currentSequences: []*storepb.SequenceMetadata{},
- previousSequences: []*storepb.SequenceMetadata{
- {
- Name: "user_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- },
- expectedSequenceCount: 0,
- description: "Should remove standalone sequence from chunks",
- },
- {
- name: "Modify sequence (change parameters)",
- originalSDL: `CREATE TABLE users (
- id INTEGER NOT NULL,
- email VARCHAR(255) NOT NULL
-);
-
-CREATE SEQUENCE user_seq
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;`,
- currentSequences: []*storepb.SequenceMetadata{
- {
- Name: "user_seq",
- DataType: "bigint",
- Start: "10",
- Increment: "2",
- MinValue: "",
- MaxValue: "",
- CacheSize: "5",
- Cycle: false,
- },
- },
- previousSequences: []*storepb.SequenceMetadata{
- {
- Name: "user_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- },
- expectedSequenceCount: 1,
- description: "Should modify existing sequence when parameters change",
- },
- {
- name: "Multiple sequence operations",
- originalSDL: `CREATE TABLE orders (
- id INTEGER NOT NULL,
- customer_id INTEGER,
- total DECIMAL(10,2),
- status VARCHAR(20)
-);
-
-CREATE SEQUENCE order_seq
- START WITH 100
- INCREMENT BY 1;`,
- currentSequences: []*storepb.SequenceMetadata{
- {
- Name: "order_total_seq",
- DataType: "bigint",
- Start: "1000",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- {
- Name: "customer_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "10",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- },
- previousSequences: []*storepb.SequenceMetadata{
- {
- Name: "order_seq",
- DataType: "bigint",
- Start: "100",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- },
- expectedSequenceCount: 2,
- description: "Should handle multiple sequence operations (drop old, add new)",
- },
- {
- name: "Schema-qualified sequence names",
- originalSDL: `CREATE SCHEMA test_schema;
-CREATE TABLE test_schema.products (
- id INTEGER NOT NULL,
- name VARCHAR(255)
-);`,
- currentSequences: []*storepb.SequenceMetadata{
- {
- Name: "product_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- },
- previousSequences: []*storepb.SequenceMetadata{},
- expectedSequenceCount: 1,
- description: "Should handle schema-qualified sequence names",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- // Parse the original SDL to create chunks
- chunks, err := ChunkSDLText(tc.originalSDL)
- require.NoError(t, err, "Failed to parse original SDL")
-
- // Create sequence maps for simulation
- currentSequences := make(map[string]*storepb.SequenceMetadata)
- previousSequences := make(map[string]*storepb.SequenceMetadata)
-
- for _, seq := range tc.currentSequences {
- key := formatSequenceKey("public", seq.Name)
- currentSequences[key] = seq
- }
-
- for _, seq := range tc.previousSequences {
- key := formatSequenceKey("public", seq.Name)
- previousSequences[key] = seq
- }
-
- // Apply sequence changes directly to test the core logic
- err = applySequenceChangesInternal(chunks, currentSequences, previousSequences)
- require.NoError(t, err, "Failed to apply sequence changes")
-
- // Verify the expected number of sequences
- assert.Len(t, chunks.Sequences, tc.expectedSequenceCount,
- "Expected %d sequences, got %d", tc.expectedSequenceCount, len(chunks.Sequences))
-
- // Verify each current sequence is present
- for key, seq := range currentSequences {
- chunk, exists := chunks.Sequences[key]
- assert.True(t, exists, "Expected sequence %s not found in chunks", key)
- if exists {
- assert.NotNil(t, chunk.ASTNode, "Sequence chunk should have AST node")
- // Verify we can get text from the chunk using the proper extraction function
- if sequenceAST, ok := chunk.ASTNode.(*parser.CreateseqstmtContext); ok {
- text := extractSequenceTextFromAST(sequenceAST)
- assert.NotEmpty(t, text, "Sequence chunk should have non-empty text")
- assert.Contains(t, text, "CREATE", "Sequence text should contain CREATE")
- assert.Contains(t, text, "SEQUENCE", "Sequence text should contain SEQUENCE")
- assert.Contains(t, text, seq.Name, "Sequence text should contain sequence name")
- }
- }
- }
-
- // Verify previous sequences that shouldn't exist are removed
- for key := range previousSequences {
- if _, stillExists := currentSequences[key]; !stillExists {
- _, exists := chunks.Sequences[key]
- assert.False(t, exists, "Sequence %s should have been removed from chunks", key)
- }
- }
-
- t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
- })
- }
-}
-
-// applySequenceChangesInternal is a test helper that directly applies sequence changes to chunks
-func applySequenceChangesInternal(chunks *schema.SDLChunks, currentSequences, previousSequences map[string]*storepb.SequenceMetadata) error {
- if chunks == nil {
- return nil
- }
-
- // Process sequence additions: create new sequence chunks
- for sequenceKey, currentSequence := range currentSequences {
- if _, exists := previousSequences[sequenceKey]; !exists {
- // New sequence - create a chunk for it
- err := createSequenceChunk(chunks, currentSequence, sequenceKey)
- if err != nil {
- return err
- }
- }
- }
-
- // Process sequence modifications: update existing chunks
- for sequenceKey, currentSequence := range currentSequences {
- if previousSequence, exists := previousSequences[sequenceKey]; exists {
- // Sequence exists in both - check if it needs modification
- err := updateSequenceChunkIfNeeded(chunks, currentSequence, previousSequence, sequenceKey)
- if err != nil {
- return err
- }
- }
- }
-
- // Process sequence deletions: remove dropped sequence chunks
- for sequenceKey := range previousSequences {
- if _, exists := currentSequences[sequenceKey]; !exists {
- // Sequence was dropped - remove it from chunks
- deleteSequenceChunk(chunks, sequenceKey)
- }
- }
-
- return nil
-}
-
-// TestGenerateCreateSequenceSDL tests the SDL generation for CREATE SEQUENCE statements
-func TestGenerateCreateSequenceSDL(t *testing.T) {
- testCases := []struct {
- name string
- sequence *storepb.SequenceMetadata
- expectedSDL string
- }{
- {
- name: "Simple sequence",
- sequence: &storepb.SequenceMetadata{
- Name: "user_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- },
- expectedSDL: `CREATE SEQUENCE "user_seq" START WITH 1 INCREMENT BY 1 CACHE 1`,
- },
- {
- name: "Sequence with complex options",
- sequence: &storepb.SequenceMetadata{
- Name: "order_id_seq",
- DataType: "bigint",
- Start: "1000000",
- Increment: "1",
- MinValue: "1",
- MaxValue: "9223372036854775807",
- CacheSize: "50",
- Cycle: false,
- },
- expectedSDL: `CREATE SEQUENCE "order_id_seq" START WITH 1000000 INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 50`,
- },
- {
- name: "Sequence with owner",
- sequence: &storepb.SequenceMetadata{
- Name: "product_id_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- MinValue: "",
- MaxValue: "",
- CacheSize: "1",
- Cycle: false,
- OwnerTable: "products",
- OwnerColumn: "id",
- },
- expectedSDL: `CREATE SEQUENCE "product_id_seq" START WITH 1 INCREMENT BY 1 CACHE 1 OWNED BY "products"."id"`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := generateCreateSequenceSDL("public", tc.sequence)
- // Note: The exact format may vary depending on the writeSequenceSDL implementation
- // We mainly check that it generates some reasonable SDL
- assert.NotEmpty(t, result, "Should generate non-empty SDL")
- assert.Contains(t, result, "CREATE", "Should contain CREATE")
- assert.Contains(t, result, "SEQUENCE", "Should contain SEQUENCE")
- assert.Contains(t, result, tc.sequence.Name, "Should contain sequence name")
- })
- }
-}
-
-// TestSequenceDefinitionsEqual tests the sequence comparison logic
-func TestSequenceDefinitionsEqual(t *testing.T) {
- testCases := []struct {
- name string
- sequence1 *storepb.SequenceMetadata
- sequence2 *storepb.SequenceMetadata
- expected bool
- }{
- {
- name: "Identical sequences",
- sequence1: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- sequence2: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- expected: true,
- },
- {
- name: "Different names",
- sequence1: &storepb.SequenceMetadata{
- Name: "test_seq1",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- sequence2: &storepb.SequenceMetadata{
- Name: "test_seq2",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- expected: false,
- },
- {
- name: "Different start values",
- sequence1: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- sequence2: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "10",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- expected: false,
- },
- {
- name: "Different increment values",
- sequence1: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- },
- sequence2: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "2",
- CacheSize: "1",
- Cycle: false,
- },
- expected: false,
- },
- {
- name: "Different owner information",
- sequence1: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- OwnerTable: "table1",
- OwnerColumn: "id",
- },
- sequence2: &storepb.SequenceMetadata{
- Name: "test_seq",
- DataType: "bigint",
- Start: "1",
- Increment: "1",
- CacheSize: "1",
- Cycle: false,
- OwnerTable: "table2",
- OwnerColumn: "id",
- },
- expected: false,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- result := sequenceDefinitionsEqual(tc.sequence1, tc.sequence2)
- assert.Equal(t, tc.expected, result)
- })
- }
-}
diff --git a/backend/plugin/schema/pg/sequence_sdl_diff_test.go b/backend/plugin/schema/pg/sequence_sdl_diff_test.go
index 066ce11a0b..ed3637a5de 100644
--- a/backend/plugin/schema/pg/sequence_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/sequence_sdl_diff_test.go
@@ -330,7 +330,7 @@ func TestSequenceSDLDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/standalone_index_test.go b/backend/plugin/schema/pg/standalone_index_test.go
index 1a145406a0..66e5f3d932 100644
--- a/backend/plugin/schema/pg/standalone_index_test.go
+++ b/backend/plugin/schema/pg/standalone_index_test.go
@@ -119,7 +119,7 @@ func TestStandaloneCreateIndexSupport(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -272,7 +272,7 @@ func TestStandaloneIndexIntegrationWithTableChanges(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -477,7 +477,7 @@ CREATE INDEX "idx_employees_name" ON "company"."employees" (name);
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/table_constraints_test.go b/backend/plugin/schema/pg/table_constraints_test.go
index 3db6e5c44c..d3a94cf821 100644
--- a/backend/plugin/schema/pg/table_constraints_test.go
+++ b/backend/plugin/schema/pg/table_constraints_test.go
@@ -204,7 +204,7 @@ func TestTableConstraintsSDLDiff(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil)
require.NoError(t, err, "GetSDLDiff should not return error")
tc.validate(t, diff)
})
diff --git a/backend/plugin/schema/pg/table_migration_integration_test.go b/backend/plugin/schema/pg/table_migration_integration_test.go
index 7e1a25889a..03c10bd085 100644
--- a/backend/plugin/schema/pg/table_migration_integration_test.go
+++ b/backend/plugin/schema/pg/table_migration_integration_test.go
@@ -137,7 +137,7 @@ CREATE TABLE table_c (id INTEGER PRIMARY KEY);
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Step 1: Get SDL diff using AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -203,7 +203,7 @@ func TestTableMigrationASTOnlyModeValidation(t *testing.T) {
`
// Get diff without metadata extraction
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -245,7 +245,7 @@ func TestMultipleTablesHandling(t *testing.T) {
`
// Get diff without metadata extraction (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -308,7 +308,7 @@ func TestComplexTableWithConstraintsAndIndexes(t *testing.T) {
`
// Get diff in AST-only mode
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -514,7 +514,7 @@ ALTER TABLE "public"."orders" ADD CONSTRAINT "fk_customer" FOREIGN KEY (customer
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Get diff in AST-only mode (nil schemas for AST-only)
- diff, err := GetSDLDiff(test.currentSDL, test.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(test.currentSDL, test.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -591,7 +591,7 @@ func TestTableConstraintComplexChanges(t *testing.T) {
`
// Get diff in AST-only mode
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -858,7 +858,7 @@ func TestCreateTableWithTableConstraintsIntegration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Step 1: Get SDL diff using AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -1034,7 +1034,7 @@ CREATE INDEX idx_orders_complex ON orders (customer_id, status, total_amount DES
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Get diff in AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err, "GetSDLDiff should not return error")
require.NotNil(t, diff, "diff should not be nil")
diff --git a/backend/plugin/schema/pg/trigger_drop_dependency_test.go b/backend/plugin/schema/pg/trigger_drop_dependency_test.go
index f37af35ae1..21b941a38c 100644
--- a/backend/plugin/schema/pg/trigger_drop_dependency_test.go
+++ b/backend/plugin/schema/pg/trigger_drop_dependency_test.go
@@ -81,7 +81,7 @@ func TestDropTriggerDependencyOrder(t *testing.T) {
currentSDL := ``
// Generate diff and migration (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Debug: print diff information
@@ -192,7 +192,7 @@ func TestCreateTriggerDependencyOrder(t *testing.T) {
`
// Generate diff and migration (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Debug: print diff information
@@ -276,7 +276,7 @@ func TestSameTriggerNameOnDifferentTables(t *testing.T) {
previousSDL := ``
// Generate diff and migration (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Debug: print diff information
diff --git a/backend/plugin/schema/pg/trigger_sdl_diff_test.go b/backend/plugin/schema/pg/trigger_sdl_diff_test.go
index adb883ffdc..620ae1e0fe 100644
--- a/backend/plugin/schema/pg/trigger_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/trigger_sdl_diff_test.go
@@ -32,7 +32,7 @@ func TestTriggerDiffStructure(t *testing.T) {
previousSDL := ""
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.Len(t, diff.TableChanges, 1, "Should have one table change")
@@ -87,7 +87,7 @@ func TestCreateTriggerExtraction(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.sql, "", nil, nil)
+ diff, err := GetSDLDiff(tt.sql, "", nil)
require.NoError(t, err)
totalTriggers := 0
@@ -108,7 +108,7 @@ func TestTriggerCommentExtraction(t *testing.T) {
COMMENT ON TRIGGER audit_trigger ON users IS 'Audit log trigger';
`
- diff, err := GetSDLDiff(sql, "", nil, nil)
+ diff, err := GetSDLDiff(sql, "", nil)
require.NoError(t, err)
// Check that comment change exists
@@ -135,7 +135,7 @@ func TestDropTriggerMigration(t *testing.T) {
CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -162,7 +162,7 @@ func TestCreateTriggerMigrationWithDependencyOrder(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION audit_log();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -197,7 +197,7 @@ func TestTriggerCommentMigration(t *testing.T) {
COMMENT ON TRIGGER audit_trigger ON users IS 'Audit log trigger';
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -275,7 +275,7 @@ func TestStandaloneTriggerDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil)
require.NoError(t, err)
totalTriggers := 0
@@ -308,7 +308,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
CREATE TRIGGER update_trigger BEFORE UPDATE ON orders FOR EACH ROW EXECUTE FUNCTION log_update();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
totalTriggers := 0
@@ -331,7 +331,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
CREATE TRIGGER event_trigger AFTER INSERT ON app.events FOR EACH ROW EXECUTE FUNCTION app.notify();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
found := false
@@ -355,7 +355,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
EXECUTE FUNCTION check_price();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -378,7 +378,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
CREATE TRIGGER t2 AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Should have 1 change for t1 (ALTER using CREATE OR REPLACE), none for t2
@@ -405,7 +405,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION log_changes();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -423,7 +423,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH STATEMENT EXECUTE FUNCTION stmt_trigger();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -441,7 +441,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
COMMENT ON TRIGGER t2 ON events IS 'Update trigger';
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
// Check both comments are extracted
@@ -466,7 +466,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Should have trigger drop
@@ -490,7 +490,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION check_stock();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -508,7 +508,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION instead_trigger();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -526,7 +526,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION test_func();
`
- diff, err := GetSDLDiff(currentSDL, "", nil, nil)
+ diff, err := GetSDLDiff(currentSDL, "", nil)
require.NoError(t, err)
migration, err := generateMigration(diff)
@@ -555,7 +555,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION test_func();
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Should have 1 ALTER action (not DROP + CREATE)
@@ -598,7 +598,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
COMMENT ON TRIGGER audit_trigger ON users IS 'Updated comment';
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Trigger itself should NOT have ALTER action (definition unchanged)
@@ -652,7 +652,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
COMMENT ON TRIGGER audit_trigger ON users IS 'New comment';
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Trigger should NOT have ALTER action
@@ -704,7 +704,7 @@ func TestTriggerSDLIntegration(t *testing.T) {
FOR EACH ROW EXECUTE FUNCTION audit();
`
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
// Trigger should NOT have ALTER action
diff --git a/backend/plugin/schema/pg/usability_check_test.go b/backend/plugin/schema/pg/usability_check_test.go
index ffee16a388..66378b0a05 100644
--- a/backend/plugin/schema/pg/usability_check_test.go
+++ b/backend/plugin/schema/pg/usability_check_test.go
@@ -283,7 +283,7 @@ COMMENT ON TABLE "public"."users" IS 'To be removed';
t.Run(tt.name, func(t *testing.T) {
t.Logf("Description: %s", tt.description)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -445,7 +445,7 @@ COMMENT ON VIEW "public"."active_users" IS 'Old view comment';
t.Run(tt.name, func(t *testing.T) {
t.Logf("Description: %s", tt.description)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -541,7 +541,7 @@ $$`,
t.Run(tt.name, func(t *testing.T) {
t.Logf("Description: %s", tt.description)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -619,7 +619,7 @@ COMMENT ON SEQUENCE "public"."user_id_seq" IS 'Old sequence comment';
t.Run(tt.name, func(t *testing.T) {
t.Logf("Description: %s", tt.description)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/view_migration_integration_test.go b/backend/plugin/schema/pg/view_migration_integration_test.go
index c686cfe7c1..74d0050a68 100644
--- a/backend/plugin/schema/pg/view_migration_integration_test.go
+++ b/backend/plugin/schema/pg/view_migration_integration_test.go
@@ -118,7 +118,7 @@ CREATE VIEW dependent_view AS
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Step 1: Get SDL diff using AST-only mode (no metadata extraction)
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -181,7 +181,7 @@ func TestViewMigrationASTOnlyModeValidation(t *testing.T) {
`
// Get diff without metadata extraction
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -225,7 +225,7 @@ func TestViewDependencyHandlingInAST(t *testing.T) {
`
// Get diff without metadata extraction (AST-only mode)
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -293,7 +293,7 @@ func TestDropTableAndDependentView_CorrectOrder(t *testing.T) {
currentSDL := ``
// Get the diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -351,7 +351,7 @@ func TestDropMultipleTablesAndViews_CorrectOrder(t *testing.T) {
currentSDL := ``
// Get the diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -409,7 +409,7 @@ func TestCreateTableAndDependentView_CorrectOrder(t *testing.T) {
`
// Get the diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -467,7 +467,7 @@ func TestCreateMultipleTablesAndViews_CorrectOrder(t *testing.T) {
`
// Get the diff
- diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/pg/view_sdl_diff_test.go b/backend/plugin/schema/pg/view_sdl_diff_test.go
index 8feb832692..0cf56b1ca7 100644
--- a/backend/plugin/schema/pg/view_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/view_sdl_diff_test.go
@@ -167,7 +167,7 @@ func TestViewSDLDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
diff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.go
index a78f4b7db5..5bfee65f6a 100644
--- a/backend/plugin/schema/schema.go
+++ b/backend/plugin/schema/schema.go
@@ -39,7 +39,7 @@ type getProcedureDefinition func(string, *storepb.ProcedureMetadata) (string, er
type getSequenceDefinition func(string, *storepb.SequenceMetadata) (string, error)
type getDatabaseMetadata func(string) (*storepb.DatabaseSchemaMetadata, error)
type generateMigration func(*MetadataDiff) (string, error)
-type getSDLDiff func(currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseMetadata) (*MetadataDiff, error)
+type getSDLDiff func(currentSDLText, previousUserSDLText string, currentSchema *model.DatabaseMetadata) (*MetadataDiff, error)
type walkThrough func(*model.DatabaseMetadata, []base.AST) *storepb.Advice
type GetDefinitionContext struct {
@@ -244,12 +244,12 @@ func RegisterGetSDLDiff(engine storepb.Engine, f getSDLDiff) {
getSDLDiffs[engine] = f
}
-func GetSDLDiff(engine storepb.Engine, currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseMetadata) (*MetadataDiff, error) {
+func GetSDLDiff(engine storepb.Engine, currentSDLText, previousUserSDLText string, currentSchema *model.DatabaseMetadata) (*MetadataDiff, error) {
f, ok := getSDLDiffs[engine]
if !ok {
return nil, errors.Errorf("engine %s is not supported", engine)
}
- return f(currentSDLText, previousUserSDLText, currentSchema, previousSchema)
+ return f(currentSDLText, previousUserSDLText, currentSchema)
}
func RegisterGetMultiFileDatabaseDefinition(engine storepb.Engine, f getMultiFileDatabaseDefinition) {
diff --git a/backend/runner/taskrun/database_migrate_executor.go b/backend/runner/taskrun/database_migrate_executor.go
index d6dfdb89fe..c4bed86c0d 100644
--- a/backend/runner/taskrun/database_migrate_executor.go
+++ b/backend/runner/taskrun/database_migrate_executor.go
@@ -152,7 +152,6 @@ func (exec *DatabaseMigrateExecutor) ensureBaselineChangelog(ctx context.Context
Status: store.ChangelogStatusDone,
SyncHistoryUID: &baselineSyncHistoryUID,
Payload: &storepb.ChangelogPayload{
- Type: storepb.ChangelogPayload_BASELINE,
GitCommit: exec.profile.GitCommit,
},
})
@@ -238,7 +237,6 @@ func (exec *DatabaseMigrateExecutor) runStandardMigration(ctx context.Context, d
SyncHistoryUID: nil,
Payload: &storepb.ChangelogPayload{
TaskRun: common.FormatTaskRun(database.ProjectID, task.PlanID, task.Environment, task.ID, taskRunUID),
- Type: storepb.ChangelogPayload_MIGRATE,
GitCommit: exec.profile.GitCommit,
},
})
@@ -347,7 +345,6 @@ func (exec *DatabaseMigrateExecutor) runGhostMigration(ctx context.Context, driv
SyncHistoryUID: nil,
Payload: &storepb.ChangelogPayload{
TaskRun: common.FormatTaskRun(database.ProjectID, task.PlanID, task.Environment, task.ID, taskRunUID),
- Type: storepb.ChangelogPayload_MIGRATE,
GitCommit: exec.profile.GitCommit,
},
})
@@ -455,7 +452,6 @@ func (exec *DatabaseMigrateExecutor) runVersionedRelease(ctx context.Context, dr
SyncHistoryUID: nil,
Payload: &storepb.ChangelogPayload{
TaskRun: taskRunName,
- Type: storepb.ChangelogPayload_MIGRATE,
GitCommit: exec.profile.GitCommit,
},
})
@@ -669,7 +665,6 @@ func (exec *DatabaseMigrateExecutor) runDeclarativeRelease(ctx context.Context,
SyncHistoryUID: nil,
Payload: &storepb.ChangelogPayload{
TaskRun: common.FormatTaskRun(database.ProjectID, task.PlanID, task.Environment, task.ID, taskRunUID),
- Type: storepb.ChangelogPayload_SDL,
GitCommit: exec.profile.GitCommit,
},
})
@@ -1069,19 +1064,18 @@ func diff(ctx context.Context, s *store.Store, instance *store.InstanceMessage,
return "", errors.Errorf("database schema %q not found", database.DatabaseName)
}
- // Try to get the previous successful SDL text and schema from task history
- previousUserSDLText, previousSchema, err := getPreviousSuccessfulSDLAndSchema(ctx, s, database.InstanceID, database.DatabaseName)
+ // Get the previous SDL text from the database's release field
+ previousUserSDLText, err := getPreviousSDL(ctx, s, database.InstanceID, database.DatabaseName)
if err != nil {
- return "", errors.Wrapf(err, "failed to get previous SDL text and schema for database %q", database.DatabaseName)
+ return "", errors.Wrapf(err, "failed to get previous SDL text for database %q", database.DatabaseName)
}
- // Use GetSDLDiff with previous SDL text and schema
+ // Use GetSDLDiff to compute the schema diff
// - engine: the database engine
// - currentSDLText: user's target SDL input
// - previousUserSDLText: previous SDL text (empty triggers initialization scenario)
- // - currentSchema: current database schema (used as baseline in initialization)
- // - previousSchema: previous database schema from changelog
- schemaDiff, err := schema.GetSDLDiff(pengine, sheetContent, previousUserSDLText, dbMetadata, previousSchema)
+ // - currentSchema: current database schema
+ schemaDiff, err := schema.GetSDLDiff(pengine, sheetContent, previousUserSDLText, dbMetadata)
if err != nil {
return "", errors.Wrap(err, "failed to compute SDL schema diff")
}
@@ -1099,101 +1093,65 @@ func diff(ctx context.Context, s *store.Store, instance *store.InstanceMessage,
return migrationSQL, nil
}
-// getPreviousSuccessfulSDLAndSchema gets both the SDL text and database schema from the most recent successful SDL changelog.
-// It retrieves the SDL text by following the reference chain: changelog -> task_run -> task -> release -> file -> sheet.
-// Returns empty string for SDL text if no previous successful SDL changelog is found or if the reference chain is broken.
-func getPreviousSuccessfulSDLAndSchema(ctx context.Context, s *store.Store, instanceID string, databaseName string) (string, *model.DatabaseMetadata, error) {
- // Find the most recent successful SDL changelog for this database
- // We only want MIGRATE_SDL type changelogs that are completed (DONE status)
- doneStatus := store.ChangelogStatusDone
- limit := 1 // We only need the most recent one
-
- changelogs, err := s.ListChangelogs(ctx, &store.FindChangelogMessage{
+// getPreviousSDL gets the SDL text from the database's tracked release field.
+// Returns empty string if no previous release exists.
+func getPreviousSDL(ctx context.Context, s *store.Store, instanceID string, databaseName string) (string, error) {
+ // Get the database to access the last applied release
+ database, err := s.GetDatabase(ctx, &store.FindDatabaseMessage{
InstanceID: &instanceID,
DatabaseName: &databaseName,
- TypeList: []string{storepb.ChangelogPayload_SDL.String()}, // Only SDL migrations
- Status: &doneStatus,
- Limit: &limit, // Get only the most recent one
- ShowFull: true, // Get full schema
})
if err != nil {
- return "", nil, errors.Wrapf(err, "failed to list previous SDL changelogs for database %s", databaseName)
- }
-
- if len(changelogs) == 0 {
- // No previous SDL changelogs found - this is fine, we'll use initialization scenario
- return "", nil, nil
- }
-
- mostRecentChangelog := changelogs[0] // ListChangelogs should return them in descending order by creation time
-
- // Retrieve the previous SDL text by following the reference chain:
- // changelog -> task_run -> task -> release -> file -> sheet
- var previousUserSDLText string
- if taskRunName := mostRecentChangelog.Payload.GetTaskRun(); taskRunName != "" {
- // Parse task run name to get task ID
- _, _, _, taskID, _, err := common.GetProjectIDPlanIDStageIDTaskIDTaskRunID(taskRunName)
- if err == nil {
- // Get the task
- task, err := s.GetTaskByID(ctx, taskID)
- if err == nil && task != nil {
- // Get the release from the task
- if releaseName := task.Payload.GetRelease(); releaseName != "" {
- projectID, releaseID, err := common.GetProjectReleaseID(releaseName)
- if err == nil {
- release, err := s.GetRelease(ctx, &store.FindReleaseMessage{
- ProjectID: &projectID,
- ReleaseID: &releaseID,
- })
- if err == nil && release != nil {
- // For SDL/declarative releases, there should be exactly one file
- if len(release.Payload.Files) == 1 {
- file := release.Payload.Files[0]
- sheet, err := s.GetSheetFull(ctx, file.SheetSha256)
- if err == nil && sheet != nil {
- previousUserSDLText = sheet.Statement
- }
- }
- }
- }
- }
- }
- }
+ return "", errors.Wrapf(err, "failed to get database %s", databaseName)
+ }
+ if database == nil {
+ return "", errors.Errorf("database %s not found", databaseName)
}
- // Get the previous schema from sync history
- // Use SyncHistoryUID (after applying the SDL) instead of PrevSyncHistoryUID (before applying)
- // This represents the database schema state after the previous SDL was successfully applied
- var previousSchema *model.DatabaseMetadata
- if mostRecentChangelog.SyncHistoryUID != nil {
- // Get the sync history record to obtain the schema metadata
- syncHistory, err := s.GetSyncHistoryByUID(ctx, *mostRecentChangelog.SyncHistoryUID)
- if err != nil {
- return "", nil, errors.Wrapf(err, "failed to get sync history by UID %d", *mostRecentChangelog.SyncHistoryUID)
- }
+ // Get the previous SDL text from the database's release field
+ if database.Metadata == nil || database.Metadata.Release == "" {
+ return "", nil
+ }
- if syncHistory != nil && syncHistory.Metadata != nil {
- // Get instance to determine engine and case sensitivity
- instance, err := s.GetInstance(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
- if err != nil {
- return "", nil, errors.Wrapf(err, "failed to get instance %s", instanceID)
- }
- if instance == nil {
- return "", nil, errors.Errorf("instance %s not found", instanceID)
- }
+ // Parse release name to get project ID and release ID
+ projectID, releaseID, err := common.GetProjectReleaseID(database.Metadata.Release)
+ if err != nil {
+ slog.Warn("Failed to parse release name, treating as initialization", "release", database.Metadata.Release, "error", err)
+ return "", nil
+ }
- // Create a DatabaseSchema wrapper using the metadata from sync history
- previousSchema = model.NewDatabaseMetadata(
- syncHistory.Metadata,
- []byte(syncHistory.Schema), // Use the schema content from sync history
- &storepb.DatabaseConfig{}, // Empty config
- instance.Metadata.GetEngine(),
- store.IsObjectCaseSensitive(instance),
- )
- }
+ // Load the release
+ release, err := s.GetRelease(ctx, &store.FindReleaseMessage{
+ ProjectID: &projectID,
+ ReleaseID: &releaseID,
+ })
+ if err != nil {
+ slog.Warn("Failed to get release, treating as initialization", "project", projectID, "release", releaseID, "error", err)
+ return "", nil
+ }
+ if release == nil {
+ slog.Warn("Release not found, treating as initialization", "project", projectID, "release", releaseID)
+ return "", nil
+ }
+
+ // For SDL/declarative releases, there should be exactly one file
+ if len(release.Payload.Files) != 1 {
+ slog.Warn("Unexpected number of files in SDL release, treating as initialization", "expected", 1, "got", len(release.Payload.Files))
+ return "", nil
+ }
+
+ file := release.Payload.Files[0]
+ sheet, err := s.GetSheetFull(ctx, file.SheetSha256)
+ if err != nil {
+ slog.Warn("Failed to get sheet, treating as initialization", "sha256", file.SheetSha256, "error", err)
+ return "", nil
+ }
+ if sheet == nil {
+ slog.Warn("Sheet not found, treating as initialization", "sha256", file.SheetSha256)
+ return "", nil
}
- return previousUserSDLText, previousSchema, nil
+ return sheet.Statement, nil
}
// computeNeedDump determines if schema dump is needed based on task type and statements.
diff --git a/backend/store/changelog.go b/backend/store/changelog.go
index 3fe525a723..40b7c7f30b 100644
--- a/backend/store/changelog.go
+++ b/backend/store/changelog.go
@@ -43,7 +43,6 @@ type FindChangelogMessage struct {
InstanceID *string
DatabaseName *string
- TypeList []string
Status *ChangelogStatus
CreatedAtBefore *time.Time
CreatedAtAfter *time.Time
@@ -197,9 +196,6 @@ func (s *Store) ListChangelogs(ctx context.Context, find *FindChangelogMessage)
if find.HasSyncHistory {
q.And("changelog.sync_history_id IS NOT NULL")
}
- if len(find.TypeList) > 0 {
- q.And("changelog.payload->>'type' = ANY(?)", find.TypeList)
- }
if v := find.CreatedAtBefore; v != nil {
q.And("changelog.created_at <= ?", *v)
}
diff --git a/backend/tests/action_test.go b/backend/tests/action_test.go
index 4c120e106b..4d6865c58b 100644
--- a/backend/tests/action_test.go
+++ b/backend/tests/action_test.go
@@ -966,17 +966,8 @@ func TestActionRolloutCommand(t *testing.T) {
Parent: database.Name,
}))
a.NoError(err)
- // Expect at least 1 changelog (MIGRATE), possibly 2 if BASELINE was created
+ // Expect at least 1 changelog for the versioned release
a.GreaterOrEqual(len(changelogs.Msg.Changelogs), 1, "Expected at least 1 changelog for the versioned release")
- // Verify at least one MIGRATE changelog exists
- foundMigrateChangelog := false
- for _, changelog := range changelogs.Msg.Changelogs {
- if changelog.Type == v1pb.Changelog_MIGRATE {
- foundMigrateChangelog = true
- break
- }
- }
- a.True(foundMigrateChangelog, "Expected to find at least one MIGRATE changelog")
revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{
Parent: database.Name,
diff --git a/backend/tests/pg_sdl_rollout_test.go b/backend/tests/pg_sdl_rollout_test.go
index 9502c5e007..6390ea057c 100644
--- a/backend/tests/pg_sdl_rollout_test.go
+++ b/backend/tests/pg_sdl_rollout_test.go
@@ -2,7 +2,6 @@ package tests
import (
"context"
- "database/sql"
"fmt"
"strings"
"testing"
@@ -258,57 +257,6 @@ CREATE TABLE "public"."posts" (
len(result.ExecutedStatements),
strings.Join(result.ExecutedStatements, "\n---\n"))
})
-
- t.Run("DriftDetection", func(t *testing.T) {
- a := require.New(t)
-
- // Create unique database name
- dbName := fmt.Sprintf("sdl_drift_%s", strings.ReplaceAll(uuid.New().String()[:8], "-", ""))
-
- // Create database directly in PostgreSQL
- _, err := pgContainer.db.Exec(fmt.Sprintf("CREATE DATABASE %s", dbName))
- a.NoError(err)
-
- // Create database in Bytebase
- err = ctl.createDatabase(ctx, ctl.project, instance, nil, dbName, "postgres")
- a.NoError(err)
-
- // Get database
- databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{
- Name: fmt.Sprintf("%s/databases/%s", instance.Name, dbName),
- }))
- a.NoError(err)
- database := databaseResp.Msg
-
- // Create initial schema via SDL
- initialSDL := `CREATE TABLE "public"."users" (
- "id" serial NOT NULL,
- "name" varchar(255) NOT NULL,
- CONSTRAINT "pk_users" PRIMARY KEY ("id")
-);`
-
- _, err = executeSDLRolloutWithResult(ctx, ctl, database, initialSDL)
- a.NoError(err)
-
- // Introduce drift by directly modifying the database
- directExecuteSQL(pgContainer, database, `ALTER TABLE "public"."users" ADD COLUMN "email" varchar(255);`)
- _, err = ctl.databaseServiceClient.SyncDatabase(ctx, connect.NewRequest(&v1pb.SyncDatabaseRequest{
- Name: database.Name,
- }))
- a.NoError(err)
-
- // Verify drift was introduced
- a.True(verifyColumnExists(ctx, ctl, database, "users", "email"))
-
- // Re-apply original SDL to fix drift
- result, err := executeSDLRolloutWithResult(ctx, ctl, database, initialSDL)
- a.NoError(err)
- a.NotEmpty(result.ExecutedStatements, "Expected statements to fix drift")
-
- // Verify drift was fixed (email column should be removed)
- a.False(verifyColumnExists(ctx, ctl, database, "users", "email"))
- a.Equal(2, getTableColumnCount(ctx, ctl, database, "users"))
- })
}
// executeSDLRolloutWithResult performs a complete SDL rollout and returns the result including executed SQL.
@@ -501,24 +449,3 @@ func getTableColumnCount(ctx context.Context, ctl *controller, database *v1pb.Da
}
return 0
}
-
-// directExecuteSQL executes SQL directly on the database (for drift tests).
-func directExecuteSQL(pgContainer *Container, database *v1pb.Database, sqlStmt string) {
- // Extract database name from resource name
- parts := strings.Split(database.Name, "/")
- dbName := parts[len(parts)-1]
-
- // Connect to the specific database
- connStr := fmt.Sprintf("host=%s port=%s user=postgres password=root-password dbname=%s sslmode=disable",
- pgContainer.host, pgContainer.port, dbName)
- db, err := sql.Open("pgx", connStr)
- if err != nil {
- panic(err)
- }
- defer db.Close()
-
- _, err = db.Exec(sqlStmt)
- if err != nil {
- panic(err)
- }
-}
diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.go
index 258684c3b0..2e1e734192 100644
--- a/backend/tests/schema_update_test.go
+++ b/backend/tests/schema_update_test.go
@@ -96,15 +96,12 @@ func TestSchemaAndDataUpdate(t *testing.T) {
// Expect 3 changelogs: 2 migrations + baseline (auto-created on first migration)
a.Equal(3, len(changelogs))
// First changelog should be the data update migration (most recent)
- a.Equal(v1pb.Changelog_MIGRATE, changelogs[0].Type)
a.Equal(v1pb.Changelog_DONE, changelogs[0].Status)
a.Equal(dumpedSchema, changelogs[0].Schema)
// Second changelog should be the schema migration
- a.Equal(v1pb.Changelog_MIGRATE, changelogs[1].Type)
a.Equal(v1pb.Changelog_DONE, changelogs[1].Status)
a.Equal(dumpedSchema, changelogs[1].Schema)
// Third changelog should be the baseline
- a.Equal(v1pb.Changelog_BASELINE, changelogs[2].Type)
a.Equal(v1pb.Changelog_DONE, changelogs[2].Status)
}
diff --git a/backend/tests/sync_schema_test.go b/backend/tests/sync_schema_test.go
index ee49497df4..92ca7d1443 100644
--- a/backend/tests/sync_schema_test.go
+++ b/backend/tests/sync_schema_test.go
@@ -98,10 +98,6 @@ DROP SCHEMA IF EXISTS "schema_a";
changelogs := resp.Msg.Changelogs
// Expect 2 changelogs: baseline (auto-created on first migration) + migration
a.Equal(2, len(changelogs))
- // First changelog should be the migration (most recent)
- a.Equal(v1pb.Changelog_MIGRATE, changelogs[0].Type)
- // Second changelog should be the baseline
- a.Equal(v1pb.Changelog_BASELINE, changelogs[1].Type)
err = ctl.createDatabase(ctx, ctl.project, instance, nil /* environment */, newDatabaseName, "bytebase")
a.NoError(err)
diff --git a/docs/adding-new-object-to-sdl-mode.md b/docs/adding-new-object-to-sdl-mode.md
index f0845521f2..09eca8d7cf 100644
--- a/docs/adding-new-object-to-sdl-mode.md
+++ b/docs/adding-new-object-to-sdl-mode.md
@@ -209,11 +209,11 @@ func ChunkSDLText(sdlText string) (*schema.SDLChunks, error) {
Add a call to process the new object type:
```go
-func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseSchema) (*schema.MetadataDiff, error) {
+func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema *model.DatabaseMetadata) (*schema.MetadataDiff, error) {
// ... parse SDL ...
// Process table changes
- err = processTableChanges(currentChunks, previousChunks, currentSchema, previousSchema, currentDBSDLChunks, diff)
+ err = processTableChanges(currentChunks, previousChunks, currentSchema, currentDBSDLChunks, diff)
if err != nil {
return nil, errors.Wrap(err, "failed to process table changes")
}
@@ -462,94 +462,6 @@ The comment processing system needs to know which objects are being created or d
---
-### 2.5 Implement Drift Handling (REQUIRED)
-
-Drift handling synchronizes SDL chunks with actual database state when they differ. **This is mandatory for all object types.**
-
-This is needed when:
-- User's SDL file doesn't match database state
-- Auto-sync is enabled
-- Database schema differs from SDL (drift detection)
-
-**Without this implementation, the object type will not work correctly in drift scenarios.**
-
-**File**: `backend/plugin/schema/pg/get_sdl_diff.go`
-
-```go
-func applyMaterializedViewChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema) error {
- // Build maps of current and previous materialized views from database metadata
- currentMVs := make(map[string]*storepb.MaterializedViewMetadata)
- for _, schema := range currentSchema.Schemas {
- for _, mv := range schema.MaterializedViews {
- key := schema.Name + "." + mv.Name
- currentMVs[key] = mv
- }
- }
-
- previousMVs := make(map[string]*storepb.MaterializedViewMetadata)
- for _, schema := range previousSchema.Schemas {
- for _, mv := range schema.MaterializedViews {
- key := schema.Name + "." + mv.Name
- previousMVs[key] = mv
- }
- }
-
- // Handle additions: objects exist in DB but not in SDL chunks
- for key, mv := range currentMVs {
- if _, exists := previousMVs[key]; !exists {
- if err := createMaterializedViewChunk(previousChunks, mv); err != nil {
- return err
- }
- }
- }
-
- // Handle updates: objects exist in both but differ
- for key, currentMV := range currentMVs {
- if previousMV, exists := previousMVs[key]; exists {
- if err := updateMaterializedViewChunkIfNeeded(previousChunks, currentMV, previousMV); err != nil {
- return err
- }
- }
- }
-
- // Handle deletions: objects exist in SDL but not in DB
- for key := range previousMVs {
- if _, exists := currentMVs[key]; !exists {
- deleteMaterializedViewChunk(previousChunks, key)
- }
- }
-
- return nil
-}
-```
-
-Then call it in `applyMinimalChangesToChunks`:
-
-```go
-func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema) error {
- // Process table changes
- if err := applyTableChangesToChunks(previousChunks, currentSchema, previousSchema); err != nil {
- return errors.Wrap(err, "failed to apply table changes")
- }
-
- // Process view changes
- if err := applyViewChangesToChunks(previousChunks, currentSchema, previousSchema); err != nil {
- return errors.Wrap(err, "failed to apply view changes")
- }
-
- // Process materialized view changes
- if err := applyMaterializedViewChangesToChunks(previousChunks, currentSchema, previousSchema); err != nil { // ✅ Add
- return errors.Wrap(err, "failed to apply materialized view changes")
- }
-
- // ... other object types ...
-
- return nil
-}
-```
-
----
-
## Phase 3: Migration Generation
This is the **most critical phase** where dependency ordering happens.
@@ -1466,7 +1378,7 @@ func TestMaterializedViewSDLDiff(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -1645,7 +1557,7 @@ func TestMaterializedViewCommentMigrationGeneration(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -1769,7 +1681,7 @@ func TestMaterializedViewDependencyOrder(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil)
require.NoError(t, err)
require.NotNil(t, diff)
@@ -2080,8 +1992,6 @@ Use this checklist to ensure complete implementation:
- [ ] Registered in `processCommentChanges`
- [ ] Registered in `buildCreatedObjectsSet`
- [ ] Registered in `buildDroppedObjectsSet`
-- [ ] **Drift handling implemented (`applyXXXChangesToChunks`) - REQUIRED**
-- [ ] **Drift handler called in `applyMinimalChangesToChunks` - REQUIRED**
#### Migration Generation - CREATE
- [ ] Comment type registered in `differ.go`
@@ -2131,7 +2041,7 @@ Use this checklist to ensure complete implementation:
Adding a new database object to SDL mode requires changes in **6 major phases**:
1. **Parser**: Extract AST nodes and associate COMMENT statements
-2. **SDL Diff**: Detect CREATE/DROP/MODIFY and comment-only changes + **Drift handling (REQUIRED)**
+2. **SDL Diff**: Detect CREATE/DROP/MODIFY and comment-only changes
3. **Migration Generation**: Add to topological sort with **AST-only dependency extraction** (both CREATE and DROP!)
4. **SDL Output**: Generate single-file and multi-file SDL formats
5. **Testing**: Comprehensive tests including dependency ordering
@@ -2148,20 +2058,10 @@ Without this, migrations will have wrong ordering in `bb rollout` (SDL mode), le
Always implement and test dependency ordering with the `TestXXXDependencyOrder` test!
-### 2. Drift handling implementation (REQUIRED!)
-> **`applyXXXChangesToChunks` function and call in `applyMinimalChangesToChunks`**
-
-Without this, the object type will not work correctly when:
-- User's SDL file doesn't match database state
-- Auto-sync is enabled
-- Database schema differs from SDL (drift detection)
-
-All other object types (tables, views, functions, sequences, materialized views) implement drift handling. Your new object type must too.
-
-### 3. Archive schema filter (MOST CRITICAL - Breaks production!)
+### 2. Archive schema filter (CRITICAL - Breaks production!)
> **Add object to `FilterPostgresArchiveSchema` in `differ.go`**
-This is **the #1 mistake** that:
+This is **a critical mistake** that:
- ✅ Passes all unit tests
- ✅ Works correctly in SDL parsing and diff calculation
- ❌ **Silently fails in production `bb rollout`**
diff --git a/frontend/src/components/Changelog/ChangelogDataTable.vue b/frontend/src/components/Changelog/ChangelogDataTable.vue
index e4826aa0a0..b862ea9539 100644
--- a/frontend/src/components/Changelog/ChangelogDataTable.vue
+++ b/frontend/src/components/Changelog/ChangelogDataTable.vue
@@ -20,11 +20,8 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { getDateForPbTimestampProtoEs } from "@/types";
import type { Changelog } from "@/types/proto-es/v1/database_service_pb";
-import {
- Changelog_Status,
- Changelog_Type,
-} from "@/types/proto-es/v1/database_service_pb";
-import { changelogLink, getChangelogChangeType } from "@/utils/v1/changelog";
+import { Changelog_Status } from "@/types/proto-es/v1/database_service_pb";
+import { changelogLink } from "@/utils/v1/changelog";
import HumanizeDate from "../misc/HumanizeDate.vue";
import ChangelogStatusIcon from "./ChangelogStatusIcon.vue";
@@ -93,13 +90,6 @@ const columnList = computed(() => {
},
render: (changelog) => changelog.planTitle || "-",
},
- {
- key: "type",
- title: t("changelog.change-type"),
- width: 120,
- resizable: true,
- render: (changelog) => getChangelogChangeType(changelog.type),
- },
];
return columns.filter((col) => !col.hide);
});
@@ -123,11 +113,6 @@ const rowProps = (changelog: Changelog) => {
};
const allowToSelectChangelog = (changelog: Changelog) => {
- return (
- changelog.status === Changelog_Status.DONE &&
- (changelog.type === Changelog_Type.BASELINE ||
- changelog.type === Changelog_Type.MIGRATE ||
- changelog.type === Changelog_Type.SDL)
- );
+ return changelog.status === Changelog_Status.DONE;
};
</script>
diff --git a/frontend/src/components/Changelog/ChangelogDetail.vue b/frontend/src/components/Changelog/ChangelogDetail.vue
index a53315703c..c5e0ee00bb 100644
--- a/frontend/src/components/Changelog/ChangelogDetail.vue
+++ b/frontend/src/components/Changelog/ChangelogDetail.vue
@@ -18,7 +18,6 @@
<div class="flex items-center gap-x-3 text-sm text-control-light">
<div class="flex items-center gap-x-2">
<ChangelogStatusIcon :status="changelog.status" />
- <span>{{ getChangelogChangeType(changelog.type) }}</span>
</div>
<span v-if="formattedCreateTime">•</span>
<span v-if="formattedCreateTime">
@@ -134,7 +133,6 @@ import { getDateForPbTimestampProtoEs } from "@/types";
import type { Changelog } from "@/types/proto-es/v1/database_service_pb";
import {
Changelog_Status,
- Changelog_Type,
ChangelogView,
} from "@/types/proto-es/v1/database_service_pb";
import {
@@ -142,7 +140,6 @@ import {
extractProjectResourceName,
wrapRefAsPromise,
} from "@/utils";
-import { getChangelogChangeType } from "@/utils/v1/changelog";
import { instanceV1SupportsSchemaRollback } from "@/utils/v1/instance";
import ChangelogStatusIcon from "./ChangelogStatusIcon.vue";
@@ -221,7 +218,7 @@ const allowShowDiff = computed((): boolean => {
if (!changelog.value) {
return false;
}
- return changelog.value.type === Changelog_Type.MIGRATE;
+ return true;
});
// Get the previous changelog's schema as the "before" state for diff
@@ -247,10 +244,7 @@ const allowRollback = computed((): boolean => {
) {
return false;
}
- return (
- changelog.value.type === Changelog_Type.MIGRATE &&
- changelog.value.status === Changelog_Status.DONE
- );
+ return changelog.value.status === Changelog_Status.DONE;
});
// Only show task run logs for completed or failed changelogs
@@ -308,10 +302,8 @@ watch(
state.previousChangelog = undefined;
}
- // Show diff by default for MIGRATE changelogs
- if (changelog.value.type === Changelog_Type.MIGRATE) {
- state.showDiff = true;
- }
+ // Show diff by default for all changelogs
+ state.showDiff = true;
}
state.loading = false;
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue
index e1e6007b40..401154372c 100644
--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorActionPopover.vue
@@ -49,7 +49,6 @@ const shouldShowInstanceRoleSelect = computed(() => {
if (engine !== Engine.POSTGRES) {
return false;
}
- // Only works for DDL/DML, exclude creating database and schema baseline.
if (selectedTask.value.type !== Task_Type.DATABASE_MIGRATE) {
return false;
}
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
index b96b396e15..09544a55a6 100644
--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
@@ -287,7 +287,6 @@ const allowEditStatementWhenCreating = computed(() => {
/**
* to set the MonacoEditor as readonly
* This happens when
- * - BASELINE issue
* - Not in edit mode
* - Disallowed to edit statement
*/
diff --git a/frontend/src/components/SyncDatabaseSchemaV1/ChangelogSelector.vue b/frontend/src/components/SyncDatabaseSchemaV1/ChangelogSelector.vue
index 3c19af9809..6f73488420 100644
--- a/frontend/src/components/SyncDatabaseSchemaV1/ChangelogSelector.vue
+++ b/frontend/src/components/SyncDatabaseSchemaV1/ChangelogSelector.vue
@@ -23,10 +23,7 @@ import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResource
import { useChangelogStore, useDatabaseV1Store } from "@/store";
import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";
import type { Changelog } from "@/types/proto-es/v1/database_service_pb";
-import {
- Changelog_Status,
- Changelog_Type,
-} from "@/types/proto-es/v1/database_service_pb";
+import { Changelog_Status } from "@/types/proto-es/v1/database_service_pb";
import {
isValidChangelogName,
mockLatestChangelog,
@@ -42,11 +39,6 @@ const emit = defineEmits<{
(event: "update:value", value: string | undefined): void;
}>();
-const ALLOWED_CHANGELOG_TYPES: Changelog_Type[] = [
- Changelog_Type.BASELINE,
- Changelog_Type.MIGRATE,
-];
-
const changelogStore = useChangelogStore();
const databaseStore = useDatabaseV1Store();
const remoteResourceSelectorRef =
@@ -83,10 +75,7 @@ const handleSearch = async (params: {
parent: props.database,
pageToken: params.pageToken,
pageSize: params.pageSize,
- filter: [
- `status == "${Changelog_Status[Changelog_Status.DONE]}"`,
- `type in [${ALLOWED_CHANGELOG_TYPES.map((t) => `"${Changelog_Type[t]}"`).join(", ")}]`,
- ].join(" && "),
+ filter: `status == "${Changelog_Status[Changelog_Status.DONE]}"`,
}
);
@@ -128,9 +117,6 @@ const renderSchemaVersionLabel = (
class="text-control-light"
date={getDateForPbTimestampProtoEs(resource.createTime)}
/>
- <NTag round size="small">
- {Changelog_Type[resource.type]}
- </NTag>
{resource.planTitle && (
<NTag round size="small">
{resource.planTitle}
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index d0d0c426a8..38499ceeaa 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -216,7 +216,6 @@
"resource-not-found": "Resource not found",
"continue-anyway": "Continue anyway",
"permissions": "Permissions",
- "baseline": "Baseline",
"leave-without-saving": "Leave without saving?",
"configure-now": "Configure now",
"connection": "Connection",
@@ -1641,10 +1640,6 @@
"changelog": {
"self": "Changelog",
"select": "Schema version is recorded each time a schema change is applied via Bytebase",
- "change-type": "Type",
- "type": {
- "migrate": "Migrate"
- },
"no-schema-change": "this migration has no schema change",
"show-diff": "Show diff",
"schema-snapshot-after-change": "The schema snapshot recorded after applying this change",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 8717a10493..6d4a94c064 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -216,7 +216,6 @@
"resource-not-found": "Recurso no encontrado",
"continue-anyway": "De todas maneras, continúe",
"permissions": "Permisos",
- "baseline": "Base",
"leave-without-saving": "¿Salir sin ahorrar?",
"configure-now": "Configurar ahora",
"connection": "Conexión",
@@ -1641,10 +1640,6 @@
"changelog": {
"self": "Historial de cambios",
"select": "La versión del esquema se registra cada vez que se aplica un cambio de esquema a través de Bytebase",
- "change-type": "Tipo",
- "type": {
- "migrate": "Migrar"
- },
"no-schema-change": "esta migración no tiene cambios de esquema",
"show-diff": "Mostrar diferencias",
"schema-snapshot-after-change": "La instantánea de esquema registrada después de aplicar este cambio",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index adc3a99381..d4f4ee59a8 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -216,7 +216,6 @@
"resource-not-found": "リソースが見つかりません",
"continue-anyway": "まだ続けたい",
"permissions": "権限",
- "baseline": "ベースライン",
"leave-without-saving": "変更を保存していませんか?",
"configure-now": "今すぐ設定する",
"connection": "接続する",
@@ -1641,10 +1640,6 @@
"changelog": {
"self": "変更履歴",
"select": "スキーマのバージョンは、Bytebase を通じてスキーマの変更が実行されるたびに記録されます。",
- "change-type": "タイプ",
- "type": {
- "migrate": "マイグレート"
- },
"no-schema-change": "この変更ではスキーマの変更はありません",
"show-diff": "違いを表示",
"schema-snapshot-after-change": "この変更を完了した後のスキーマのスナップショット",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index dfd05313b9..1fe728006c 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -216,7 +216,6 @@
"resource-not-found": "Không tìm thấy tài nguyên",
"continue-anyway": "Tiếp tục",
"permissions": "Quyền",
- "baseline": "Đường cơ sở",
"leave-without-saving": "Thoát mà không lưu?",
"configure-now": "Cấu hình ngay",
"connection": "Kết nối",
@@ -1641,10 +1640,6 @@
"changelog": {
"self": "Nhật ký thay đổi",
"select": "Phiên bản lược đồ được ghi lại mỗi khi thay đổi lược đồ được áp dụng qua Bytebase",
- "change-type": "Loại thay đổi",
- "type": {
- "migrate": "Di chuyển"
- },
"no-schema-change": "di chuyển này không có thay đổi lược đồ",
"show-diff": "Hiển thị khác biệt",
"schema-snapshot-after-change": "Ảnh chụp nhanh lược đồ được ghi lại sau khi áp dụng thay đổi này",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 3a2f3cac0c..80e6f19b27 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -216,7 +216,6 @@
"resource-not-found": "未找到请求的资源",
"continue-anyway": "仍要继续",
"permissions": "权限",
- "baseline": "基线",
"leave-without-saving": "不保存变动?",
"configure-now": "现在配置",
"connection": "连接",
@@ -1641,10 +1640,6 @@
"changelog": {
"self": "变更历史",
"select": "Schema 版本是在每次通过 Bytebase 执行 Schema 变更后被记录下来的",
- "change-type": "类型",
- "type": {
- "migrate": "变更"
- },
"no-schema-change": "本次变更没有任何 Schema 的改动",
"show-diff": "显示差异",
"schema-snapshot-after-change": "完成这次变更后的 schema 快照",
diff --git a/frontend/src/types/proto-es/v1/database_service_pb.d.ts b/frontend/src/types/proto-es/v1/database_service_pb.d.ts
index f5ab7bbf7e..accde2c492 100644
--- a/frontend/src/types/proto-es/v1/database_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/database_service_pb.d.ts
@@ -2944,12 +2944,10 @@ export declare type ListChangelogsRequest = Message<"bytebase.v1.ListChangelogsR
*
* Supported filter:
* - status: the changelog status, support "==" operation. check Changelog.Status for available values.
- * - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
* - create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
*
* Example:
* status == "DONE"
- * type in ["BASELINE", "MIGRATE"]
* status == "FAILED" && type == "SDL"
* create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
*
@@ -3059,11 +3057,6 @@ export declare type Changelog = Message<"bytebase.v1.Changelog"> & {
* @generated from field: string plan_title = 15;
*/
planTitle: string;
-
- /**
- * @generated from field: bytebase.v1.Changelog.Type type = 14;
- */
- type: Changelog_Type;
};
/**
@@ -3102,36 +3095,6 @@ export enum Changelog_Status {
*/
export declare const Changelog_StatusSchema: GenEnum<Changelog_Status>;
-/**
- * @generated from enum bytebase.v1.Changelog.Type
- */
-export enum Changelog_Type {
- /**
- * @generated from enum value: TYPE_UNSPECIFIED = 0;
- */
- TYPE_UNSPECIFIED = 0,
-
- /**
- * @generated from enum value: BASELINE = 1;
- */
- BASELINE = 1,
-
- /**
- * @generated from enum value: MIGRATE = 2;
- */
- MIGRATE = 2,
-
- /**
- * @generated from enum value: SDL = 3;
- */
- SDL = 3,
-}
-
-/**
- * Describes the enum bytebase.v1.Changelog.Type.
- */
-export declare const Changelog_TypeSchema: GenEnum<Changelog_Type>;
-
/**
* @generated from message bytebase.v1.GetSchemaStringRequest
*/
diff --git a/frontend/src/types/proto-es/v1/database_service_pb.js b/frontend/src/types/proto-es/v1/database_service_pb.js
index 21327ded9b..649772e06d 100644
--- a/frontend/src/types/proto-es/v1/database_service_pb.js
+++ b/frontend/src/types/proto-es/v1/database_service_pb.js
@@ -16,7 +16,7 @@ import { file_v1_instance_service } from "./instance_service_pb";
* Describes the file v1/database_service.proto.
*/
export const file_v1_database_service = /*@__PURE__*/
- fileDesc("Chl2MS9kYXRhYmFzZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJBChJHZXREYXRhYmFzZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2UidwoYQmF0Y2hHZXREYXRhYmFzZXNSZXF1ZXN0Ei0KBnBhcmVudBgBIAEoCUId4EEC+kEXEhVieXRlYmFzZS5jb20vRGF0YWJhc2USLAoFbmFtZXMYAiADKAlCHeBBAvpBFwoVYnl0ZWJhc2UuY29tL0RhdGFiYXNlIkUKGUJhdGNoR2V0RGF0YWJhc2VzUmVzcG9uc2USKAoJZGF0YWJhc2VzGAEgAygLMhUuYnl0ZWJhc2UudjEuRGF0YWJhc2UipAEKFExpc3REYXRhYmFzZXNSZXF1ZXN0Ei0KBnBhcmVudBgBIAEoCUId4EEC+kEXEhVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkSDgoGZmlsdGVyGAQgASgJEhQKDHNob3dfZGVsZXRlZBgFIAEoCBIQCghvcmRlcl9ieRgGIAEoCSJaChVMaXN0RGF0YWJhc2VzUmVzcG9uc2USKAoJZGF0YWJhc2VzGAEgAygLMhUuYnl0ZWJhc2UudjEuRGF0YWJhc2USFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJIo0BChVVcGRhdGVEYXRhYmFzZVJlcXVlc3QSLAoIZGF0YWJhc2UYASABKAsyFS5ieXRlYmFzZS52MS5EYXRhYmFzZUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAMgASgIImgKG0JhdGNoVXBkYXRlRGF0YWJhc2VzUmVxdWVzdBIOCgZwYXJlb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GViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_instance_service]);
+ fileDesc("Chl2MS9kYXRhYmFzZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJBChJHZXREYXRhYmFzZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2UidwoYQmF0Y2hHZXREYXRhYmFzZXNSZXF1ZXN0Ei0KBnBhcmVudBgBIAEoCUId4EEC+kEXEhVieXRlYmFzZS5jb20vRGF0YWJhc2USLAoFbmFtZXMYAiADKAlCHeBBAvpBFwoVYnl0ZWJhc2UuY29tL0RhdGFiYXNlIkUKGUJhdGNoR2V0RGF0YWJhc2VzUmVzcG9uc2USKAoJZGF0YWJhc2VzGAEgAygLMhUuYnl0ZWJhc2UudjEuRGF0YWJhc2UipAEKFExpc3REYXRhYmFzZXNSZXF1ZXN0Ei0KBnBhcmVudBgBIAEoCUId4EEC+kEXEhVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkSDgoGZmlsdGVyGAQgASgJEhQKDHNob3dfZGVsZXRlZBgFIAEoCBIQCghvcmRlcl9ieRgGIAEoCSJaChVMaXN0RGF0YWJhc2VzUmVzcG9uc2USKAoJZGF0YWJhc2VzGAEgAygLMhUuYnl0ZWJhc2UudjEuRGF0YWJhc2USFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJIo0BChVVcGRhdGVEYXRhYmFzZVJlcXVlc3QSLAoIZGF0YWJhc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0ZWJhc2UudjFCFERhdGFiYXNlU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_instance_service]);
/**
* Describes the message bytebase.v1.GetDatabaseRequest.
@@ -509,18 +509,6 @@ export const Changelog_StatusSchema = /*@__PURE__*/
export const Changelog_Status = /*@__PURE__*/
tsEnum(Changelog_StatusSchema);
-/**
- * Describes the enum bytebase.v1.Changelog.Type.
- */
-export const Changelog_TypeSchema = /*@__PURE__*/
- enumDesc(file_v1_database_service, 54, 1);
-
-/**
- * @generated from enum bytebase.v1.Changelog.Type
- */
-export const Changelog_Type = /*@__PURE__*/
- tsEnum(Changelog_TypeSchema);
-
/**
* Describes the message bytebase.v1.GetSchemaStringRequest.
* Use `create(GetSchemaStringRequestSchema)` to create a new message.
diff --git a/frontend/src/utils/v1/changelog.ts b/frontend/src/utils/v1/changelog.ts
index c4bd88eb3b..78d13536a8 100644
--- a/frontend/src/utils/v1/changelog.ts
+++ b/frontend/src/utils/v1/changelog.ts
@@ -1,13 +1,9 @@
import { create } from "@bufbuild/protobuf";
-import { t } from "@/plugins/i18n";
import { useDatabaseV1Store } from "@/store";
import type { ComposedDatabase } from "@/types";
import { UNKNOWN_ID } from "@/types";
import type { Changelog } from "@/types/proto-es/v1/database_service_pb";
-import {
- Changelog_Type,
- ChangelogSchema,
-} from "@/types/proto-es/v1/database_service_pb";
+import { ChangelogSchema } from "@/types/proto-es/v1/database_service_pb";
import { databaseV1Url, extractDatabaseResourceName } from "./database";
export const extractChangelogUID = (name: string) => {
@@ -54,16 +50,3 @@ export const mockLatestChangelog = (
schemaSize: BigInt(new TextEncoder().encode(schema).length),
});
};
-
-export const getChangelogChangeType = (type: Changelog_Type) => {
- switch (type) {
- case Changelog_Type.SDL:
- return "SDL";
- case Changelog_Type.MIGRATE:
- return t("changelog.type.migrate");
- case Changelog_Type.BASELINE:
- return t("common.baseline");
- default:
- return "-";
- }
-};
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 54af01857e..472f2389fc 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -1615,12 +1615,10 @@ paths:
Supported filter:
- status: the changelog status, support "==" operation. check Changelog.Status for available values.
- - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
- create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
Example:
status == "DONE"
- type in ["BASELINE", "MIGRATE"]
status == "FAILED" && type == "SDL"
create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
schema:
@@ -1632,12 +1630,10 @@ paths:
Supported filter:
- status: the changelog status, support "==" operation. check Changelog.Status for available values.
- - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
- create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
Example:
status == "DONE"
- type in ["BASELINE", "MIGRATE"]
status == "FAILED" && type == "SDL"
create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
responses:
@@ -11265,9 +11261,6 @@ components:
The title of the plan associated with this changelog's task run.
This field is populated by deriving the plan from task_run for display purposes.
readOnly: true
- type:
- title: type
- $ref: '#/components/schemas/bytebase.v1.Changelog.Type'
title: Changelog
additionalProperties: false
bytebase.v1.Changelog.Status:
@@ -11278,14 +11271,6 @@ components:
- PENDING
- DONE
- FAILED
- bytebase.v1.Changelog.Type:
- type: string
- title: Type
- enum:
- - TYPE_UNSPECIFIED
- - BASELINE
- - MIGRATE
- - SDL
bytebase.v1.ChangelogView:
type: string
title: ChangelogView
@@ -14871,12 +14856,10 @@ components:
Supported filter:
- status: the changelog status, support "==" operation. check Changelog.Status for available values.
- - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
- create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
Example:
status == "DONE"
- type in ["BASELINE", "MIGRATE"]
status == "FAILED" && type == "SDL"
create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
title: ListChangelogsRequest
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index e6b3bf1c44..0f322165d0 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -38,8 +38,6 @@
- [store/changelog.proto](#store_changelog-proto)
- [ChangelogPayload](#bytebase-store-ChangelogPayload)
- - [ChangelogPayload.Type](#bytebase-store-ChangelogPayload-Type)
-
- [store/database.proto](#store_database-proto)
- [BoundingBox](#bytebase-store-BoundingBox)
- [CheckConstraintMetadata](#bytebase-store-CheckConstraintMetadata)
@@ -809,7 +807,6 @@ Metadata about the request.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| task_run | [string](#string) | | Format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}/taskRuns/{taskRun} |
-| type | [ChangelogPayload.Type](#bytebase-store-ChangelogPayload-Type) | | |
| git_commit | [string](#string) | | |
@@ -818,20 +815,6 @@ Metadata about the request.
-
-<a name="bytebase-store-ChangelogPayload-Type"></a>
-
-### ChangelogPayload.Type
-
-
-| Name | Number | Description |
-| ---- | ------ | ----------- |
-| TYPE_UNSPECIFIED | 0 | |
-| BASELINE | 1 | |
-| MIGRATE | 2 | |
-| SDL | 3 | |
-
-
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index f0b8cc75e8..997edec961 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -307,10 +307,6 @@
</li>
- <li>
- <a href="#bytebase.store.ChangelogPayload.Type"><span class="badge">E</span>ChangelogPayload.Type</a>
- </li>
-
</ul>
@@ -2751,13 +2747,6 @@ This information is not authenticated and should be treated accordingly. </p></t
<td><p>Format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}/taskRuns/{taskRun} </p></td>
</tr>
- <tr>
- <td>type</td>
- <td><a href="#bytebase.store.ChangelogPayload.Type">ChangelogPayload.Type</a></td>
- <td></td>
- <td><p> </p></td>
- </tr>
-
<tr>
<td>git_commit</td>
<td><a href="#string">string</a></td>
@@ -2774,41 +2763,6 @@ This information is not authenticated and should be treated accordingly. </p></t
- <h3 id="bytebase.store.ChangelogPayload.Type">ChangelogPayload.Type</h3>
- <p></p>
- <table class="enum-table">
- <thead>
- <tr><td>Name</td><td>Number</td><td>Description</td></tr>
- </thead>
- <tbody>
-
- <tr>
- <td>TYPE_UNSPECIFIED</td>
- <td>0</td>
- <td><p></p></td>
- </tr>
-
- <tr>
- <td>BASELINE</td>
- <td>1</td>
- <td><p></p></td>
- </tr>
-
- <tr>
- <td>MIGRATE</td>
- <td>2</td>
- <td><p></p></td>
- </tr>
-
- <tr>
- <td>SDL</td>
- <td>3</td>
- <td><p></p></td>
- </tr>
-
- </tbody>
- </table>
-
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index a450232609..39085da1cc 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -242,7 +242,6 @@
- [ViewMetadata](#bytebase-v1-ViewMetadata)
- [Changelog.Status](#bytebase-v1-Changelog-Status)
- - [Changelog.Type](#bytebase-v1-Changelog-Type)
- [ChangelogView](#bytebase-v1-ChangelogView)
- [ColumnMetadata.IdentityGeneration](#bytebase-v1-ColumnMetadata-IdentityGeneration)
- [GenerationMetadata.Type](#bytebase-v1-GenerationMetadata-Type)
@@ -3284,7 +3283,6 @@ BoundingBox defines the spatial bounds for GEOMETRY spatial indexes.
| schema_size | [int64](#int64) | | |
| task_run | [string](#string) | | Format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}/taskRuns/{taskRun} |
| plan_title | [string](#string) | | The title of the plan associated with this changelog&#39;s task run. This field is populated by deriving the plan from task_run for display purposes. |
-| type | [Changelog.Type](#bytebase-v1-Changelog-Type) | | |
@@ -3858,9 +3856,9 @@ When paginating, all other parameters provided must match the call that provided
| view | [ChangelogView](#bytebase-v1-ChangelogView) | | |
| filter | [string](#string) | | Filter is used to filter changelogs returned in the list. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
-Supported filter: - status: the changelog status, support &#34;==&#34; operation. check Changelog.Status for available values. - type: the changelog type, support &#34;in&#34; and &#34;==&#34; operation. check Changelog.Type for available values. - create_time: the changelog create time in &#34;2006-01-02T15:04:05Z07:00&#34; format, support &#34;&gt;=&#34; or &#34;&lt;=&#34; operator.
+Supported filter: - status: the changelog status, support &#34;==&#34; operation. check Changelog.Status for available values. - create_time: the changelog create time in &#34;2006-01-02T15:04:05Z07:00&#34; format, support &#34;&gt;=&#34; or &#34;&lt;=&#34; operator.
-Example: status == &#34;DONE&#34; type in [&#34;BASELINE&#34;, &#34;MIGRATE&#34;] status == &#34;FAILED&#34; &amp;&amp; type == &#34;SDL&#34; create_time &gt;= &#34;2024-01-01T00:00:00Z&#34; &amp;&amp; create_time &lt;= &#34;2024-01-02T00:00:00Z&#34; |
+Example: status == &#34;DONE&#34; status == &#34;FAILED&#34; &amp;&amp; type == &#34;SDL&#34; create_time &gt;= &#34;2024-01-01T00:00:00Z&#34; &amp;&amp; create_time &lt;= &#34;2024-01-02T00:00:00Z&#34; |
@@ -4316,20 +4314,6 @@ ViewMetadata is the metadata for views.
-<a name="bytebase-v1-Changelog-Type"></a>
-
-### Changelog.Type
-
-
-| Name | Number | Description |
-| ---- | ------ | ----------- |
-| TYPE_UNSPECIFIED | 0 | |
-| BASELINE | 1 | |
-| MIGRATE | 2 | |
-| SDL | 3 | |
-
-
-
<a name="bytebase-v1-ChangelogView"></a>
### ChangelogView
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 868ef34a34..d44c9983e3 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -1095,10 +1095,6 @@
<a href="#bytebase.v1.Changelog.Status"><span class="badge">E</span>Changelog.Status</a>
</li>
- <li>
- <a href="#bytebase.v1.Changelog.Type"><span class="badge">E</span>Changelog.Type</a>
- </li>
-
<li>
<a href="#bytebase.v1.ChangelogView"><span class="badge">E</span>ChangelogView</a>
</li>
@@ -9635,13 +9631,6 @@ A maximum of 1000 databases can be modified in a batch. </p></td>
This field is populated by deriving the plan from task_run for display purposes. </p></td>
</tr>
- <tr>
- <td>type</td>
- <td><a href="#bytebase.v1.Changelog.Type">Changelog.Type</a></td>
- <td></td>
- <td><p> </p></td>
- </tr>
-
</tbody>
</table>
@@ -11189,12 +11178,10 @@ The syntax and semantics of CEL are documented at https://github.com/google/cel-
Supported filter:
- status: the changelog status, support &#34;==&#34; operation. check Changelog.Status for available values.
-- type: the changelog type, support &#34;in&#34; and &#34;==&#34; operation. check Changelog.Type for available values.
- create_time: the changelog create time in &#34;2006-01-02T15:04:05Z07:00&#34; format, support &#34;&gt;=&#34; or &#34;&lt;=&#34; operator.
Example:
status == &#34;DONE&#34;
-type in [&#34;BASELINE&#34;, &#34;MIGRATE&#34;]
status == &#34;FAILED&#34; &amp;&amp; type == &#34;SDL&#34;
create_time &gt;= &#34;2024-01-01T00:00:00Z&#34; &amp;&amp; create_time &lt;= &#34;2024-01-02T00:00:00Z&#34; </p></td>
</tr>
@@ -12674,41 +12661,6 @@ In this situation, `update_mask` is ignored. </p></td>
</tbody>
</table>
- <h3 id="bytebase.v1.Changelog.Type">Changelog.Type</h3>
- <p></p>
- <table class="enum-table">
- <thead>
- <tr><td>Name</td><td>Number</td><td>Description</td></tr>
- </thead>
- <tbody>
-
- <tr>
- <td>TYPE_UNSPECIFIED</td>
- <td>0</td>
- <td><p></p></td>
- </tr>
-
- <tr>
- <td>BASELINE</td>
- <td>1</td>
- <td><p></p></td>
- </tr>
-
- <tr>
- <td>MIGRATE</td>
- <td>2</td>
- <td><p></p></td>
- </tr>
-
- <tr>
- <td>SDL</td>
- <td>3</td>
- <td><p></p></td>
- </tr>
-
- </tbody>
- </table>
-
<h3 id="bytebase.v1.ChangelogView">ChangelogView</h3>
<p></p>
<table class="enum-table">
diff --git a/proto/store/store/changelog.proto b/proto/store/store/changelog.proto
index a3c5f2b9a3..5db8237eee 100644
--- a/proto/store/store/changelog.proto
+++ b/proto/store/store/changelog.proto
@@ -10,13 +10,5 @@ message ChangelogPayload {
// Format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}/taskRuns/{taskRun}
string task_run = 1;
- enum Type {
- TYPE_UNSPECIFIED = 0;
- BASELINE = 1;
- MIGRATE = 2;
- SDL = 3;
- }
- Type type = 5;
-
string git_commit = 6;
}
diff --git a/proto/v1/v1/database_service.proto b/proto/v1/v1/database_service.proto
index 5e4122ad3e..16b43c3016 100644
--- a/proto/v1/v1/database_service.proto
+++ b/proto/v1/v1/database_service.proto
@@ -1381,12 +1381,10 @@ message ListChangelogsRequest {
//
// Supported filter:
// - status: the changelog status, support "==" operation. check Changelog.Status for available values.
- // - type: the changelog type, support "in" and "==" operation. check Changelog.Type for available values.
// - create_time: the changelog create time in "2006-01-02T15:04:05Z07:00" format, support ">=" or "<=" operator.
//
// Example:
// status == "DONE"
- // type in ["BASELINE", "MIGRATE"]
// status == "FAILED" && type == "SDL"
// create_time >= "2024-01-01T00:00:00Z" && create_time <= "2024-01-02T00:00:00Z"
string filter = 5;
@@ -1440,14 +1438,6 @@ message Changelog {
// The title of the plan associated with this changelog's task run.
// This field is populated by deriving the plan from task_run for display purposes.
string plan_title = 15 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- enum Type {
- TYPE_UNSPECIFIED = 0;
- BASELINE = 1;
- MIGRATE = 2;
- SDL = 3;
- }
- Type type = 14;
}
message GetSchemaStringRequest {