resource

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2025 License: MIT Imports: 33 Imported by: 2

Documentation

Overview

Package resource provides a set of types and functions for working with resources.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedNodeType = errors.New("unsupported AST node type for SQL generation")

ErrUnsupportedNodeType indicates an AST node type that the SQL generator cannot handle.

View Source
var ErrUnsupportedOperator = errors.New("unsupported operator for SQL generation")

ErrUnsupportedOperator indicates a condition operator that the SQL generator cannot handle.

Functions

func AddResources added in v0.0.3

func AddResources[Resource Resourcer](c *Collection, scope accesstypes.PermissionScope, rSet *Set[Resource]) error

AddResources adds all the resources and permissions from a ResourceSet to the collection. It is a no-op if collectResourcePermissions is false.

func CloneRequest added in v0.0.18

func CloneRequest(r *http.Request) (*http.Request, error)

CloneRequest creates a deep copy of an http.Request, including its body. This is useful when the request body needs to be read multiple times, as the original body can only be read once. The cloned request gets a new body that can be read and seeked independently.

func CommitTimestamp added in v0.1.10

func CommitTimestamp(_ context.Context, _ TxnBuffer) (any, error)

CommitTimestamp is a FieldDefaultFunc that returns the Spanner commit timestamp.

func CommitTimestampPtr added in v0.1.10

func CommitTimestampPtr(_ context.Context, _ TxnBuffer) (any, error)

CommitTimestampPtr is a FieldDefaultFunc that returns a pointer to the Spanner commit timestamp.

func DefaultFalse added in v0.1.16

func DefaultFalse(_ context.Context, _ TxnBuffer) (any, error)

DefaultFalse is a FieldDefaultFunc that returns false.

func DefaultTrue added in v0.1.16

func DefaultTrue(_ context.Context, _ TxnBuffer) (any, error)

DefaultTrue is a FieldDefaultFunc that returns true.

func Operations added in v0.0.3

func Operations(r *http.Request, pattern string, opts ...Option) iter.Seq2[*Operation, error]

Operations parses a batch JSON patch request and yields an iterator of individual Operation objects.

func PatchsetCompare added in v0.0.3

func PatchsetCompare(a, b PatchSetComparer) bool

PatchsetCompare compares two PatchSetComparer objects for equality. It checks patch type, data, fields, and primary keys.

func ProcessEvent added in v0.0.3

func ProcessEvent(processName string) string

ProcessEvent generates a standard event source string for a system process.

func UserEvent added in v0.0.3

func UserEvent(ctx context.Context) string

UserEvent generates a standard event source string for an action performed by a user. It extracts user information from the context.

func UserProcessEvent added in v0.0.3

func UserProcessEvent(ctx context.Context, processName string) string

UserProcessEvent generates a standard event source string for an action performed by a user within a specific system process.

Types

type Buffer added in v0.6.0

type Buffer interface {
	Buffer(ctx context.Context, txn TxnBuffer, eventSource ...string) error
}

Buffer is an interface for types that can buffer their Spanner mutations into a transaction via the Buffer method. This is used for batching operations.

type Collection

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

Collection stores information about resources, their permissions, and tags. It is used during code generation to create TypeScript definitions and Go handlers.

func NewCollection

func NewCollection() *Collection

NewCollection creates and initializes a new Collection.

func (*Collection) AddMethodResource added in v0.1.0

func (s *Collection) AddMethodResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, res accesstypes.Resource) error

AddMethodResource adds a resource associated with a method, allowing duplicate permission registrations. It is a no-op if collectResourcePermissions is false.

func (*Collection) AddResource

func (s *Collection) AddResource(scope accesstypes.PermissionScope, permission accesstypes.Permission, res accesstypes.Resource) error

AddResource adds a resource with a specific permission to the collection. It is a no-op if collectResourcePermissions is false.

func (*Collection) IsResourceImmutable

func (s *Collection) IsResourceImmutable(scope accesstypes.PermissionScope, res accesstypes.Resource) bool

IsResourceImmutable checks if a resource is marked as immutable within a given scope. It always returns false if collectResourcePermissions is false.

func (*Collection) List

List returns a map of permissions to the resources that have them. It returns an empty map if collectResourcePermissions is false.

func (*Collection) ResourceExists added in v0.1.7

func (s *Collection) ResourceExists(r accesstypes.Resource) bool

ResourceExists checks if a resource exists in the collection. It always returns false if collectResourcePermissions is false.

func (*Collection) Resources added in v0.0.10

func (s *Collection) Resources() []accesstypes.Resource

Resources returns a sorted list of all unique base resource names in the collection. It returns an empty slice if collectResourcePermissions is false.

func (*Collection) Scope

Scope returns the permission scope for a given resource. It returns an empty scope if the resource is not found or if collectResourcePermissions is false.

func (*Collection) TypescriptData added in v0.0.10

func (s *Collection) TypescriptData() *TypescriptData

TypescriptData returns a struct containing all the data needed for TypeScript code generation.

type Columns added in v0.0.3

type Columns string

Columns is a string representing a comma-separated list of database column names.

type CommitBuffer added in v0.0.21

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

CommitBuffer provides a way to buffer Spanner mutations and commit them in batches. This can improve performance by reducing the number of round trips to the database.

func NewCommitBuffer added in v0.0.21

func NewCommitBuffer(db TxnFuncRunner, eventSource string, autoCommitSize int) *CommitBuffer

NewCommitBuffer returns a CommitBuffer that flushes the buffer when it reaches autoCommitSize, committing the content in a single transaction. A autoCommitSize of 0 means that the buffer will never be flushed automatically. The buffer can be flushed manually by calling Commit(). Commit() must be called before discarding CommitBuffer to ensure all buffered mutations are committed.

func (*CommitBuffer) Buffer added in v0.0.21

func (cb *CommitBuffer) Buffer(ctx context.Context, ps ...Buffer) error

Buffer adds one or more SpannerBuffer items to the internal buffer. If the number of items in the buffer reaches the `autoCommitSize`, it will automatically trigger a commit.

func (*CommitBuffer) Commit added in v0.0.21

func (cb *CommitBuffer) Commit(ctx context.Context) error

Commit manually triggers a commit of all items currently in the buffer. If the buffer is empty, this is a no-op. After a successful commit, the buffer is cleared.

type Committer added in v0.6.0

type Committer interface {
	ReadWriteTransaction(ctx context.Context, f func(context.Context, *spanner.ReadWriteTransaction) error) (commitTimestamp time.Time, err error)
}

Committer is an interface that abstracts the Spanner client's transaction functionality. It is used by PatchSet.SpannerApply() to allow for mocking the Spanner client in tests. It is satisfied by *spanner.Client.

type Condition added in v0.1.12

type Condition struct {
	Field    string
	Operator string
	Value    any   // For eq, ne, gt, lt, gte, lte
	Values   []any // For in, notin
	IsNullOp bool  // For isnull, isnotnull
}

Condition represents a single condition (e.g., name:eq:John).

type ConditionNode added in v0.1.12

type ConditionNode struct {
	Condition Condition
}

ConditionNode represents a simple condition in the AST.

func (*ConditionNode) String added in v0.1.12

func (cn *ConditionNode) String() string

String returns a string representation of the ConditionNode.

type Config added in v0.0.3

type Config struct {
	DBType              DBType
	ChangeTrackingTable string
	TrackChanges        bool
}

Config holds database-specific configuration for a resource.

func (Config) SetChangeTrackingTable added in v0.0.3

func (c Config) SetChangeTrackingTable(changeTrackingTable string) Config

SetChangeTrackingTable returns a new Config with the change tracking table name set.

func (Config) SetDBType added in v0.0.3

func (c Config) SetDBType(dbType DBType) Config

SetDBType returns a new Config with the DBType set.

func (Config) SetTrackChanges added in v0.0.3

func (c Config) SetTrackChanges(trackChanges bool) Config

SetTrackChanges returns a new Config with the change tracking flag set.

type Configurer added in v0.0.3

type Configurer interface {
	Config() Config
}

Configurer is an interface for types that can provide a resource configuration.

type DBType added in v0.0.3

type DBType string

DBType represents the type of database, such as Spanner or PostgreSQL.

const (
	// SpannerDBType represents the Google Cloud Spanner database.
	SpannerDBType DBType = "spanner"
	// PostgresDBType represents the PostgreSQL database.
	PostgresDBType DBType = "postgres"
)

type DataChangeEvent added in v0.0.3

type DataChangeEvent struct {
	TableName   accesstypes.Resource `spanner:"TableName"`
	RowID       string               `spanner:"RowId"`
	EventTime   time.Time            `spanner:"EventTime"`
	EventSource string               `spanner:"EventSource"`
	ChangeSet   spanner.NullJSON     `spanner:"ChangeSet"`
}

DataChangeEvent represents a record of a change made to a database table.

type Decoder added in v0.0.3

type Decoder[Resource Resourcer, Request any] struct {
	// contains filtered or unexported fields
}

Decoder is a struct that can be used for decoding http requests and validating those requests

func NewDecoder added in v0.0.3

func NewDecoder[Resource Resourcer, Request any](rSet *Set[Resource]) (*Decoder[Resource, Request], error)

NewDecoder creates a new Decoder for a given Resource and Request type.

func (*Decoder[Resource, Request]) Decode added in v0.0.3

func (d *Decoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions, requiredPermission accesstypes.Permission) (*PatchSet[Resource], error)

Decode decodes an http.Request into a PatchSet and enables user permission enforcement.

func (*Decoder[Resource, Request]) DecodeOperation added in v0.0.17

func (d *Decoder[Resource, Request]) DecodeOperation(oper *Operation, userPermissions UserPermissions) (*PatchSet[Resource], error)

DecodeOperation decodes an Operation into a PatchSet and enables user permission enforcement.

func (*Decoder[Resource, Request]) DecodeOperationWithoutPermissions added in v0.0.17

func (d *Decoder[Resource, Request]) DecodeOperationWithoutPermissions(oper *Operation) (*PatchSet[Resource], error)

DecodeOperationWithoutPermissions decodes an Operation into a PatchSet without enforcing user permissions.

func (*Decoder[Resource, Request]) DecodeWithoutPermissions added in v0.0.17

func (d *Decoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*PatchSet[Resource], error)

DecodeWithoutPermissions decodes an http.Request into a PatchSet without enforcing any user permissions.

func (*Decoder[Resource, Request]) WithValidator added in v0.0.3

func (d *Decoder[Resource, Request]) WithValidator(v ValidatorFunc) *Decoder[Resource, Request]

WithValidator sets the validator function for the Decoder.

type DefaultsFunc added in v0.3.1

type DefaultsFunc func(ctx context.Context, txn TxnBuffer) error

DefaultsFunc is the signature for a function that applies default values to a PatchSet.

type DiffElem added in v0.0.3

type DiffElem struct {
	Old any
	New any
}

DiffElem represents the old and new values of a field that has been changed.

type DomainFromCtx added in v0.0.3

type DomainFromCtx func(context.Context) accesstypes.Domain

DomainFromCtx is a function that extracts a domain from a context.

type DomainFromReq added in v0.0.3

type DomainFromReq func(*http.Request) accesstypes.Domain

DomainFromReq is a function that extracts a domain from an http.Request.

type ExpressionNode added in v0.1.12

type ExpressionNode interface {
	// String returns a string representation of the node (for debugging/testing).
	String() string
}

ExpressionNode represents a node in the filter AST.

type FieldDefaultFunc added in v0.1.5

type FieldDefaultFunc func(ctx context.Context, txn TxnBuffer) (any, error)

FieldDefaultFunc is the signature for a function that applies a default value to one field of a PatchSet.

func DefaultString added in v0.1.18

func DefaultString(v string) FieldDefaultFunc

DefaultString returns a FieldDefaultFunc that provides the given string value.

type FilterFieldInfo added in v0.5.0

type FilterFieldInfo struct {
	DbColumnName string
	Kind         reflect.Kind
	FieldType    reflect.Type
	Indexed      bool
	PII          bool
}

FilterFieldInfo holds metadata about a field that can be used in a filter.

type FilterLexer added in v0.5.0

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

FilterLexer parses the filter producing tokens

func NewFilterLexer added in v0.5.0

func NewFilterLexer(input string) *FilterLexer

NewFilterLexer creates a new lexer for the given input filter string.

func (*FilterLexer) NextToken added in v0.5.0

func (l *FilterLexer) NextToken() (Token, error)

NextToken returns the next token from the input string.

type FilterParser added in v0.5.0

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

FilterParser builds an AST from tokens.

func NewFilterParser added in v0.5.0

func NewFilterParser(lexer *FilterLexer, jsonToFieldInfo map[jsonFieldName]FilterFieldInfo) (*FilterParser, error)

NewFilterParser creates a new parser with the given lexer and field information map.

func (*FilterParser) Parse added in v0.5.0

func (p *FilterParser) Parse() (ExpressionNode, error)

Parse is the main entry point for parsing the filter string.

type GroupNode added in v0.1.12

type GroupNode struct {
	Expression ExpressionNode
}

GroupNode represents a parenthesized group of expressions in the AST.

func (*GroupNode) String added in v0.1.12

func (gn *GroupNode) String() string

String returns a string representation of the GroupNode.

type Ident added in v0.0.19

type Ident[T comparable] struct {
	// contains filtered or unexported fields
}

Ident represents a database column identifier in a query, typed to ensure compile-time correctness of comparisons.

func NewIdent added in v0.0.19

func NewIdent[T comparable](column string, px PartialQueryClause, indexed bool) Ident[T]

NewIdent creates a new identifier for a column.

func (Ident[T]) Equal added in v0.0.19

func (i Ident[T]) Equal(v ...T) QueryClause

Equal creates an equality (`=`) or `IN` condition.

func (Ident[T]) GreaterThan added in v0.0.19

func (i Ident[T]) GreaterThan(v T) QueryClause

GreaterThan creates a `>` condition.

func (Ident[T]) GreaterThanEq added in v0.0.19

func (i Ident[T]) GreaterThanEq(v T) QueryClause

GreaterThanEq creates a `>=` condition.

func (Ident[T]) IsNotNull added in v0.1.12

func (i Ident[T]) IsNotNull() QueryClause

IsNotNull creates an `IS NOT NULL` condition.

func (Ident[T]) IsNull added in v0.1.12

func (i Ident[T]) IsNull() QueryClause

IsNull creates an `IS NULL` condition.

func (Ident[T]) LessThan added in v0.0.19

func (i Ident[T]) LessThan(v T) QueryClause

LessThan creates a `<` condition.

func (Ident[T]) LessThanEq added in v0.0.19

func (i Ident[T]) LessThanEq(v T) QueryClause

LessThanEq creates a `<=` condition.

func (Ident[T]) NotEqual added in v0.0.19

func (i Ident[T]) NotEqual(v ...T) QueryClause

NotEqual creates a not-equal (`<>`) or `NOT IN` condition.

type KeyPart

type KeyPart struct {
	Key   accesstypes.Field
	Value any
}

KeyPart represents a single component of a primary key, consisting of a field name and its value.

type KeySet

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

KeySet is an object that represents a single or composite primary key and its value.

func (KeySet) Add

func (p KeySet) Add(key accesstypes.Field, value any) KeySet

Add adds an additional column to the primary key creating a composite primary key

  • PrimaryKey is immutable.
  • Add returns a new PrimaryKey that should be used for all subsequent operations.

func (KeySet) KeyMap

func (p KeySet) KeyMap() map[accesstypes.Field]any

KeyMap returns a map representation of the key set, with field names as keys and their values as values.

func (KeySet) KeySet

func (p KeySet) KeySet() spanner.KeySet

KeySet converts the resource KeySet into a `spanner.KeySet`, which can be used in Spanner read or delete operations.

func (KeySet) Len

func (p KeySet) Len() int

Len returns the number of parts in the key set (for composite keys, this will be greater than 1).

func (KeySet) Parts

func (p KeySet) Parts() []KeyPart

Parts returns the slice of KeyPart components that make up the key set.

func (KeySet) RowID

func (p KeySet) RowID() string

RowID generates a string representation of the key set, typically for use in logging or as a unique identifier.

type Link struct {
	ID       ccc.UUID `json:"id"`
	Resource string   `json:"resource"`
	Text     string   `json:"text"`
}

Link represents a hyperlink to another resource, containing its ID, type, and display text.

func (*Link) DecodeSpanner added in v0.0.11

func (l *Link) DecodeSpanner(val any) error

DecodeSpanner implements the spanner.Decoder interface, unmarshaling a JSON string from Spanner into the Link struct.

func (Link) EncodeSpanner added in v0.0.11

func (l Link) EncodeSpanner() (any, error)

EncodeSpanner implements the spanner.Encoder interface, marshaling the Link to its JSON representation for storage.

func (Link) IsNull added in v0.0.11

func (l Link) IsNull() bool

IsNull checks if the Link is considered null (i.e., its ID is nil).

func (Link) MarshalJSON added in v0.0.11

func (l Link) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Link) UnmarshalJSON added in v0.0.11

func (l *Link) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type LogicalOpNode added in v0.1.12

type LogicalOpNode struct {
	Left     ExpressionNode
	Operator LogicalOperator
	Right    ExpressionNode
}

LogicalOpNode represents a logical operation (AND/OR) in the AST.

func (*LogicalOpNode) String added in v0.1.12

func (ln *LogicalOpNode) String() string

String returns a string representation of the LogicalOpNode.

type LogicalOperator added in v0.1.12

type LogicalOperator string

LogicalOperator defines the type of logical operator (AND, OR).

const (
	// OperatorAnd represents a logical AND.
	OperatorAnd LogicalOperator = "AND"
	// OperatorOr represents a logical OR.
	OperatorOr LogicalOperator = "OR"
)

type Metadata added in v0.5.0

type Metadata[Resource Resourcer] struct {
	// contains filtered or unexported fields
}

Metadata contains cached metadata about a resource, such as its database schema mapping and configuration.

func NewMetadata added in v0.5.0

func NewMetadata[Resource Resourcer]() *Metadata[Resource]

NewMetadata creates or retrieves cached metadata for a resource.

func (*Metadata[Resource]) Fields added in v0.5.0

func (r *Metadata[Resource]) Fields() []accesstypes.Field

Fields returns a slice of all field names for the resource.

func (*Metadata[Resource]) Len added in v0.5.0

func (r *Metadata[Resource]) Len() int

Len returns the number of fields in the resource.

type NullLink struct {
	Link  Link
	Valid bool
}

NullLink is a nullable version of Link, supporting JSON and Spanner encoding/decoding of null values.

func (*NullLink) DecodeSpanner added in v0.0.11

func (nl *NullLink) DecodeSpanner(val any) error

DecodeSpanner implements the spanner.Decoder interface for NullLink.

func (NullLink) EncodeSpanner added in v0.0.11

func (nl NullLink) EncodeSpanner() (any, error)

EncodeSpanner implements the spanner.Encoder interface for NullLink.

func (NullLink) MarshalJSON added in v0.0.11

func (nl NullLink) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for NullLink.

func (*NullLink) UnmarshalJSON added in v0.0.11

func (nl *NullLink) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for NullLink.

type Operation added in v0.0.3

type Operation struct {
	Type OperationType
	Req  *http.Request
	// contains filtered or unexported fields
}

Operation represents a single operation within a batch request, containing its type and a corresponding http.Request.

func (*Operation) ReqWithPattern added in v0.2.3

func (o *Operation) ReqWithPattern(pattern string, opts ...Option) (*http.Request, error)

ReqWithPattern creates a new http.Request from the operation, applying a new URL pattern to its context. This is useful when a batch operation's path contains more segments than the initial prefix pattern.

type OperationType added in v0.0.3

type OperationType string

OperationType defines the type of a patch operation (add, patch, remove).

const (
	// OperationCreate corresponds to an "add" operation.
	OperationCreate OperationType = "add"
	// OperationUpdate corresponds to a "patch" operation.
	OperationUpdate OperationType = "patch"
	// OperationDelete corresponds to a "remove" operation.
	OperationDelete OperationType = "remove"
)

type Option added in v0.0.12

type Option func(opt options) options

Option is a function that configures the behavior of the Operations parser.

func MatchPrefix added in v0.2.3

func MatchPrefix() Option

MatchPrefix is an option that allows matching only the prefix of an operation's path against the provided pattern.

func RequireCreatePath added in v0.0.12

func RequireCreatePath() Option

RequireCreatePath is an option that mandates a path for "add" operations.

type PartialQueryClause added in v0.0.19

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

PartialQueryClause represents an incomplete query clause, typically the left-hand side of a logical operation.

func NewPartialQueryClause added in v0.0.19

func NewPartialQueryClause() PartialQueryClause

NewPartialQueryClause creates an empty PartialQueryClause.

func (PartialQueryClause) Group added in v0.0.19

Group wraps a QueryClause in parentheses.

type PatchSet

type PatchSet[Resource Resourcer] struct {
	// contains filtered or unexported fields
}

PatchSet represents a set of changes to be applied to a resource.

func NewPatchSet

func NewPatchSet[Resource Resourcer](rMeta *Metadata[Resource]) *PatchSet[Resource]

NewPatchSet creates a new, empty PatchSet for a given resource metadata.

func (*PatchSet[Resource]) Apply added in v0.6.0

func (p *PatchSet[Resource]) Apply(ctx context.Context, committer Committer, eventSource ...string) error

Apply applies the patch within a new read-write transaction.

func (*PatchSet[Resource]) Buffer added in v0.6.0

func (p *PatchSet[Resource]) Buffer(ctx context.Context, txn TxnBuffer, eventSource ...string) error

Buffer buffers the patch's mutations into an existing transaction buffer.

func (*PatchSet[Resource]) Data

func (p *PatchSet[Resource]) Data() map[accesstypes.Field]any

Data returns the underlying map of field-value pairs.

func (*PatchSet[Resource]) Diff added in v0.0.3

func (p *PatchSet[Resource]) Diff(old any) (map[accesstypes.Field]DiffElem, error)

Diff returns a map of fields that have changed between old and patchSet.

func (*PatchSet[Resource]) EnableUserPermissionEnforcement added in v0.0.17

func (p *PatchSet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, requiredPermission accesstypes.Permission) *PatchSet[Resource]

EnableUserPermissionEnforcement enables the checking of user permissions for the PatchSet.

func (*PatchSet[Resource]) Fields

func (p *PatchSet[Resource]) Fields() []accesstypes.Field

Fields returns a slice of all fields that have been set in the PatchSet.

func (*PatchSet[Resource]) Get

func (p *PatchSet[Resource]) Get(field accesstypes.Field) any

Get retrieves the value of a field from the PatchSet.

func (*PatchSet[Resource]) HasKey

func (p *PatchSet[Resource]) HasKey() bool

HasKey checks if any primary key has been set.

func (*PatchSet[Resource]) IsSet added in v0.0.3

func (p *PatchSet[Resource]) IsSet(field accesstypes.Field) bool

IsSet checks if a field has been set in the PatchSet.

func (*PatchSet[Resource]) Key

func (p *PatchSet[Resource]) Key(field accesstypes.Field) any

Key retrieves the value of a primary key field.

func (*PatchSet[Resource]) Len

func (p *PatchSet[Resource]) Len() int

Len returns the number of fields in the PatchSet.

func (*PatchSet[Resource]) PatchType added in v0.0.3

func (p *PatchSet[Resource]) PatchType() PatchType

PatchType returns the type of the patch.

func (*PatchSet[Resource]) PrimaryKey added in v0.0.3

func (p *PatchSet[Resource]) PrimaryKey() KeySet

PrimaryKey returns the KeySet containing the primary key(s) for the resource.

func (*PatchSet[Resource]) RegisterDefaultCreateFunc added in v0.1.10

func (p *PatchSet[Resource]) RegisterDefaultCreateFunc(field accesstypes.Field, fn FieldDefaultFunc)

RegisterDefaultCreateFunc registers a function to set a default value for a field during a create operation.

func (*PatchSet[Resource]) RegisterDefaultUpdateFunc added in v0.1.10

func (p *PatchSet[Resource]) RegisterDefaultUpdateFunc(field accesstypes.Field, fn FieldDefaultFunc)

RegisterDefaultUpdateFunc registers a function to set a default value for a field during an update operation.

func (*PatchSet[Resource]) RegisterDefaultsCreateFunc added in v0.3.1

func (p *PatchSet[Resource]) RegisterDefaultsCreateFunc(fn DefaultsFunc)

RegisterDefaultsCreateFunc registers a function that will be called on all Create Patches just before the patch is buffered to set necessary default values

func (*PatchSet[Resource]) RegisterDefaultsUpdateFunc added in v0.3.1

func (p *PatchSet[Resource]) RegisterDefaultsUpdateFunc(fn DefaultsFunc)

RegisterDefaultsUpdateFunc registers a function that will be called on all Update Patches just before the patch is buffered to set necessary default values

func (*PatchSet[Resource]) RegisterValidateCreateFunc added in v0.3.1

func (p *PatchSet[Resource]) RegisterValidateCreateFunc(fn ValidateFunc)

RegisterValidateCreateFunc registers a function that will be called on all Create Patches just before the patch is buffered to validate the patch

func (*PatchSet[Resource]) RegisterValidateUpdateFunc added in v0.3.1

func (p *PatchSet[Resource]) RegisterValidateUpdateFunc(fn ValidateFunc)

RegisterValidateUpdateFunc registers a function that will be called on all Update Patches just before the patch is buffered to validate the patch

func (*PatchSet[Resource]) Resolve added in v0.0.3

func (p *PatchSet[Resource]) Resolve() (map[string]any, error)

Resolve returns a map with the keys set to the database struct tags found on databaseType, and the values set to the values in patchSet.

func (*PatchSet[Resource]) Resource added in v0.0.3

func (p *PatchSet[Resource]) Resource() accesstypes.Resource

Resource returns the name of the resource this PatchSet applies to.

func (*PatchSet[Resource]) Set

func (p *PatchSet[Resource]) Set(field accesstypes.Field, value any) *PatchSet[Resource]

Set adds or updates a field's value in the PatchSet.

func (*PatchSet[Resource]) SetKey

func (p *PatchSet[Resource]) SetKey(field accesstypes.Field, value any) *PatchSet[Resource]

SetKey sets a primary key field and value for the PatchSet.

func (*PatchSet[Resource]) SetPatchType added in v0.0.3

func (p *PatchSet[Resource]) SetPatchType(t PatchType) *PatchSet[Resource]

SetPatchType sets the type of the patch (Create, Update, or Delete).

type PatchSetComparer added in v0.0.3

type PatchSetComparer interface {
	Data() map[accesstypes.Field]any
	Fields() []accesstypes.Field
	PatchType() PatchType
	PrimaryKey() KeySet
}

PatchSetComparer is an interface for comparing two PatchSet-like objects.

type PatchType added in v0.0.3

type PatchType string

PatchType defines the type of operation for a PatchSet.

const (
	// CreatePatchType indicates an insert operation.
	CreatePatchType PatchType = "CreatePatchType"
	// UpdatePatchType indicates an update operation.
	UpdatePatchType PatchType = "UpdatePatchType"
	// CreateOrUpdatePatchType indicates an insert or update operation.
	CreateOrUpdatePatchType PatchType = "CreateOrUpdatePatchType"
	// DeletePatchType indicates a delete operation.
	DeletePatchType PatchType = "DeletePatchType"
)

type PostgreSQLGenerator added in v0.1.12

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

PostgreSQLGenerator is a SQL generator for PostgreSQL.

func NewPostgreSQLGenerator added in v0.1.12

func NewPostgreSQLGenerator() *PostgreSQLGenerator

NewPostgreSQLGenerator creates a new PostgreSQLGenerator.

func (*PostgreSQLGenerator) GenerateSQL added in v0.1.12

func (g *PostgreSQLGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params []any, err error)

GenerateSQL generates SQL for the given node.

type PostgresStatement added in v0.1.12

type PostgresStatement struct {
	SQL    string
	Params []any
	// contains filtered or unexported fields
}

PostgresStatement holds a SQL string and its parameters for a PostgreSQL query.

type QueryClause added in v0.0.19

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

QueryClause represents a complete, valid query expression that can be part of a WHERE clause.

func (QueryClause) And added in v0.0.19

And starts a logical AND operation, returning a PartialQueryClause to which the right-hand side can be appended.

func (QueryClause) Or added in v0.0.19

Or starts a logical OR operation, returning a PartialQueryClause to which the right-hand side can be appended.

func (QueryClause) Validate added in v0.1.15

func (qc QueryClause) Validate() error

Validate checks if the query clause has at least one indexed field.

type QueryDecoder added in v0.0.3

type QueryDecoder[Resource Resourcer, Request any] struct {
	// contains filtered or unexported fields
}

QueryDecoder is a struct that returns columns that a given user has access to view

func NewQueryDecoder added in v0.0.3

func NewQueryDecoder[Resource Resourcer, Request any](resSet *Set[Resource]) (*QueryDecoder[Resource, Request], error)

NewQueryDecoder creates a new QueryDecoder for a given Resource and Request type.

func (*QueryDecoder[Resource, Request]) Decode added in v0.0.3

func (d *QueryDecoder[Resource, Request]) Decode(request *http.Request, userPermissions UserPermissions) (*QuerySet[Resource], error)

Decode decodes an http.Request into a QuerySet and enables user permission enforcement.

func (*QueryDecoder[Resource, Request]) DecodeWithoutPermissions added in v0.0.17

func (d *QueryDecoder[Resource, Request]) DecodeWithoutPermissions(request *http.Request) (*QuerySet[Resource], error)

DecodeWithoutPermissions decodes an http.Request into a QuerySet without enforcing user permissions.

type QueryParam added in v0.1.12

type QueryParam struct {
	Name  string
	Value any
}

QueryParam holds a single query parameter's name and value.

type QuerySet

type QuerySet[Resource Resourcer] struct {
	// contains filtered or unexported fields
}

QuerySet represents a query for a resource, including fields, keys, filters, and permissions.

func NewQuerySet

func NewQuerySet[Resource Resourcer](rMeta *Metadata[Resource]) *QuerySet[Resource]

NewQuerySet creates a new, empty QuerySet for a given resource metadata.

func (*QuerySet[Resource]) AddField

func (q *QuerySet[Resource]) AddField(field accesstypes.Field) *QuerySet[Resource]

AddField adds a field to be returned by the query.

func (*QuerySet[Resource]) Columns added in v0.0.3

func (q *QuerySet[Resource]) Columns() (Columns, error)

Columns returns the database struct tags for the fields in databaseType that the user has access to view.

func (*QuerySet[Resource]) EnableUserPermissionEnforcement added in v0.0.17

func (q *QuerySet[Resource]) EnableUserPermissionEnforcement(rSet *Set[Resource], userPermissions UserPermissions, requiredPermission accesstypes.Permission) *QuerySet[Resource]

EnableUserPermissionEnforcement enables the checking of user permissions for the QuerySet.

func (*QuerySet[Resource]) Fields

func (q *QuerySet[Resource]) Fields() []accesstypes.Field

Fields returns the list of fields to be returned by the query.

func (*QuerySet[Resource]) Key added in v0.0.3

func (q *QuerySet[Resource]) Key(field accesstypes.Field) any

Key retrieves the value of a primary key field.

func (*QuerySet[Resource]) KeySet added in v0.0.3

func (q *QuerySet[Resource]) KeySet() KeySet

KeySet returns the KeySet containing the primary key(s) for the resource.

func (*QuerySet[Resource]) Len

func (q *QuerySet[Resource]) Len() int

Len returns the number of fields to be returned by the query.

func (*QuerySet[Resource]) PostgresStmt added in v0.0.3

func (q *QuerySet[Resource]) PostgresStmt() (*PostgresStatement, error)

PostgresStmt builds a PostgreSQL SQL statement from the QuerySet.

func (*QuerySet[Resource]) RequiredPermission added in v0.0.17

func (q *QuerySet[Resource]) RequiredPermission() accesstypes.Permission

RequiredPermission returns the permission required to execute the query.

func (*QuerySet[Resource]) Resource added in v0.0.3

func (q *QuerySet[Resource]) Resource() accesstypes.Resource

Resource returns the name of the resource this QuerySet applies to.

func (*QuerySet[Resource]) ReturnAccessableFields added in v0.0.17

func (q *QuerySet[Resource]) ReturnAccessableFields(b bool) *QuerySet[Resource]

ReturnAccessableFields configures the QuerySet to automatically include all fields the user has access to if no specific fields are requested.

func (*QuerySet[Resource]) SetFilterAst added in v0.1.13

func (q *QuerySet[Resource]) SetFilterAst(ast ExpressionNode)

SetFilterAst sets the filter condition for the query using a raw expression tree.

func (*QuerySet[Resource]) SetKey added in v0.0.3

func (q *QuerySet[Resource]) SetKey(field accesstypes.Field, value any)

SetKey sets a primary key field and value for the query's WHERE clause.

func (*QuerySet[Resource]) SetLimit added in v0.2.7

func (q *QuerySet[Resource]) SetLimit(limit *uint64)

SetLimit sets the maximum number of results to return.

func (*QuerySet[Resource]) SetOffset added in v0.4.4

func (q *QuerySet[Resource]) SetOffset(offset *uint64)

SetOffset sets the starting point for returning results.

func (*QuerySet[Resource]) SetSearchParam added in v0.0.13

func (q *QuerySet[Resource]) SetSearchParam(search *Search)

SetSearchParam sets the search parameters for the query.

func (*QuerySet[Resource]) SetSortFields added in v0.1.13

func (q *QuerySet[Resource]) SetSortFields(sortFields []SortField)

SetSortFields sets the sorting order for the query results.

func (*QuerySet[Resource]) SetWhereClause added in v0.0.19

func (q *QuerySet[Resource]) SetWhereClause(qc QueryClause)

SetWhereClause sets the filter condition for the query using a QueryClause.

func (*QuerySet[Resource]) SpannerList added in v0.0.3

func (q *QuerySet[Resource]) SpannerList(ctx context.Context, db spxapi.Querier) iter.Seq2[*Resource, error]

SpannerList executes the query and returns an iterator for the results.

func (*QuerySet[Resource]) SpannerRead added in v0.0.3

func (q *QuerySet[Resource]) SpannerRead(ctx context.Context, db spxapi.Querier) (*Resource, error)

SpannerRead executes the query and returns a single result.

func (*QuerySet[Resource]) SpannerStmt added in v0.0.3

func (q *QuerySet[Resource]) SpannerStmt() (*SpannerStatement, error)

SpannerStmt builds a Spanner SQL statement from the QuerySet.

type RPCDecoder added in v0.1.0

type RPCDecoder[Request any] struct {
	// contains filtered or unexported fields
}

RPCDecoder decodes an HTTP request for an RPC-style endpoint, validates the request body, and enforces permissions for the RPC method.

func NewRPCDecoder added in v0.1.0

func NewRPCDecoder[Request any](userPermissions func(*http.Request) UserPermissions, methodName accesstypes.Resource, perm accesstypes.Permission) (*RPCDecoder[Request], error)

NewRPCDecoder creates a new RPCDecoder for a given request type, method name, and required permission.

func (*RPCDecoder[Request]) Decode added in v0.1.0

func (s *RPCDecoder[Request]) Decode(request *http.Request) (*Request, error)

Decode decodes the HTTP request body into the Request struct and checks user permissions.

func (*RPCDecoder[Request]) WithValidator added in v0.1.0

func (s *RPCDecoder[Request]) WithValidator(v ValidatorFunc) *RPCDecoder[Request]

WithValidator sets a validator function on the decoder.

type RequestFieldMapper added in v0.0.17

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

RequestFieldMapper provides a mapping between JSON field names (from struct tags) and their corresponding Go struct field names.

func NewRequestFieldMapper added in v0.0.17

func NewRequestFieldMapper(v any) (*RequestFieldMapper, error)

NewRequestFieldMapper creates a new RequestFieldMapper by inspecting the struct tags of the provided value.

func (*RequestFieldMapper) Fields added in v0.0.17

func (f *RequestFieldMapper) Fields() []accesstypes.Field

Fields returns a slice of all Go struct field names.

func (*RequestFieldMapper) Len added in v0.0.17

func (f *RequestFieldMapper) Len() int

Len returns the number of mapped fields.

func (*RequestFieldMapper) StructFieldName added in v0.0.17

func (f *RequestFieldMapper) StructFieldName(jsonTag string) (accesstypes.Field, bool)

StructFieldName retrieves the Go struct field name for a given JSON tag.

type Resourcer

type Resourcer interface {
	Resource() accesstypes.Resource
	DefaultConfig() Config
}

Resourcer is an interface that all resource structs must implement.

type RunnerFunc added in v0.0.21

type RunnerFunc func(ctx context.Context, txn TxnBuffer) error

RunnerFunc is a function that converts a TxnFuncRunner into a TxnRunner

func (RunnerFunc) Execute added in v0.0.21

func (fn RunnerFunc) Execute(ctx context.Context, txn TxnBuffer) error

Execute runs the function.

type SQLDialect added in v0.1.12

type SQLDialect int

SQLDialect defines the type of SQL dialect to generate.

const (
	// PostgreSQL dialect.
	PostgreSQL SQLDialect = iota
	// Spanner dialect.
	Spanner
)
type Search struct {
	// contains filtered or unexported fields
}

Search represents a search query with a specific type and values.

func NewSearch added in v0.1.13

func NewSearch(typ SearchType, values map[SearchKey]string) *Search

NewSearch creates a new Search object.

type SearchKey added in v0.0.13

type SearchKey string

SearchKey is the key used in a search query, typically corresponding to a field name.

func (SearchKey) String added in v0.1.13

func (f SearchKey) String() string

type SearchKeys added in v0.0.13

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

SearchKeys holds the mapping of search keys to their corresponding search types, parsed from struct tags.

func NewSearchKeys added in v0.0.13

func NewSearchKeys[Req any](res Resourcer) *SearchKeys

NewSearchKeys creates a new SearchKeys instance by inspecting the struct tags of a request type.

type SearchType added in v0.0.13

type SearchType string

SearchType defines the type of search to be performed (e.g., substring, full-text).

const (
	// SubString search type.
	SubString SearchType = "substring"
	// FullText search type.
	FullText SearchType = "fulltext"
	// Ngram search type.
	Ngram SearchType = "ngram"
)

type Set added in v0.5.0

type Set[Resource Resourcer] struct {
	// contains filtered or unexported fields
}

Set holds metadata about a resource, including its permissions and field-to-tag mappings.

func NewSet added in v0.5.0

func NewSet[Resource Resourcer, Request any](permissions ...accesstypes.Permission) (*Set[Resource], error)

NewSet creates a new Set for a given Resource and Request type, parsing permissions from struct tags.

func (*Set[Resource]) BaseResource added in v0.5.0

func (r *Set[Resource]) BaseResource() accesstypes.Resource

BaseResource returns the base name of the resource (without any tags).

func (*Set[Resource]) ImmutableFields added in v0.5.0

func (r *Set[Resource]) ImmutableFields() map[accesstypes.Tag]struct{}

ImmutableFields returns a map of tags for fields that are marked as immutable.

func (*Set[Resource]) PermissionRequired added in v0.5.0

func (r *Set[Resource]) PermissionRequired(fieldName accesstypes.Field, perm accesstypes.Permission) bool

PermissionRequired checks if a specific permission is required for a given field.

func (*Set[Resource]) Permissions added in v0.5.0

func (r *Set[Resource]) Permissions() []accesstypes.Permission

Permissions returns all permissions associated with the resource set.

func (*Set[Resource]) Resource added in v0.5.0

func (r *Set[Resource]) Resource(fieldName accesstypes.Field) accesstypes.Resource

Resource returns the full resource name for a field, including its tag (e.g., "myresource.myfield").

func (*Set[Resource]) ResourceMetadata added in v0.5.0

func (r *Set[Resource]) ResourceMetadata() *Metadata[Resource]

ResourceMetadata returns the metadata for the resource.

func (*Set[Resource]) TagPermissions added in v0.5.0

func (r *Set[Resource]) TagPermissions() accesstypes.TagPermissions

TagPermissions returns the mapping of tags to their required permissions.

type SortDirection added in v0.1.13

type SortDirection string

SortDirection defines the sort direction for a field.

const (
	// SortAscending specifies sorting in ascending order.
	SortAscending SortDirection = "asc"
	// SortDescending specifies sorting in descending order.
	SortDescending SortDirection = "desc"
)

type SortField added in v0.1.13

type SortField struct {
	Field     string
	Direction SortDirection
}

SortField represents a field to sort by, including the field name and sort direction.

type SpannerGenerator added in v0.1.12

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

SpannerGenerator is a SQL generator for Spanner.

func NewSpannerGenerator added in v0.1.12

func NewSpannerGenerator() *SpannerGenerator

NewSpannerGenerator creates a new SpannerGenerator.

func (*SpannerGenerator) GenerateSQL added in v0.1.12

func (g *SpannerGenerator) GenerateSQL(node ExpressionNode) (sqlStr string, params map[string]any, err error)

GenerateSQL generates SQL for the given node and returns named parameters.

type SpannerStatement added in v0.1.12

type SpannerStatement struct {
	spanner.Statement
	// contains filtered or unexported fields
}

SpannerStatement wraps a `spanner.Statement` and includes a resolved WHERE clause for debugging.

type Statement added in v0.0.13

type Statement struct {
	SQL              string
	SpannerParams    map[string]any
	PostgreSQLParams []any
}

Statement is a generic container for a SQL statement and its parameters, supporting both Spanner and PostgreSQL.

type StructDecoder added in v0.0.3

type StructDecoder[Request any] struct {
	// contains filtered or unexported fields
}

StructDecoder is a struct that can be used for decoding http requests and validating those requests

func NewStructDecoder added in v0.0.3

func NewStructDecoder[Request any]() (*StructDecoder[Request], error)

NewStructDecoder creates a new StructDecoder for a given request type.

func (*StructDecoder[Request]) Decode added in v0.0.3

func (s *StructDecoder[Request]) Decode(request *http.Request) (*Request, error)

Decode decodes the HTTP request body into the target Request struct.

func (*StructDecoder[Request]) WithValidator added in v0.0.3

func (s *StructDecoder[Request]) WithValidator(v ValidatorFunc) *StructDecoder[Request]

WithValidator sets a validator function on the decoder.

type Token added in v0.1.12

type Token struct {
	Type  TokenType
	Value string
}

Token represents a single token.

type TokenType added in v0.1.12

type TokenType int

TokenType defines the types of tokens in the filter string.

const (
	// TokenEOF represents the end of the input string.
	TokenEOF TokenType = iota
	// TokenLParen represents '('
	TokenLParen
	// TokenRParen represents ')'
	TokenRParen
	// TokenComma represents ','
	TokenComma
	// TokenPipe represents '|'
	TokenPipe
	// TokenCondition represents 'field:operator:value' or 'field:operator:(value1,value2,...)' or 'field:operator'
	TokenCondition
)

func (TokenType) String added in v0.1.12

func (i TokenType) String() string

type TxnBuffer added in v0.0.21

type TxnBuffer interface {
	BufferWrite(ms []*spanner.Mutation) error
	spxapi.Querier
}

TxnBuffer is an interface that abstracts a Spanner read-write transaction, allowing mutations to be buffered and queries to be executed within the transaction. It is satisfied by *spanner.ReadWriteTransaction.

type TxnFuncRunner added in v0.0.21

type TxnFuncRunner interface {
	ExecuteFunc(ctx context.Context, runnerFn func(ctx context.Context, txn TxnBuffer) error) error
}

TxnFuncRunner provides a way to execute a function within a read-write transaction. This is useful for batching operations that need to be committed together.

type TxnRunner added in v0.0.21

type TxnRunner interface {
	Execute(ctx context.Context, txn TxnBuffer) error
}

TxnRunner will have its Execute() method called inside the *spanner.ReadWriteTransaction provided by TxnBuffer

type TypescriptData added in v0.0.10

type TypescriptData struct {
	Permissions           []accesstypes.Permission
	ResourcePermissions   []accesstypes.Permission
	Resources             []accesstypes.Resource
	ResourceTags          map[accesstypes.Resource][]accesstypes.Tag
	ResourcePermissionMap permissionMap
	Domains               []accesstypes.PermissionScope
}

TypescriptData holds all the collected resource and permission information needed for TypeScript code generation.

type UserFromCtx added in v0.0.3

type UserFromCtx func(context.Context) accesstypes.User

UserFromCtx is a function that extracts a user from a context.

type UserFromReq added in v0.0.3

type UserFromReq func(*http.Request) accesstypes.User

UserFromReq is a function that extracts a user from an http.Request.

type UserPermissions added in v0.0.17

type UserPermissions interface {
	Check(ctx context.Context, perm accesstypes.Permission, resources ...accesstypes.Resource) (ok bool, missing []accesstypes.Resource, err error)
	Domain() accesstypes.Domain
	User() accesstypes.User
}

UserPermissions is an interface that provides methods to check user permissions and retrieve user information, and is used in the PatchSet and QuerySet types to enforce user permissions on resources.

type ValidateFunc added in v0.3.1

type ValidateFunc func(ctx context.Context, txn TxnBuffer) error

ValidateFunc is the signature for a function that validates a PatchSet prior to committing it.

type ValidatorFunc added in v0.0.3

type ValidatorFunc interface {
	Struct(s interface{}) error
	StructPartial(s interface{}, fields ...string) error
}

ValidatorFunc is a function that validates s It returns an error if the validation fails

Directories

Path Synopsis
Package generation provides tools for generating resource-driven API boilerplate in Go & TypeScript based on Go structures and a Spanner DB schema.
Package generation provides tools for generating resource-driven API boilerplate in Go & TypeScript based on Go structures and a Spanner DB schema.
parser
Package parser is a simplified abstraction over go/parser, tailored for the go:generate resource/generation tool.
Package parser is a simplified abstraction over go/parser, tailored for the go:generate resource/generation tool.
parser/genlang
Package genlang provides parsing for godoc comment annotations
Package genlang provides parsing for godoc comment annotations

Jump to

Keyboard shortcuts

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