Files
threshold/internal/db/schema/migrations/base.go
T
Timothy Messier 8caaf3e076 refactor(schema): Add support for migration editions
This refactors the schema package and subpackages to support editions.
An Edition is a collection of sql migrations. A given boundary binary
can have multiple migration editions. The `schema.Manager` is updated to
apply the necessary migrations in the correct order, leveraging an
Edition's priority to determine the order in which the separate Editions
are applied.

The sql migration files are now nested under a directory for the
edition.

This also switches from the generated code to using embed, which
eliminates the need for the `make migrations` target and the generated
code. As such this commit removes the target and generated code.

See:
    https://pkg.go.dev/embed
2021-10-08 06:50:26 -04:00

67 lines
1.9 KiB
Go

// Package migrations contains the base sql statements needed to bootstrap the
// migration process. These statements setup the tables necessary for tracking
// the state of migrations.
package migrations
import (
"embed"
"path/filepath"
"strings"
)
// postgres contains the sql for creating the base tables used to manage
// migrations.
//go:embed base/postgres
var postgres embed.FS
// Base contains the sql migrtaions needed to create the initial based tables used
// to manage other migrations.
// Unlike the other migrations these create statements represent the "current" state of the tables
// and are only used on a fresh install.
type base struct {
CreateSchemaVersion string
CreateLogMigration string
}
var baseByDialect map[string]base
func stripBeginCommit(c []byte) string {
contents := strings.TrimSpace(string(c))
if strings.ToLower(contents[:len("begin;")]) == "begin;" {
contents = contents[len("begin;"):]
}
if strings.ToLower(contents[len(contents)-len("commit;"):]) == "commit;" {
contents = contents[:len(contents)-len("commit;")]
}
contents = strings.TrimSpace(contents)
return contents
}
func newBase(root string, m embed.FS) base {
schemaVersion, err := m.ReadFile(filepath.Join(root, "01_boundary_schema_version.up.sql"))
if err != nil {
panic("missing base migration file 01_boundary_schema_version.up.sql")
}
logMigration, err := m.ReadFile(filepath.Join(root, "02_log_migration.up.sql"))
if err != nil {
panic("missing base migration file 02_log_migration.up.sql")
}
return base{
CreateSchemaVersion: stripBeginCommit(schemaVersion),
CreateLogMigration: stripBeginCommit(logMigration),
}
}
func init() {
baseByDialect = map[string]base{
"postgres": newBase("base/postgres", postgres),
}
}
// Base returns the base create statements for the given dialect.
func Base(dialect string) base {
return baseByDialect[dialect]
}