Skip to content

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

chore: store schema version (#16208)

Danny Xu42375962e8d3
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index a8475461b9..d7212eb563 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -1138,7 +1138,7 @@ func (s *DatabaseService) convertToDatabase(ctx context.Context, database *store
Project: common.FormatProject(database.ProjectID),
Environment: environment,
EffectiveEnvironment: effectiveEnvironment,
- SchemaVersion: database.SchemaVersion,
+ SchemaVersion: database.Metadata.GetVersion(),
Labels: database.Metadata.Labels,
InstanceResource: instanceResource,
BackupAvailable: database.Metadata.GetBackupAvailable(),
diff --git a/backend/migrator/migration/3.7/0006##backfill_database_metadata_version.sql b/backend/migrator/migration/3.7/0006##backfill_database_metadata_version.sql
new file mode 100644
index 0000000000..ca63dd15b8
--- /dev/null
+++ b/backend/migrator/migration/3.7/0006##backfill_database_metadata_version.sql
@@ -0,0 +1,25 @@
+-- Backfill database metadata version field from revision table
+UPDATE db
+SET metadata = jsonb_set(
+ COALESCE(metadata, '{}'::jsonb),
+ '{version}',
+ to_jsonb(COALESCE(
+ (
+ SELECT revision.version
+ FROM revision
+ WHERE revision.instance = db.instance
+ AND revision.db_name = db.name
+ AND deleted_at IS NOT NULL
+ ORDER BY revision.version DESC
+ LIMIT 1
+ ),
+ ''
+ ))
+)
+WHERE EXISTS (
+ SELECT 1
+ FROM revision
+ WHERE revision.instance = db.instance
+ AND revision.db_name = db.name
+ AND deleted_at IS NULL
+);
\ No newline at end of file
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 7ea5d7cf9d..2404b45f90 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -12,7 +12,7 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.7.5"), *files[len(files)-1].version)
+ require.Equal(t, semver.MustParse("3.7.6"), *files[len(files)-1].version)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index 520c77fd3e..eadb492b7a 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -19,6 +19,7 @@ import (
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/runner/schemasync"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/store/model"
"github.com/bytebase/bytebase/backend/utils"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -513,6 +514,23 @@ func endMigration(ctx context.Context, storeInstance *store.Store, mc *migrateCo
return errors.Wrapf(err, "failed to create revision")
}
update.RevisionUID = &revision.UID
+
+ // Update database metadata with the version only if the new version is greater
+ metadata := mc.database.Metadata
+ if metadata == nil {
+ metadata = &storepb.DatabaseMetadata{}
+ }
+
+ if shouldUpdateVersion(metadata.Version, mc.version) {
+ metadata.Version = mc.version
+ if _, err := storeInstance.UpdateDatabase(ctx, &store.UpdateDatabaseMessage{
+ InstanceID: mc.database.InstanceID,
+ DatabaseName: mc.database.DatabaseName,
+ Metadata: metadata,
+ }); err != nil {
+ return errors.Wrapf(err, "failed to update database metadata with version")
+ }
+ }
}
status := store.ChangelogStatusDone
update.Status = &status
@@ -528,6 +546,30 @@ func endMigration(ctx context.Context, storeInstance *store.Store, mc *migrateCo
return nil
}
+// shouldUpdateVersion checks if newVersion is greater than currentVersion.
+// Returns true if:
+// - currentVersion is empty
+// - currentVersion is invalid
+// - newVersion is greater than currentVersion
+func shouldUpdateVersion(currentVersion, newVersion string) bool {
+ if currentVersion == "" {
+ // If no current version, always update
+ return true
+ }
+ current, err := model.NewVersion(currentVersion)
+ if err != nil {
+ // If current version is invalid, update with new version
+ return true
+ }
+
+ nv, err := model.NewVersion(newVersion)
+ if err != nil {
+ // If new version is invalid, don't update
+ return false
+ }
+ return current.LessThan(nv)
+}
+
func convertTaskType(t base.TaskType) storepb.ChangelogPayload_Type {
switch t {
case base.TaskDatabaseDataUpdate:
diff --git a/backend/store/database.go b/backend/store/database.go
index 83eb84c894..f2e4d39c65 100644
--- a/backend/store/database.go
+++ b/backend/store/database.go
@@ -24,8 +24,6 @@ type DatabaseMessage struct {
Deleted bool
Metadata *storepb.DatabaseMetadata
- // Output only
- SchemaVersion string
}
func (d *DatabaseMessage) String() string {
@@ -393,16 +391,6 @@ func (*Store) listDatabaseImplV2(ctx context.Context, txn *sql.Tx, find *FindDat
db.instance,
db.name,
db.deleted,
- COALESCE(
- (
- SELECT revision.version
- FROM revision
- WHERE revision.instance = db.instance AND revision.db_name = db.name AND deleted_at IS NOT NULL
- ORDER BY revision.version DESC
- LIMIT 1
- ),
- ''
- ),
db.metadata
FROM db
LEFT JOIN instance ON db.instance = instance.resource_id
@@ -434,7 +422,6 @@ func (*Store) listDatabaseImplV2(ctx context.Context, txn *sql.Tx, find *FindDat
&databaseMessage.InstanceID,
&databaseMessage.DatabaseName,
&databaseMessage.Deleted,
- &databaseMessage.SchemaVersion,
&metadataString,
); err != nil {
return nil, err
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 1cc5cc2318..875ec99a00 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -9399,6 +9399,9 @@ components:
drifted:
type: boolean
description: The schema is drifted from the source of truth.
+ version:
+ type: string
+ description: The version of database schema.
description: DatabaseMetadata is the metadata for databases.
DatabaseSchema:
type: object
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 3b0c1b372d..bfb607975d 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -1134,6 +1134,7 @@ DatabaseMetadata is the metadata for databases.
| datashare | [bool](#bool) | | |
| secrets | [Secret](#bytebase-store-Secret) | repeated | |
| drifted | [bool](#bool) | | The schema is drifted from the source of truth. |
+| version | [string](#string) | | The version of database schema. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 42e63bbb6a..d68ec80725 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -3417,6 +3417,13 @@ classification and user_comment is parsed from the comment. </p></td>
<td><p>The schema is drifted from the source of truth. </p></td>
</tr>
+ <tr>
+ <td>version</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The version of database schema. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/generated-go/store/database.pb.go b/proto/generated-go/store/database.pb.go
index a2ad8ab5d2..4be4885a4c 100644
--- a/proto/generated-go/store/database.pb.go
+++ b/proto/generated-go/store/database.pb.go
@@ -409,7 +409,9 @@ type DatabaseMetadata struct {
Datashare bool `protobuf:"varint,4,opt,name=datashare,proto3" json:"datashare,omitempty"`
Secrets []*Secret `protobuf:"bytes,5,rep,name=secrets,proto3" json:"secrets,omitempty"`
// The schema is drifted from the source of truth.
- Drifted bool `protobuf:"varint,6,opt,name=drifted,proto3" json:"drifted,omitempty"`
+ Drifted bool `protobuf:"varint,6,opt,name=drifted,proto3" json:"drifted,omitempty"`
+ // The version of database schema.
+ Version string `protobuf:"bytes,7,opt,name=version,proto3" json:"version,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -486,6 +488,13 @@ func (x *DatabaseMetadata) GetDrifted() bool {
return false
}
+func (x *DatabaseMetadata) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
// DatabaseSchemaMetadata is the schema metadata for databases.
type DatabaseSchemaMetadata struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -3824,14 +3833,15 @@ var File_store_database_proto protoreflect.FileDescriptor
const file_store_database_proto_rawDesc = "" +
"\n" +
- "\x14store/database.proto\x12\x0ebytebase.store\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x12store/common.proto\"\xea\x02\n" +
+ "\x14store/database.proto\x12\x0ebytebase.store\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x12store/common.proto\"\x84\x03\n" +
"\x10DatabaseMetadata\x12D\n" +
"\x06labels\x18\x01 \x03(\v2,.bytebase.store.DatabaseMetadata.LabelsEntryR\x06labels\x12@\n" +
"\x0elast_sync_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\flastSyncTime\x12)\n" +
"\x10backup_available\x18\x03 \x01(\bR\x0fbackupAvailable\x12\x1c\n" +
"\tdatashare\x18\x04 \x01(\bR\tdatashare\x120\n" +
"\asecrets\x18\x05 \x03(\v2\x16.bytebase.store.SecretR\asecrets\x12\x18\n" +
- "\adrifted\x18\x06 \x01(\bR\adrifted\x1a9\n" +
+ "\adrifted\x18\x06 \x01(\bR\adrifted\x12\x18\n" +
+ "\aversion\x18\a \x01(\tR\aversion\x1a9\n" +
"\vLabelsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xb7\x03\n" +
diff --git a/proto/store/store/database.proto b/proto/store/store/database.proto
index 85c0f99cf4..57b4dc9a0d 100644
--- a/proto/store/store/database.proto
+++ b/proto/store/store/database.proto
@@ -17,6 +17,8 @@ message DatabaseMetadata {
repeated Secret secrets = 5;
// The schema is drifted from the source of truth.
bool drifted = 6;
+ // The version of database schema.
+ string version = 7;
}
// DatabaseSchemaMetadata is the schema metadata for databases.