github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/validationfile/blocks/schema.go (about)

     1  package blocks
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	yamlv3 "gopkg.in/yaml.v3"
     8  
     9  	"github.com/authzed/spicedb/pkg/schemadsl/compiler"
    10  	"github.com/authzed/spicedb/pkg/schemadsl/input"
    11  	"github.com/authzed/spicedb/pkg/spiceerrors"
    12  )
    13  
    14  // ParsedSchema is the parsed schema in a validationfile.
    15  type ParsedSchema struct {
    16  	// Schema is the schema found.
    17  	Schema string
    18  
    19  	// SourcePosition is the position of the schema in the file.
    20  	SourcePosition spiceerrors.SourcePosition
    21  
    22  	// CompiledSchema is the compiled schema.
    23  	CompiledSchema *compiler.CompiledSchema
    24  }
    25  
    26  // UnmarshalYAML is a custom unmarshaller.
    27  func (ps *ParsedSchema) UnmarshalYAML(node *yamlv3.Node) error {
    28  	err := node.Decode(&ps.Schema)
    29  	if err != nil {
    30  		return convertYamlError(err)
    31  	}
    32  
    33  	compiled, err := compiler.Compile(compiler.InputSchema{
    34  		Source:       input.Source("schema"),
    35  		SchemaString: ps.Schema,
    36  	}, compiler.AllowUnprefixedObjectType())
    37  	if err != nil {
    38  		var errWithContext compiler.ErrorWithContext
    39  		if errors.As(err, &errWithContext) {
    40  			line, col, lerr := errWithContext.SourceRange.Start().LineAndColumn()
    41  			if lerr != nil {
    42  				return lerr
    43  			}
    44  
    45  			return spiceerrors.NewErrorWithSource(
    46  				fmt.Errorf("error when parsing schema: %s", errWithContext.BaseMessage),
    47  				errWithContext.ErrorSourceCode,
    48  				uint64(line+1), // source line is 0-indexed
    49  				uint64(col+1),  // source col is 0-indexed
    50  			)
    51  		}
    52  
    53  		return fmt.Errorf("error when parsing schema: %w", err)
    54  	}
    55  
    56  	ps.CompiledSchema = compiled
    57  	ps.SourcePosition = spiceerrors.SourcePosition{LineNumber: node.Line, ColumnPosition: node.Column}
    58  	return nil
    59  }