github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/services/shared/schema_test.go (about) 1 package shared 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/stretchr/testify/require" 8 9 "github.com/authzed/spicedb/internal/datastore/memdb" 10 "github.com/authzed/spicedb/internal/testfixtures" 11 "github.com/authzed/spicedb/pkg/datastore" 12 "github.com/authzed/spicedb/pkg/schemadsl/compiler" 13 "github.com/authzed/spicedb/pkg/schemadsl/input" 14 ) 15 16 func TestApplySchemaChanges(t *testing.T) { 17 require := require.New(t) 18 rawDS, err := memdb.NewMemdbDatastore(0, 0, memdb.DisableGC) 19 require.NoError(err) 20 21 // Write the initial schema. 22 ds, _ := testfixtures.DatastoreFromSchemaAndTestRelationships(rawDS, ` 23 definition user {} 24 25 definition document { 26 relation viewer: user 27 permission view = viewer 28 } 29 30 caveat hasFortyTwo(value int) { 31 value == 42 32 } 33 `, nil, require) 34 35 // Update the schema and ensure it works. 36 compiled, err := compiler.Compile(compiler.InputSchema{ 37 Source: input.Source("schema"), 38 SchemaString: ` 39 definition user {} 40 41 definition organization { 42 relation member: user 43 permission admin = member 44 } 45 46 caveat catchTwentyTwo(value int) { 47 value == 22 48 } 49 `, 50 }, compiler.AllowUnprefixedObjectType()) 51 require.NoError(err) 52 53 validated, err := ValidateSchemaChanges(context.Background(), compiled, false) 54 require.NoError(err) 55 56 _, err = ds.ReadWriteTx(context.Background(), func(ctx context.Context, rwt datastore.ReadWriteTransaction) error { 57 applied, err := ApplySchemaChanges(context.Background(), rwt, validated) 58 require.NoError(err) 59 60 require.Equal(applied.NewObjectDefNames, []string{"organization"}) 61 require.Equal(applied.RemovedObjectDefNames, []string{"document"}) 62 require.Equal(applied.NewCaveatDefNames, []string{"catchTwentyTwo"}) 63 require.Equal(applied.RemovedCaveatDefNames, []string{"hasFortyTwo"}) 64 65 orgDef, err := rwt.LookupNamespacesWithNames(ctx, []string{"organization"}) 66 require.NoError(err) 67 require.Len(orgDef, 1) 68 69 require.NotEmpty(orgDef[0].Definition.Relation[0].CanonicalCacheKey) 70 require.NotEmpty(orgDef[0].Definition.Relation[1].CanonicalCacheKey) 71 return nil 72 }) 73 require.NoError(err) 74 }