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
This commit is contained in:
Timothy Messier committed 2021-10-08 06:50:26 -04:00
1 parent 217adfc4d2
commit 8caaf3e076
144 files changed
+3469 -11098

No files matched your search

+262 -135
View File
@@ -1,14 +1,14 @@
package schema
package schema_test
import (
"context"
"database/sql"
"sort"
"strings"
"testing"
"github.com/hashicorp/boundary/internal/db/common"
"github.com/hashicorp/boundary/internal/db/schema/postgres"
"github.com/hashicorp/boundary/internal/db/schema"
"github.com/hashicorp/boundary/internal/db/schema/internal/edition"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/testing/dbtest"
"github.com/stretchr/testify/assert"
@@ -27,13 +27,13 @@ func TestNewManager(t *testing.T) {
require.NoError(t, err)
ctx := context.Background()
_, err = NewManager(ctx, dialect, d)
_, err = schema.NewManager(ctx, schema.Dialect(dialect), d)
require.NoError(t, err)
_, err = NewManager(ctx, "unknown", d)
_, err = schema.NewManager(ctx, schema.Dialect("unknown"), d)
assert.True(t, errors.Match(errors.T(errors.InvalidParameter), err))
d.Close()
_, err = NewManager(ctx, dialect, d)
_, err = schema.NewManager(ctx, schema.Dialect(dialect), d)
assert.True(t, errors.Match(errors.T(errors.Op("schema.NewManager")), err))
}
@@ -51,32 +51,232 @@ func TestCurrentState(t *testing.T) {
d, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m, err := NewManager(ctx, dialect, d)
m, err := schema.NewManager(ctx, schema.Dialect(dialect), d, schema.WithEditions(
edition.Editions{
{
Name: "oss",
Dialect: schema.Postgres,
LatestVersion: 2,
Migrations: map[int][]byte{
2: []byte(`select 1`),
},
Priority: 0,
},
},
))
require.NoError(t, err)
want := &State{
BinarySchemaVersion: BinarySchemaVersion(dialect),
DatabaseSchemaVersion: nilVersion,
want := &schema.State{
Editions: []schema.EditionState{
{
Name: "oss",
BinarySchemaVersion: 2,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
},
}
s, err := m.CurrentState(ctx)
require.NoError(t, err)
assert.Equal(t, want, s)
testDriver, err := postgres.New(ctx, d)
require.NoError(t, err)
require.NoError(t, testDriver.EnsureVersionTable(ctx))
require.NoError(t, testDriver.Run(ctx, strings.NewReader("select 1"), 2))
assert.NoError(t, m.ApplyMigrations(ctx))
want = &State{
InitializationStarted: true,
BinarySchemaVersion: BinarySchemaVersion(dialect),
DatabaseSchemaVersion: 2,
want = &schema.State{
Initialized: true,
Editions: []schema.EditionState{
{
Name: "oss",
BinarySchemaVersion: 2,
DatabaseSchemaVersion: 2,
DatabaseSchemaState: schema.Equal,
},
},
}
s, err = m.CurrentState(ctx)
require.NoError(t, err)
assert.Equal(t, want, s)
assert.True(t, s.MigrationsApplied())
}
func TestRollForward(t *testing.T) {
func TestApplyMigration(t *testing.T) {
tests := []struct {
name string
editions edition.Editions
expectErr bool
state *schema.State
}{
{
"oneEdition",
edition.Editions{
edition.New("one", schema.Postgres, one, 0),
},
false,
&schema.State{
Initialized: true,
Editions: []schema.EditionState{
{
Name: "one",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: 1,
DatabaseSchemaState: schema.Equal,
},
},
},
},
{
"twoEditions",
edition.Editions{
edition.New("one", schema.Postgres, one, 0),
edition.New("two", schema.Postgres, two, 1),
},
false,
&schema.State{
Initialized: true,
Editions: []schema.EditionState{
{
Name: "one",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: 1,
DatabaseSchemaState: schema.Equal,
},
{
Name: "two",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: 1,
DatabaseSchemaState: schema.Equal,
},
},
},
},
{
"twoEditionsIncorrectPriority",
edition.Editions{
edition.New("one", schema.Postgres, one, 1),
edition.New("two", schema.Postgres, two, 0),
},
true,
&schema.State{
Initialized: false,
Editions: []schema.EditionState{
{
Name: "one",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
{
Name: "two",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
},
},
},
{
"threeEditions",
edition.Editions{
edition.New("one", schema.Postgres, one, 0),
edition.New("two", schema.Postgres, two, 1),
edition.New("three", schema.Postgres, three, 2),
},
false,
&schema.State{
Initialized: true,
Editions: []schema.EditionState{
{
Name: "one",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: 1,
DatabaseSchemaState: schema.Equal,
},
{
Name: "two",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: 1,
DatabaseSchemaState: schema.Equal,
},
{
Name: "three",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: 1,
DatabaseSchemaState: schema.Equal,
},
},
},
},
{
"threeEditionsIncorrectPriority",
edition.Editions{
edition.New("one", schema.Postgres, one, 0),
edition.New("two", schema.Postgres, two, 2),
edition.New("three", schema.Postgres, three, 1),
},
true,
&schema.State{
Initialized: false,
Editions: []schema.EditionState{
{
Name: "one",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
{
Name: "two",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
{
Name: "three",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dialect := dbtest.Postgres
c, u, _, err := dbtest.StartUsingTemplate(dialect, dbtest.WithTemplate(dbtest.Template1))
t.Cleanup(func() {
if err := c(); err != nil {
t.Fatalf("Got error at cleanup: %v", err)
}
})
require.NoError(t, err)
ctx := context.Background()
d, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m, err := schema.NewManager(ctx, schema.Dialect(dialect), d, schema.WithEditions(tt.editions))
require.NoError(t, err)
if tt.expectErr {
assert.Error(t, m.ApplyMigrations(ctx))
} else {
assert.NoError(t, m.ApplyMigrations(ctx))
}
s, err := m.CurrentState(ctx)
require.NoError(t, err)
assert.Equal(t, tt.state.Initialized, s.Initialized)
assert.ElementsMatch(t, tt.state.Editions, s.Editions)
if tt.expectErr {
assert.False(t, s.MigrationsApplied())
} else {
assert.True(t, s.MigrationsApplied())
}
})
}
}
func TestApplyMigration_canceledContext(t *testing.T) {
dialect := dbtest.Postgres
c, u, _, err := dbtest.StartUsingTemplate(dialect)
@@ -88,87 +288,16 @@ func TestRollForward(t *testing.T) {
require.NoError(t, err)
ctx := context.Background()
m, err := NewManager(ctx, dialect, d)
require.NoError(t, err)
assert.NoError(t, m.RollForward(ctx))
// Now set to dirty at an early version
_, err = postgres.New(ctx, d)
require.NoError(t, err)
// TODO: Extract out a way to mock the db to test failing rollforwards.
_, err = d.ExecContext(ctx, "TRUNCATE boundary_schema_version; INSERT INTO boundary_schema_version (version, dirty) VALUES (2, true)")
require.NoError(t, err)
assert.Error(t, m.RollForward(ctx))
}
func TestRollForward_NotFromFresh(t *testing.T) {
dialect := dbtest.Postgres
oState := migrationStates[dialect]
nState := createPartialMigrationState(oState, 8)
migrationStates[dialect] = nState
c, u, _, err := dbtest.StartUsingTemplate(dialect, dbtest.WithTemplate(dbtest.Template1))
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, c())
})
d, err := common.SqlOpen(dialect, u)
m, err := schema.NewManager(ctx, schema.Dialect(dialect), d)
require.NoError(t, err)
// Initialize the DB with only a portion of the current sql scripts.
ctx := context.Background()
m, err := NewManager(ctx, dialect, d)
require.NoError(t, err)
assert.NoError(t, m.RollForward(ctx))
state, err := m.CurrentState(ctx)
require.NoError(t, err)
assert.Equal(t, nState.binarySchemaVersion, state.DatabaseSchemaVersion)
assert.False(t, state.Dirty)
// Restore the full set of sql scripts and roll the rest of the way forward.
migrationStates[dialect] = oState
newM, err := NewManager(ctx, dialect, d)
require.NoError(t, err)
assert.NoError(t, newM.RollForward(ctx))
state, err = newM.CurrentState(ctx)
require.NoError(t, err)
assert.Equal(t, oState.binarySchemaVersion, state.DatabaseSchemaVersion)
assert.False(t, state.Dirty)
}
func TestRunMigration_canceledContext(t *testing.T) {
dialect := dbtest.Postgres
c, u, _, err := dbtest.StartUsingTemplate(dialect)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, c())
})
d, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
ctx := context.Background()
m, err := NewManager(ctx, dialect, d)
require.NoError(t, err)
// TODO: Find a way to test different parts of the runMigrations loop.
ctx, cancel := context.WithCancel(ctx)
cancel()
assert.Error(t, m.runMigrations(ctx, newStatementProvider(dialect, 0)))
assert.Error(t, m.ApplyMigrations(ctx))
}
func TestRollForward_BadSQL(t *testing.T) {
func TestApplyMigrations_BadSQL(t *testing.T) {
dialect := dbtest.Postgres
oState := migrationStates[dialect]
defer func() { migrationStates[dialect] = oState }()
nState := createPartialMigrationState(oState, 8)
nState.binarySchemaVersion = 10
nState.upMigrations[10] = []byte("SELECT 1 FROM NonExistantTable;")
migrationStates[dialect] = nState
c, u, _, err := dbtest.StartUsingTemplate(dialect, dbtest.WithTemplate(dbtest.Template1))
require.NoError(t, err)
@@ -180,14 +309,37 @@ func TestRollForward_BadSQL(t *testing.T) {
// Initialize the DB with only a portion of the current sql scripts.
ctx := context.Background()
m, err := NewManager(ctx, dialect, d)
m, err := schema.NewManager(ctx, schema.Dialect(dialect), d, schema.WithEditions(
edition.Editions{
{
Name: "oss",
Dialect: schema.Postgres,
LatestVersion: 1,
Migrations: map[int][]byte{
1: []byte(`select 1 from nonexistanttable;`),
},
Priority: 0,
},
},
))
require.NoError(t, err)
assert.Error(t, m.RollForward(ctx))
assert.Error(t, m.ApplyMigrations(ctx))
state, err := m.CurrentState(ctx)
require.NoError(t, err)
assert.Equal(t, nilVersion, state.DatabaseSchemaVersion)
assert.False(t, state.Dirty)
want := &schema.State{
Initialized: false,
Editions: []schema.EditionState{
{
Name: "oss",
BinarySchemaVersion: 1,
DatabaseSchemaVersion: schema.NilVersion,
DatabaseSchemaState: schema.Behind,
},
},
}
assert.Equal(t, want, state)
assert.False(t, state.MigrationsApplied())
}
func TestManager_ExclusiveLock(t *testing.T) {
@@ -201,12 +353,12 @@ func TestManager_ExclusiveLock(t *testing.T) {
})
d1, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m1, err := NewManager(ctx, dialect, d1)
m1, err := schema.NewManager(ctx, schema.Dialect(dialect), d1)
require.NoError(t, err)
d2, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m2, err := NewManager(ctx, dialect, d2)
m2, err := schema.NewManager(ctx, schema.Dialect(dialect), d2)
require.NoError(t, err)
assert.NoError(t, m1.ExclusiveLock(ctx))
@@ -224,14 +376,14 @@ func TestManager_SharedLock(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, c())
})
d1, err := common.SqlOpen("postgres", u)
d1, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m1, err := NewManager(ctx, "postgres", d1)
m1, err := schema.NewManager(ctx, schema.Dialect(dialect), d1)
require.NoError(t, err)
d2, err := common.SqlOpen("postgres", u)
d2, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m2, err := NewManager(ctx, "postgres", d2)
m2, err := schema.NewManager(ctx, schema.Dialect(dialect), d2)
require.NoError(t, err)
assert.NoError(t, m1.SharedLock(ctx))
@@ -253,22 +405,21 @@ func Test_GetMigrationLog(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, c())
})
d, err := common.SqlOpen("postgres", u)
d, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
m, err := NewManager(ctx, "postgres", d)
m, err := schema.NewManager(ctx, schema.Dialect(dialect), d)
require.NoError(t, err)
require.NoError(t, m.RollForward(ctx))
require.NoError(t, m.ApplyMigrations(ctx))
const insert = `insert into log_migration(entry) values ($1)`
const insert = `insert into log_migration(entry, edition) values ($1, $2)`
createEntries := func(entries ...string) {
for _, e := range entries {
_, err := d.Exec(insert, e)
_, err := d.Exec(insert, e, "oss")
require.NoError(t, err)
}
}
tests := []struct {
name string
d *sql.DB
setup func()
withDeleteLog bool
wantEntries []string
@@ -276,21 +427,15 @@ func Test_GetMigrationLog(t *testing.T) {
}{
{
name: "simple",
d: d,
setup: func() { createEntries("alice", "eve", "bob") },
wantEntries: []string{"alice", "eve", "bob"},
},
{
name: "with-delete-log",
d: d,
setup: func() { createEntries("alice", "eve", "bob") },
withDeleteLog: true,
wantEntries: []string{"alice", "eve", "bob"},
},
{
name: "missing-sql-DB",
wantErrMatch: errors.T(errors.InvalidParameter),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -303,7 +448,7 @@ func Test_GetMigrationLog(t *testing.T) {
if tt.setup != nil {
tt.setup()
}
gotLog, err := GetMigrationLog(ctx, tt.d, WithDeleteLog(tt.withDeleteLog))
gotLog, err := m.GetMigrationLog(ctx, schema.WithDeleteLog(tt.withDeleteLog))
if tt.wantErrMatch != nil {
require.Error(err)
assert.Truef(errors.Match(tt.wantErrMatch, err), "expected error with code: %s and got err: %q", tt.wantErrMatch.Code, err)
@@ -330,21 +475,3 @@ func Test_GetMigrationLog(t *testing.T) {
})
}
}
// Creates a new migrationState only with the versions <= the provided maxVer
func createPartialMigrationState(om migrationState, maxVer int) migrationState {
nState := migrationState{
upMigrations: make(map[int][]byte),
}
for k := range om.upMigrations {
if k > maxVer {
// Don't store any versions past our test version.
continue
}
nState.upMigrations[k] = om.upMigrations[k]
if nState.binarySchemaVersion < k {
nState.binarySchemaVersion = k
}
}
return nState
}