-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema.go
75 lines (60 loc) · 1.55 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package repository
import (
"context"
"fmt"
"github.com/Masterminds/semver/v3"
"github.com/ttab/revisor"
"github.com/ttab/revisor/constraints"
)
func EnsureCoreSchema(ctx context.Context, store SchemaStore) error {
core, err := constraints.CoreSchema()
if err != nil {
return fmt.Errorf("failed to load core schema: %w", err)
}
coreVersion := constraints.CoreSchemaVersion()
for _, schema := range core {
err := EnsureSchema(ctx, store, schema.Name, coreVersion, schema)
if err != nil {
return fmt.Errorf("failed to ensure schema %q: %w",
schema.Name, err)
}
}
return nil
}
func EnsureSchema(
ctx context.Context, store SchemaStore,
name string, version string, schema revisor.ConstraintSet,
) error {
newVersion, err := semver.NewVersion(version)
if err != nil {
return fmt.Errorf("invalid version: %w", err)
}
versions, err := store.GetSchemaVersions(ctx)
if err != nil {
return fmt.Errorf("failed to read current schema versions: %w", err)
}
currentVersion, ok := versions[name]
register := !ok
if ok {
cV, err := semver.NewVersion(currentVersion)
if err != nil {
return fmt.Errorf("invalid version in database: %w", err)
}
register = newVersion.GreaterThan(cV)
}
if !register {
return nil
}
err = store.RegisterSchema(ctx, RegisterSchemaRequest{
Name: name,
Version: version,
Activate: true,
Specification: schema,
})
if IsDocStoreErrorCode(err, ErrCodeExists) {
return nil
} else if err != nil {
return fmt.Errorf("failed to register schema: %w", err)
}
return nil
}