github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/datastore/common/helpers.go (about) 1 package common 2 3 import ( 4 "context" 5 "fmt" 6 7 "google.golang.org/protobuf/types/known/structpb" 8 9 "github.com/authzed/spicedb/pkg/datastore" 10 core "github.com/authzed/spicedb/pkg/proto/core/v1" 11 ) 12 13 // WriteTuples is a convenience method to perform the same update operation on a set of tuples 14 func WriteTuples(ctx context.Context, ds datastore.Datastore, op core.RelationTupleUpdate_Operation, tuples ...*core.RelationTuple) (datastore.Revision, error) { 15 updates := make([]*core.RelationTupleUpdate, 0, len(tuples)) 16 for _, tpl := range tuples { 17 rtu := &core.RelationTupleUpdate{ 18 Operation: op, 19 Tuple: tpl, 20 } 21 updates = append(updates, rtu) 22 } 23 return UpdateTuplesInDatastore(ctx, ds, updates...) 24 } 25 26 // UpdateTuplesInDatastore is a convenience method to perform multiple relation update operations on a Datastore 27 func UpdateTuplesInDatastore(ctx context.Context, ds datastore.Datastore, updates ...*core.RelationTupleUpdate) (datastore.Revision, error) { 28 return ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error { 29 return rwt.WriteRelationships(ctx, updates) 30 }) 31 } 32 33 // ContextualizedCaveatFrom convenience method that handles creation of a contextualized caveat 34 // given the possibility of arguments with zero-values. 35 func ContextualizedCaveatFrom(name string, context map[string]any) (*core.ContextualizedCaveat, error) { 36 var caveat *core.ContextualizedCaveat 37 if name != "" { 38 strct, err := structpb.NewStruct(context) 39 if err != nil { 40 return nil, fmt.Errorf("malformed caveat context: %w", err) 41 } 42 caveat = &core.ContextualizedCaveat{ 43 CaveatName: name, 44 Context: strct, 45 } 46 } 47 return caveat, nil 48 }