repo

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Equal       ComparisonOp = "="
	NotEqual    ComparisonOp = "!="
	GreaterThan ComparisonOp = ">"
	LessThan    ComparisonOp = "<"

	Desc OrderDirection = "desc"
	Asc  OrderDirection = "asc"

	IDField             QueryField = "id"
	TypeField           QueryField = "type"
	RegionField         QueryField = "region"
	IdentifierField     QueryField = "identifier"
	KeyField            QueryField = "key"
	KeyTypeField        QueryField = "key_type"
	KeyConfigIDField    QueryField = "key_configuration_id"
	AdminGroupIDField   QueryField = "admin_group_id"
	ResourceIDField     QueryField = "resource_id"
	IsPrimaryField      QueryField = "is_primary"
	VersionField        QueryField = "version"
	StateField          QueryField = "state"
	StatusField         QueryField = "status"
	ArtifactField       QueryField = "artifact"
	UserField           QueryField = "user"
	ParametersField     QueryField = "parameters"
	WorkflowField       QueryField = "workflow"
	ApprovedField       QueryField = "approved"
	ArtifactTypeField   QueryField = "artifact_type"
	ArtifactIDField     QueryField = "artifact_id"
	ActionTypeField     QueryField = "action_type"
	InitiatorIDField    QueryField = "initiator_id"
	UserIDField         QueryField = "user_id"
	PrimaryKeyIDField   QueryField = "primary_key_id"
	PurposeField        QueryField = "purpose"
	NameField           QueryField = "name"
	AutoRotateField     QueryField = "auto_rotate"
	ExpirationDateField QueryField = "expiration_date"
	CreationDateField   QueryField = "creation_date"
	CreatedField        QueryField = "created_at"
	IssuerURLField      QueryField = "issuer_url"
	IAMIdField          QueryField = "iam_identifier"
	Name                QueryField = "name"

	ArtifactNameField      QueryField = "artifact_name"
	ParamResourceNameField QueryField = "parameters_resource_name"

	// KeyconfigTotalSystems and KeyconfigTotalKeys are used as aliases in JOIN operations,
	// typically in combination with the tableName to reference aggregated fields.
	KeyconfigTotalSystems QueryField = "total_systems"
	KeyconfigTotalKeys    QueryField = "total_keys"
	SystemKeyconfigName   QueryField = "key_configuration_name"

	NotNull   QueryFieldValue = "not_null"
	NotEmpty  QueryFieldValue = "not_empty"
	Empty     QueryFieldValue = "empty"
	FalseNull QueryFieldValue = "false_null"

	InnerJoin JoinType = "INNER"
	LeftJoin  JoinType = "LEFT"
	RightJoin JoinType = "RIGHT"
	FullJoin  JoinType = "FULL"

	// AllFunc is used to select all fields in a table, such as table.*.
	// For a simple * selection, do not provide any query function.
	AllFunc AggregateFunction = "*"

	MinFunc   AggregateFunction = "MIN"
	MaxFunc   AggregateFunction = "MAX"
	CountFunc AggregateFunction = "COUNT"
	SumFunc   AggregateFunction = "SUM"
	AvgFunc   AggregateFunction = "AVG"
)
View Source
const DefaultLimit = 100

Variables

View Source
var (
	ErrMigratingTenantModels = errors.New("migrating tenant models for existing tenant")
	ErrSchemaNameLength      = errors.New("schema name length must be between 3 and 63 characters")
	ErrCreatingTenant        = errors.New("creating tenant failed")
	ErrOnboardingTenant      = errors.New("onboarding tenant failed")
	ErrOnboardingInProgress  = errors.New("another onboarding is already in progress")
	ErrValidatingTenant      = errors.New("validating tenant failed")
	ErrCountingItem          = errors.New("couldn't count total number of items for pagination")
	ErrListingItems          = errors.New("couldn't list items")
)
View Source
var (
	ErrInvalidUUID         = errors.New("invalid UUID format")
	ErrNotFound            = errors.New("resource not found")
	ErrUniqueConstraint    = errors.New("unique constraint violation")
	ErrCreateResource      = errors.New("failed to create resource")
	ErrSetResource         = errors.New("failed to set resource")
	ErrUpdateResource      = errors.New("failed to update resource")
	ErrDeleteResource      = errors.New("failed to delete resource")
	ErrGetResource         = errors.New("failed to get resource")
	ErrTransaction         = errors.New("failed to execute transaction")
	ErrWithTenant          = errors.New("failed to use tenant from context")
	ErrTenantNotFound      = errors.New("tenant not found")
	ErrInvalidFieldName    = errors.New("invalid field name")
	ErrKeyConfigName       = errors.New("failed getting keyconfig name")
	ErrSystemProperties    = errors.New("failed getting system properties")
	ErrBatcherResourceType = errors.New("all resources should be of the same type")

	SQLNullBoolNull = sql.NullBool{Valid: false, Bool: true}
)
View Source
var ErrMultipleOperationsProvided = errors.New("multiple operations provided")

Functions

func GetSystemByIDWithProperties

func GetSystemByIDWithProperties(ctx context.Context, r Repo, systemID uuid.UUID, query *Query) (*model.System, error)

func GetTenant

func GetTenant(ctx context.Context, r Repo) (*model.Tenant, error)

func GetTenantByID

func GetTenantByID(ctx context.Context, r Repo, tenantID string) (*model.Tenant, error)

func HasConnectedSystems

func HasConnectedSystems(ctx context.Context, r Repo, keyConfigID uuid.UUID) (bool, error)

func ListAndCount added in v0.3.0

func ListAndCount[T Resource](
	ctx context.Context,
	r Repo,
	pagination Pagination,
	item T,
	query *Query,
) ([]*T, int, error)

ListAndCount lists items paginated and returns total count of elements Total count is only returned if pagination.count is true

func ListAndCountSystemWithProperties added in v0.3.0

func ListAndCountSystemWithProperties(
	ctx context.Context,
	r Repo,
	pagination Pagination,
	query *Query,
) ([]*model.System, int, error)

func ProcessInBatch

func ProcessInBatch[T Resource](
	ctx context.Context,
	repo Repo,
	baseQuery *Query,
	batchSize int,
	processFunc func([]*T) error,
) error

ProcessInBatch retrieves and processes records in batches from the database based on the provided query parameters. It iterates through all matching records using pagination to avoid loading large datasets into memory. The processFunc is called on the records, allowing custom processing logic. Processing stops immediately if processFunc returns an error.

Note: If you are deleting items during processing, use ProcessInBatchWithOptions with DeleteMode enabled to avoid skipping records.

func ProcessInBatchWithOptions

func ProcessInBatchWithOptions[T Resource](
	ctx context.Context,
	repo Repo,
	baseQuery *Query,
	batchSize int,
	options BatchProcessOptions,
	processFunc func([]*T) error,
) error

ProcessInBatchWithOptions retrieves and processes records in batches based on the provided query parameters. It iterates through all matching records using pagination to avoid loading large datasets into memory. The processFunc is called on the records, allowing custom processing logic. Processing stops immediately if processFunc returns an error.

Options:

  • DeleteMode: When true, assumes items are being deleted during processing and keeps offset at 0 to avoid skipping records. This ensures all items are processed even as the total count decreases.

func ToSharedModel

func ToSharedModel[T LoadEntity](v *T, opts ...Opt[T]) (*T, error)

ToSharedModel is a generic function used to lazy load model values that are not stored in the database. It applies a series of Opt functions to the provided entity, allowing additional fields to be loaded as needed. Returns the modified entity or an error if any Opt function fails.

Types

type AggregateFunction

type AggregateFunction string

type BatchProcessOptions

type BatchProcessOptions struct {
	// DeleteMode indicates that items are being deleted during processing.
	// When true, the offset is not incremented to avoid skipping records.
	DeleteMode bool
}

BatchProcessOptions configures how ProcessInBatchWithOptions should handle batch processing.

type ComparisonOp

type ComparisonOp string

type CompositeKey

type CompositeKey struct {
	IsStrict bool // IsStrict indicates if the composite key will use AND logic / OR logic for conditions.
	Conds    []Condition
}

CompositeKey is a collection of QueryField and matching value that are collectively used to find a record. IsStrict: False Conds: Key = 1, Key2 = 1 where Key = 1 OR Key2 = 1

func NewCompositeKey

func NewCompositeKey() CompositeKey

NewCompositeKey creates and returns a new CompositeKey.

func (CompositeKey) Where

func (c CompositeKey) Where(q QueryField, v any,
	options ...func(v any) Key,
) CompositeKey

Where adds a condition to the CompositeKey.

type CompositeKeyEntry

type CompositeKeyEntry struct {
	Key Key
	Err error
}

CompositeKeyEntry represents an entry in a CompositeKey, containing a Key and an optional error for validation or processing.

type CompositeKeyGroup

type CompositeKeyGroup struct {
	CompositeKey CompositeKey
	IsStrict     bool
}

func NewCompositeKeyGroup

func NewCompositeKeyGroup(key CompositeKey) CompositeKeyGroup

func (*CompositeKeyGroup) String

func (ckg *CompositeKeyGroup) String() string

type Condition

type Condition struct {
	Field QueryField
	Value CompositeKeyEntry
}

func (*Condition) String

func (c *Condition) String() string

type JoinClause

type JoinClause struct {
	OnCondition JoinCondition
	Type        JoinType
}

func (*JoinClause) JoinStatement

func (r *JoinClause) JoinStatement() string

type JoinCondition

type JoinCondition struct {
	Table     table
	Field     string
	JoinTable table
	JoinField string
}

type JoinType

type JoinType string

type Key

type Key struct {
	Value     any
	Operation ComparisonOp
}

func Gt

func Gt(v any) Key

func Lt

func Lt(v any) Key

func NotEq

func NotEq(v any) Key

type LoadEntity

type LoadEntity interface {
	model.System |
		model.KeyConfiguration
}

LoadEntity is a type constraint for entities from the database that contain models with attributes that can be lazy loaded.

type LoadingFields

type LoadingFields struct {
	Table       table
	JoinField   QueryField
	SelectField SelectField
}

type Opt

type Opt[T LoadEntity] func(*T) error

type OrderDirection

type OrderDirection string

type OrderField

type OrderField struct {
	Field     QueryField
	Direction OrderDirection
}

type Pagination added in v0.3.0

type Pagination struct {
	Skip  int
	Top   int
	Count bool
}

type Preload

type Preload []string

type Query

type Query struct {
	// Limit is a max size of returned elements.
	Limit int

	Offset int

	// CompositeKeys form the where part of the Query
	CompositeKeyGroup []CompositeKeyGroup

	// PreloadModel specifies which associations to preload.
	PreloadModel Preload

	// Used when updating a model with zero-values
	// If All is true all fields will be updated. Otherwise only the provided will be updated
	// If this is not provided, only non-zero values are updated
	UpdateFields Update

	// Used whenever a custom select is desired
	// By default, if this is not provided select all fields
	SelectFields []*SelectField

	// Joins stores the JOIN clauses for the query.
	Joins []JoinClause

	// Used to aggregate columns. Use on GroupBy
	Group []QueryField

	OrderFields []OrderField
}

func NewQuery

func NewQuery() *Query

NewQuery creates and returns a new empty query.

func NewQueryWithFieldLoading

func NewQueryWithFieldLoading(table table, fields ...LoadingFields) *Query

func (*Query) GroupBy

func (q *Query) GroupBy(field ...QueryField) *Query

func (*Query) Join

func (q *Query) Join(joinType JoinType, onCondition JoinCondition) *Query

func (*Query) Order

func (q *Query) Order(orderFields ...OrderField) *Query

func (*Query) Preload

func (q *Query) Preload(model Preload) *Query

func (*Query) Select

func (q *Query) Select(fields ...*SelectField) *Query

func (*Query) SetLimit

func (q *Query) SetLimit(limit int) *Query

SetLimit sets the limit value for the query.

func (*Query) SetOffset

func (q *Query) SetOffset(offset int) *Query

SetOffset sets the offset value for the query.

func (*Query) Update

func (q *Query) Update(fields ...QueryField) *Query

func (*Query) UpdateAll

func (q *Query) UpdateAll(b bool) *Query

func (*Query) Where

func (q *Query) Where(conds ...CompositeKeyGroup) *Query

type QueryField

type QueryField = string

type QueryFieldValue

type QueryFieldValue = string

type QueryFunction

type QueryFunction struct {
	Function AggregateFunction
	Distinct bool
}

type QueryMapper

type QueryMapper interface {
	GetQuery(ctx context.Context) *Query
	GetUUID(field QueryField) (uuid.UUID, error)
	GetPagination() Pagination
}

QueryMapper can just be a struct of filter values (for eg) for simple case (eg internal system user) In API controllers might want to have mapping from odata (for eg)

type Repo

type Repo interface {
	Create(ctx context.Context, resource Resource) error
	List(ctx context.Context, resource Resource, result any, query Query) error
	Delete(ctx context.Context, resource Resource, query Query) (bool, error)
	First(ctx context.Context, resource Resource, query Query) (bool, error)
	Patch(ctx context.Context, resource Resource, query Query) (bool, error)
	Set(ctx context.Context, resource Resource) error
	Transaction(ctx context.Context, txFunc TransactionFunc) error
	Count(ctx context.Context, resource Resource, query Query) (int, error)
	OffboardTenant(ctx context.Context, tenantID string) error
}

Repo defines an interface for Repository operations.

type Resource

type Resource interface {
	IsSharedModel() bool
	TableName() string
}

Resource defines the interface for Resource operations.

type SelectField

type SelectField struct {
	Field QueryField
	Func  QueryFunction
	Alias string
}

func NewConditionalSelectField

func NewConditionalSelectField(alias string, ck ...CompositeKeyGroup) *SelectField

func NewSelectField

func NewSelectField(field QueryField, f QueryFunction) *SelectField

func (*SelectField) SelectStatement

func (f *SelectField) SelectStatement() string

func (*SelectField) SetAlias

func (f *SelectField) SetAlias(alias string) *SelectField

type TransactionFunc

type TransactionFunc func(context.Context) error

TransactionFunc is func signature for ExecTransaction.

type UniqueConstraintError

type UniqueConstraintError struct {
	Detail string
}

UniqueConstraintError represents an error caused by a violation of a unique constraint in the database.

func (*UniqueConstraintError) Error

func (u *UniqueConstraintError) Error() string

Error returns an error message describing the unique constraint violation.

type Update

type Update struct {
	Fields []QueryField
	All    bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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