Skip to content

Commit aaa072b

Browse files
committed
x/exp/schema: make zero value of Schema work as expected
Signed-off-by: Phil Hassey <phil@strongdm.com>
1 parent 96673ca commit aaa072b

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

x/exp/schema/schema.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ func (s *Schema) SetFilename(filename string) {
2626

2727
// MarshalJSON encodes the Schema in the JSON format.
2828
func (s *Schema) MarshalJSON() ([]byte, error) {
29-
jsonSchema := (*json.Schema)(s.schema)
29+
jsonSchema := (*json.Schema)(s.astOrEmpty())
3030
return jsonSchema.MarshalJSON()
3131
}
3232

@@ -42,7 +42,7 @@ func (s *Schema) UnmarshalJSON(b []byte) error {
4242

4343
// MarshalCedar encodes the Schema in the human-readable format.
4444
func (s *Schema) MarshalCedar() ([]byte, error) {
45-
return parser.MarshalSchema(s.schema), nil
45+
return parser.MarshalSchema(s.astOrEmpty()), nil
4646
}
4747

4848
// UnmarshalCedar parses a Schema in the human-readable format.
@@ -57,10 +57,17 @@ func (s *Schema) UnmarshalCedar(b []byte) error {
5757

5858
// AST returns the underlying AST.
5959
func (s *Schema) AST() *ast.Schema {
60-
return s.schema
60+
return s.astOrEmpty()
6161
}
6262

6363
// Resolve returns a resolved.Schema with type references resolved and declarations indexed.
6464
func (s *Schema) Resolve() (*resolved.Schema, error) {
65-
return resolved.Resolve(s.schema)
65+
return resolved.Resolve(s.astOrEmpty())
66+
}
67+
68+
func (s *Schema) astOrEmpty() *ast.Schema {
69+
if s.schema == nil {
70+
return &ast.Schema{}
71+
}
72+
return s.schema
6673
}

x/exp/schema/schema_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,25 @@ func TestSchema(t *testing.T) {
720720
testutil.Error(t, err)
721721
})
722722

723+
t.Run("ZeroValueSchema", func(t *testing.T) {
724+
t.Parallel()
725+
var s schema.Schema
726+
727+
b, err := s.MarshalCedar()
728+
testutil.OK(t, err)
729+
testutil.Equals(t, string(b), "")
730+
731+
jb, err := s.MarshalJSON()
732+
testutil.OK(t, err)
733+
testutil.Equals(t, string(jb), "{}")
734+
735+
r, err := s.Resolve()
736+
testutil.OK(t, err)
737+
testutil.Equals(t, r != nil, true)
738+
739+
testutil.Equals(t, s.AST() != nil, true)
740+
})
741+
723742
t.Run("EmptySchema", func(t *testing.T) {
724743
t.Parallel()
725744
s := schema.NewSchemaFromAST(&ast.Schema{})

0 commit comments

Comments
 (0)