schema

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package schema provides functionality to convert Go types to Protobuf FileDescriptorSet.

Package schema provides comment and documentation support for proto generation.

Package schema provides types and constants for Protobuf Editions support.

Package schema provides types and functions for Protobuf Editions features support.

Package schema provides functionality to convert Go types to Protobuf FileDescriptorSet.

Package schema provides well-known types support for protobuf.

Index

Constants

View Source
const (
	// FileDescriptorProto field numbers
	FileDescriptorProtoNameField        = 1
	FileDescriptorProtoPackageField     = 2
	FileDescriptorProtoDependencyField  = 3
	FileDescriptorProtoMessageTypeField = 4
	FileDescriptorProtoEnumTypeField    = 5
	FileDescriptorProtoServiceField     = 6
	FileDescriptorProtoExtensionField   = 7
	FileDescriptorProtoOptionsField     = 8
	FileDescriptorProtoSourceCodeInfo   = 9

	// DescriptorProto (Message) field numbers
	DescriptorProtoNameField       = 1
	DescriptorProtoFieldField      = 2
	DescriptorProtoExtensionField  = 6
	DescriptorProtoNestedTypeField = 3
	DescriptorProtoEnumTypeField   = 4
	DescriptorProtoOneofDeclField  = 8

	// FieldDescriptorProto field numbers
	FieldDescriptorProtoNameField   = 1
	FieldDescriptorProtoNumberField = 3
	FieldDescriptorProtoLabelField  = 4
	FieldDescriptorProtoTypeField   = 5

	// ServiceDescriptorProto field numbers
	ServiceDescriptorProtoNameField   = 1
	ServiceDescriptorProtoMethodField = 2

	// MethodDescriptorProto field numbers
	MethodDescriptorProtoNameField       = 1
	MethodDescriptorProtoInputTypeField  = 2
	MethodDescriptorProtoOutputTypeField = 3
)

Field numbers for various descriptor types (from descriptor.proto)

View Source
const (
	Edition2023 = "2023"
	Edition2024 = "2024"
)

Edition constants for supported editions.

View Source
const (
	WellKnownTimestamp = ".google.protobuf.Timestamp"
	WellKnownDuration  = ".google.protobuf.Duration"
	WellKnownEmpty     = ".google.protobuf.Empty"
	WellKnownAny       = ".google.protobuf.Any"
	WellKnownValue     = ".google.protobuf.Value"
	WellKnownStruct    = ".google.protobuf.Struct"
	WellKnownListValue = ".google.protobuf.ListValue"
	WellKnownFieldMask = ".google.protobuf.FieldMask"
)

Well-known type names

View Source
const (
	TimestampProto = "google/protobuf/timestamp.proto"
	DurationProto  = "google/protobuf/duration.proto"
	EmptyProto     = "google/protobuf/empty.proto"
	AnyProto       = "google/protobuf/any.proto"
	StructProto    = "google/protobuf/struct.proto"
	WrappersProto  = "google/protobuf/wrappers.proto"
	FieldMaskProto = "google/protobuf/field_mask.proto"
)

Well-known type import paths

View Source
const (
	// DefaultGlobalCacheSize is the default size for the global cache
	DefaultGlobalCacheSize = 1000
)

Variables

View Source
var ErrSkipField = errors.New("skip field")

ErrSkipField is returned when a field should be skipped during processing.

Functions

func AddValidationMetadata

func AddValidationMetadata(field *descriptorpb.FieldDescriptorProto, validationTag string)

AddValidationMetadata adds validation metadata to a field descriptor.

func ApplyFeaturesToFieldOptions

func ApplyFeaturesToFieldOptions(fieldOptions *descriptorpb.FieldOptions, features *descriptorpb.FeatureSet)

ApplyFeaturesToFieldOptions applies features to FieldOptions for editions mode.

func ApplyFeaturesToFileOptions

func ApplyFeaturesToFileOptions(fileOptions *descriptorpb.FileOptions, features *descriptorpb.FeatureSet)

ApplyFeaturesToFileOptions applies features to FileOptions for editions mode.

func ApplyFeaturesToMessageOptions

func ApplyFeaturesToMessageOptions(messageOptions *descriptorpb.MessageOptions, features *descriptorpb.FeatureSet)

ApplyFeaturesToMessageOptions applies features to MessageOptions for editions mode.

func BuildFieldOptions

func BuildFieldOptions(rules []ValidationRule) *descriptorpb.FieldOptions

BuildFieldOptions creates protobuf field options from validation rules.

func BuildValidationComment

func BuildValidationComment(rules []ValidationRule) string

BuildValidationComment creates a comment string from validation rules.

func ConvertToProtobufValidation

func ConvertToProtobufValidation(validationTag string) map[string]any

ConvertToProtobufValidation converts go-playground/validator tags to protobuf validation rules.

func CreateFieldFeatures

func CreateFieldFeatures(parentFeatures *descriptorpb.FeatureSet, fieldCharacteristics FieldCharacteristics) *descriptorpb.FeatureSet

CreateFieldFeatures creates features for a field based on its characteristics and parent features.

func CreateFileFeatures

func CreateFileFeatures(edition string) *descriptorpb.FeatureSet

CreateFileFeatures creates a FeatureSet for file-level features based on the edition.

func ExtractCommentFromTag

func ExtractCommentFromTag(tag string) string

ExtractCommentFromTag extracts a comment from a struct tag. It looks for the "doc" key in the tag.

func ExtractProtoDoc

func ExtractProtoDoc(tag string) string

ExtractProtoDoc extracts message-level documentation from a special protoDoc tag.

func ExtractValidationFromJSONName

func ExtractValidationFromJSONName(jsonName string) (name, validation string)

ExtractValidationFromJSONName extracts the original name and validation from JsonName.

func GetDurationType

func GetDurationType() reflect.Type

GetDurationType returns the time.Duration type

func GetTimeType

func GetTimeType() reflect.Type

GetTimeType returns the time.Time type

func IsDurationType

func IsDurationType(t reflect.Type) bool

IsDurationType checks if a type is time.Duration

func IsEmptyType

func IsEmptyType(t reflect.Type, tag reflect.StructTag) bool

IsEmptyType checks if a type should be treated as google.protobuf.Empty

func IsTimeType

func IsTimeType(t reflect.Type) bool

IsTimeType checks if a type is time.Time

func MergeFeatures

func MergeFeatures(parent, child *descriptorpb.FeatureSet) *descriptorpb.FeatureSet

MergeFeatures merges child features with parent features. Child features override parent features where specified.

func SetGlobalCache

func SetGlobalCache(cache Cache)

SetGlobalCache sets a custom global cache.

func ShouldUseProto3Optional

func ShouldUseProto3Optional(syntaxMode SyntaxMode, features *descriptorpb.FeatureSet, isPointer bool) bool

ShouldUseProto3Optional determines if proto3_optional should be set based on features.

func StringToEdition

func StringToEdition(edition string) *descriptorpb.Edition

StringToEdition converts a string edition to the protobuf Edition enum.

func ValidateOneof

func ValidateOneof(structType reflect.Type, value any) error

ValidateOneof is a convenience function to validate oneof constraints

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder converts Go types to Protobuf FileDescriptorSet.

func NewBuilder

func NewBuilder(opts BuilderOptions) *Builder

NewBuilder creates a new schema builder.

func (*Builder) BuildMessage

func (b *Builder) BuildMessage(rt reflect.Type) (protoreflect.MessageDescriptor, error)

BuildMessage converts a Go type to a protoreflect.MessageDescriptor. BuildMessage builds a protoreflect.MessageDescriptor from a Go struct type.

func (*Builder) GetEdition

func (b *Builder) GetEdition() string

GetEdition returns the edition string

func (*Builder) GetFileDescriptorSet

func (b *Builder) GetFileDescriptorSet() *descriptorpb.FileDescriptorSet

GetFileDescriptorSet returns the complete FileDescriptorSet with all built messages.

func (*Builder) GetSyntaxMode

func (b *Builder) GetSyntaxMode() SyntaxMode

GetSyntaxMode returns the syntax mode of the builder

func (*Builder) GetWellKnownImports

func (b *Builder) GetWellKnownImports() map[string]bool

GetWellKnownImports returns the map of well-known imports

func (*Builder) HasWellKnownImports

func (b *Builder) HasWellKnownImports() bool

HasWellKnownImports returns true if any well-known imports are used

type BuilderOptions

type BuilderOptions struct {
	// PackageName is the protobuf package name to use
	PackageName string
	// EnablePGO enables Profile-Guided Optimization
	EnablePGO bool
	// MaxCacheSize limits the cache size (0 = unlimited)
	MaxCacheSize int

	// SyntaxMode specifies proto3 or editions mode
	SyntaxMode SyntaxMode
	// Edition specifies the edition year (e.g., "2023", "2024")
	Edition string
	// Features specifies the default feature set for editions mode
	Features *FeatureSet
}

BuilderOptions configures the schema builder.

type Cache

type Cache interface {
	GetMessage(key string) (protoreflect.MessageDescriptor, bool)
	PutMessage(key string, md protoreflect.MessageDescriptor)
	GetFile(key string) (*descriptorpb.FileDescriptorProto, bool)
	PutFile(key string, fd *descriptorpb.FileDescriptorProto)
	Clear()
	Size() int
}

Cache provides thread-safe caching for compiled descriptors.

func GetGlobalCache

func GetGlobalCache() Cache

GetGlobalCache returns the global cache instance.

type CommentInfo

type CommentInfo struct {
	Leading  string   // Comment appearing before the element
	Trailing string   // Comment appearing after the element on same line
	Detached []string // Detached comment blocks appearing before the element
}

CommentInfo holds documentation comments for a proto element.

type EnumType

type EnumType int

EnumType represents the enum type feature.

const (
	// EnumTypeUnknown is the default unset value.
	EnumTypeUnknown EnumType = iota
	// EnumTypeOpen allows unknown enum values.
	EnumTypeOpen
	// EnumTypeClosed rejects unknown enum values.
	EnumTypeClosed
)

type FeatureSet

type FeatureSet struct {
	FieldPresence         FieldPresence
	RepeatedFieldEncoding RepeatedFieldEncoding
	EnumType              EnumType
	UTF8Validation        UTF8Validation
}

FeatureSet represents the feature configuration for Protobuf Editions.

func DefaultEdition2023Features

func DefaultEdition2023Features() *FeatureSet

DefaultEdition2023Features returns the default feature set for Edition 2023.

func DefaultProto3Features

func DefaultProto3Features() *FeatureSet

DefaultProto3Features returns the default feature set for proto3.

func (*FeatureSet) Clone

func (fs *FeatureSet) Clone() *FeatureSet

Clone creates a copy of the FeatureSet.

type FieldCharacteristics

type FieldCharacteristics struct {
	IsRequired            bool
	ForceImplicitPresence bool
	ForceExplicitPresence bool
	ForceUnpacked         bool
	DefaultValue          string
}

FieldCharacteristics represents field-specific characteristics that affect features.

func ExtractFieldCharacteristics

func ExtractFieldCharacteristics(tags map[string]string) FieldCharacteristics

ExtractFieldCharacteristics extracts field characteristics from struct tags.

type FieldPresence

type FieldPresence int

FieldPresence represents the field presence feature.

const (
	// FieldPresenceUnknown is the default unset value.
	FieldPresenceUnknown FieldPresence = iota
	// FieldPresenceExplicit means fields have explicit presence tracking (like proto2 optional).
	FieldPresenceExplicit
	// FieldPresenceImplicit means fields have implicit presence (like proto3 default).
	FieldPresenceImplicit
	// FieldPresenceLegacyRequired means fields are required (like proto2 required).
	FieldPresenceLegacyRequired
)

type LRUCache

type LRUCache struct {
	// contains filtered or unexported fields
}

LRUCache implements an LRU cache for descriptors.

func NewLRUCache

func NewLRUCache(maxSize int) *LRUCache

NewLRUCache creates a new LRU cache with the specified max size.

func (*LRUCache) Clear

func (c *LRUCache) Clear()

Clear removes all entries from the cache.

func (*LRUCache) GetFile

func (c *LRUCache) GetFile(key string) (*descriptorpb.FileDescriptorProto, bool)

GetFile retrieves a file descriptor from the cache.

func (*LRUCache) GetMessage

func (c *LRUCache) GetMessage(key string) (protoreflect.MessageDescriptor, bool)

GetMessage retrieves a message descriptor from the cache.

func (*LRUCache) PutFile

func (c *LRUCache) PutFile(key string, fd *descriptorpb.FileDescriptorProto)

PutFile stores a file descriptor in the cache.

func (*LRUCache) PutMessage

func (c *LRUCache) PutMessage(key string, md protoreflect.MessageDescriptor)

PutMessage stores a message descriptor in the cache.

func (*LRUCache) Size

func (c *LRUCache) Size() int

Size returns the current size of the cache.

type OneofDetectionType

type OneofDetectionType int

OneofDetectionType indicates how a oneof group was detected

const (
	// OneofTypeStructTag detected via struct tag
	OneofTypeStructTag OneofDetectionType = iota
)

type OneofGroup

type OneofGroup struct {
	Name   string             // Group name (e.g., "identifier")
	Fields map[string]int     // Field name -> field index in struct
	Type   OneofDetectionType // How this oneof was detected
}

OneofGroup represents a detected oneof group

type OneofValidator

type OneofValidator struct {
	// contains filtered or unexported fields
}

OneofValidator validates oneof constraints

func NewOneofValidator

func NewOneofValidator(structType reflect.Type) *OneofValidator

NewOneofValidator creates a new oneof validator for a struct type

func (*OneofValidator) Validate

func (v *OneofValidator) Validate(value any) error

Validate checks that oneof constraints are satisfied

type PathBuilder

type PathBuilder struct {
	// contains filtered or unexported fields
}

PathBuilder helps build paths for SourceCodeInfo locations.

func NewPathBuilder

func NewPathBuilder() *PathBuilder

NewPathBuilder creates a new path builder.

func (*PathBuilder) Build

func (p *PathBuilder) Build() []int32

Build returns a copy of the current path.

func (*PathBuilder) Clone

func (p *PathBuilder) Clone() *PathBuilder

Clone creates a copy of the path builder.

func (*PathBuilder) Pop

func (p *PathBuilder) Pop() *PathBuilder

Pop removes the last element from the path.

func (*PathBuilder) Push

func (p *PathBuilder) Push(fieldNumberOrIndex int32) *PathBuilder

Push adds a field number or index to the path.

func (*PathBuilder) Reset

func (p *PathBuilder) Reset() *PathBuilder

Reset clears the path.

type RepeatedFieldEncoding

type RepeatedFieldEncoding int

RepeatedFieldEncoding represents the repeated field encoding feature.

const (
	// RepeatedFieldEncodingUnknown is the default unset value.
	RepeatedFieldEncodingUnknown RepeatedFieldEncoding = iota
	// RepeatedFieldEncodingPacked means repeated fields are packed.
	RepeatedFieldEncodingPacked
	// RepeatedFieldEncodingExpanded means repeated fields are not packed.
	RepeatedFieldEncodingExpanded
)

type SourceCodeInfoBuilder

type SourceCodeInfoBuilder struct {
	// contains filtered or unexported fields
}

SourceCodeInfoBuilder helps build SourceCodeInfo for a FileDescriptorProto.

func NewSourceCodeInfoBuilder

func NewSourceCodeInfoBuilder() *SourceCodeInfoBuilder

NewSourceCodeInfoBuilder creates a new SourceCodeInfo builder.

func (*SourceCodeInfoBuilder) AddLocation

func (b *SourceCodeInfoBuilder) AddLocation(path []int32, comment *CommentInfo)

AddLocation adds a location with comments to the SourceCodeInfo.

func (*SourceCodeInfoBuilder) Build

Build creates the SourceCodeInfo from all added locations.

type SyntaxMode

type SyntaxMode int

SyntaxMode represents the protobuf syntax mode.

const (
	// SyntaxProto3 represents proto3 syntax mode.
	SyntaxProto3 SyntaxMode = iota
	// SyntaxEditions represents editions syntax mode.
	SyntaxEditions
)

type UTF8Validation

type UTF8Validation int

UTF8Validation represents the UTF-8 validation feature.

const (
	// UTF8ValidationUnknown is the default unset value.
	UTF8ValidationUnknown UTF8Validation = iota
	// UTF8ValidationVerify verifies UTF-8 validity.
	UTF8ValidationVerify
	// UTF8ValidationNone skips UTF-8 validation.
	UTF8ValidationNone
)

type ValidationRule

type ValidationRule struct {
	Name  string
	Value string
}

ValidationRule represents a validation rule that can be converted to protobuf options.

func ParseValidationTag

func ParseValidationTag(tag string) []ValidationRule

ParseValidationTag parses a validation tag into rules.

type WellKnownType

type WellKnownType struct {
	TypeName   string
	ImportPath string
}

WellKnownType represents information about a well-known type

func IsWellKnownType

func IsWellKnownType(t reflect.Type) (WellKnownType, bool)

IsWellKnownType checks if a reflect.Type is a well-known type

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL