Documentation
¶
Index ¶
- Constants
- Variables
- func GetSystemByIDWithProperties(ctx context.Context, r Repo, systemID uuid.UUID, query *Query) (*model.System, error)
- func GetTenant(ctx context.Context, r Repo) (*model.Tenant, error)
- func GetTenantByID(ctx context.Context, r Repo, tenantID string) (*model.Tenant, error)
- func HasConnectedSystems(ctx context.Context, r Repo, keyConfigID uuid.UUID) (bool, error)
- func ListAndCount[T Resource](ctx context.Context, r Repo, pagination Pagination, item T, query *Query) ([]*T, int, error)
- func ListAndCountSystemWithProperties(ctx context.Context, r Repo, pagination Pagination, query *Query) ([]*model.System, int, error)
- func ProcessInBatch[T Resource](ctx context.Context, repo Repo, baseQuery *Query, batchSize int, ...) error
- func ProcessInBatchWithOptions[T Resource](ctx context.Context, repo Repo, baseQuery *Query, batchSize int, ...) error
- func ToSharedModel[T LoadEntity](v *T, opts ...Opt[T]) (*T, error)
- type AggregateFunction
- type BatchProcessOptions
- type ComparisonOp
- type CompositeKey
- type CompositeKeyEntry
- type CompositeKeyGroup
- type Condition
- type JoinClause
- type JoinCondition
- type JoinType
- type Key
- type LoadEntity
- type LoadingFields
- type Opt
- type OrderDirection
- type OrderField
- type Pagination
- type Preload
- type Query
- func (q *Query) GroupBy(field ...QueryField) *Query
- func (q *Query) Join(joinType JoinType, onCondition JoinCondition) *Query
- func (q *Query) Order(orderFields ...OrderField) *Query
- func (q *Query) Preload(model Preload) *Query
- func (q *Query) Select(fields ...*SelectField) *Query
- func (q *Query) SetLimit(limit int) *Query
- func (q *Query) SetOffset(offset int) *Query
- func (q *Query) Update(fields ...QueryField) *Query
- func (q *Query) UpdateAll(b bool) *Query
- func (q *Query) Where(conds ...CompositeKeyGroup) *Query
- type QueryField
- type QueryFieldValue
- type QueryFunction
- type QueryMapper
- type Repo
- type Resource
- type SelectField
- type TransactionFunc
- type UniqueConstraintError
- type Update
Constants ¶
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" )
const DefaultLimit = 100
Variables ¶
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") )
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} )
var ErrMultipleOperationsProvided = errors.New("multiple operations provided")
Functions ¶
func GetTenantByID ¶
func HasConnectedSystems ¶
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 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 ¶
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
}
type JoinClause ¶
type JoinClause struct {
OnCondition JoinCondition
Type JoinType
}
func (*JoinClause) JoinStatement ¶
func (r *JoinClause) JoinStatement() string
type JoinCondition ¶
type Key ¶
type Key struct {
Value any
Operation ComparisonOp
}
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 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 NewQueryWithFieldLoading ¶
func NewQueryWithFieldLoading(table table, fields ...LoadingFields) *Query
func (*Query) GroupBy ¶
func (q *Query) GroupBy(field ...QueryField) *Query
func (*Query) Order ¶
func (q *Query) Order(orderFields ...OrderField) *Query
func (*Query) Select ¶
func (q *Query) Select(fields ...*SelectField) *Query
func (*Query) Update ¶
func (q *Query) Update(fields ...QueryField) *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 {
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 ¶
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
}