MCPcopy Create free account
hub / github.com/bytebase/bytebase / MigrateSchema

Function MigrateSchema

backend/migrator/migrator.go:44–127  ·  view source on GitHub ↗

MigrateSchema migrates the schema for metadata database.

(ctx context.Context, db *sql.DB)

Source from the content-addressed store, hash-verified

42
43// MigrateSchema migrates the schema for metadata database.
44func MigrateSchema(ctx context.Context, db *sql.DB) error {
45 // Acquire advisory lock to ensure only one replica runs migrations.
46 // This blocks until the lock is available.
47 lock, err := store.AcquireAdvisoryLock(ctx, db, store.AdvisoryLockKeyMigration)
48 if err != nil {
49 return errors.Wrap(err, "failed to acquire migration lock")
50 }
51 defer func() {
52 if err := lock.Release(); err != nil {
53 slog.Error("Failed to release migration advisory lock", log.BBError(err))
54 }
55 }()
56
57 files, err := getSortedVersionedFiles()
58 if err != nil {
59 return err
60 }
61
62 conn, err := db.Conn(ctx)
63 if err != nil {
64 return err
65 }
66 defer conn.Close()
67
68 var ok bool
69 if err := conn.QueryRowContext(ctx,
70 `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'principal')`,
71 ).Scan(&ok); err != nil {
72 return err
73 }
74
75 latestVersion := files[len(files)-1].version.String()
76 // Initialize the latest schema.
77 if !ok {
78 buf, err := migrationFS.ReadFile(latestSchemaFileName)
79 if err != nil {
80 return errors.Wrapf(err, "failed to read latest schema %q", latestSchemaFileName)
81 }
82 if err := executeMigration(ctx, conn, string(buf), latestVersion); err != nil {
83 return err
84 }
85 slog.Info(fmt.Sprintf("Initialized database schema with version %s.", latestVersion))
86 return nil
87 }
88
89 latestDatabaseVersion, err := getLatestDatabaseVersion(ctx, conn)
90 if err != nil {
91 return err
92 }
93 if latestDatabaseVersion == nil {
94 return errors.New("the latest database version is not found")
95 }
96
97 for _, f := range files {
98 if f.version.LE(*latestDatabaseVersion) {
99 continue
100 }
101

Callers 4

NewServerFunction · 0.92

Calls 11

AcquireAdvisoryLockFunction · 0.92
BBErrorFunction · 0.92
getSortedVersionedFilesFunction · 0.85
executeMigrationFunction · 0.85
getLatestDatabaseVersionFunction · 0.85
ReleaseMethod · 0.80
ScanMethod · 0.80
InfoMethod · 0.80
CloseMethod · 0.65
StringMethod · 0.65
ErrorMethod · 0.45

Tested by 3