summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/spicedb/pkg/validationfile/blocks/schema.go
blob: 814eebca0fe634c809cdc40981f54fc806edf7ed (plain)
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
package blocks

import (
	"errors"
	"fmt"

	yamlv3 "gopkg.in/yaml.v3"

	"github.com/ccoveille/go-safecast"

	"github.com/authzed/spicedb/pkg/schemadsl/compiler"
	"github.com/authzed/spicedb/pkg/schemadsl/input"
	"github.com/authzed/spicedb/pkg/spiceerrors"
)

// ParsedSchema is the parsed schema in a validationfile.
type ParsedSchema struct {
	// Schema is the schema found.
	Schema string

	// SourcePosition is the position of the schema in the file.
	SourcePosition spiceerrors.SourcePosition

	// CompiledSchema is the compiled schema.
	CompiledSchema *compiler.CompiledSchema
}

// UnmarshalYAML is a custom unmarshaller.
func (ps *ParsedSchema) UnmarshalYAML(node *yamlv3.Node) error {
	err := node.Decode(&ps.Schema)
	if err != nil {
		return convertYamlError(err)
	}

	compiled, err := compiler.Compile(compiler.InputSchema{
		Source:       input.Source("schema"),
		SchemaString: ps.Schema,
	}, compiler.AllowUnprefixedObjectType())
	if err != nil {
		var errWithContext compiler.WithContextError
		if errors.As(err, &errWithContext) {
			line, col, lerr := errWithContext.SourceRange.Start().LineAndColumn()
			if lerr != nil {
				return lerr
			}

			uintLine, err := safecast.ToUint64(line)
			if err != nil {
				return err
			}
			uintCol, err := safecast.ToUint64(col)
			if err != nil {
				return err
			}

			return spiceerrors.NewWithSourceError(
				fmt.Errorf("error when parsing schema: %s", errWithContext.BaseMessage),
				errWithContext.ErrorSourceCode,
				uintLine+1, // source line is 0-indexed
				uintCol+1,  // source col is 0-indexed
			)
		}

		return fmt.Errorf("error when parsing schema: %w", err)
	}

	ps.CompiledSchema = compiled
	ps.SourcePosition = spiceerrors.SourcePosition{LineNumber: node.Line, ColumnPosition: node.Column}
	return nil
}