Documentation ¶
Overview ¶
Package database provides an interface for database operations.
Index ¶
- Constants
- Variables
- func CallBeforePropagationStepHook(step PropagationStep)
- func ClearAllDBEnums()
- func ContextWithTransactionRetrying(ctx context.Context) context.Context
- func Default() interface{}
- func EscapeLikeString(v string, escapeCharacter byte) string
- func IsDeadlockError(err error) bool
- func IsDuplicateEntryError(err error) bool
- func IsDuplicateEntryErrorForKey(err error, key string) bool
- func IsForeignConstraintError(err error) bool
- func IsLockWaitTimeoutExceededError(err error) bool
- func IsThreadClosedStatus(status string) bool
- func IsThreadOpenStatus(status string) bool
- func MockDBEnumQueries(sqlMock sqlmock.Sqlmock)
- func MockNow(timestamp string)
- func NewRawDBLogger() instrumentedsql.Logger
- func Now() interface{}
- func OpenRawDBConnection(sourceDSN string, enableRawLevelLogging bool) (*sql.DB, error)
- func ProhibitResultsPropagation(conn *DB)
- func PropagationStepSetAccess() *golang.Set[PropagationStep]
- func PropagationStepSetResults() *golang.Set[PropagationStep]
- func QuoteName(name string) string
- func RestoreNow()
- func SetBeforePropagationStepHook(newHook BeforePropagationStepHookFunc)
- func SetOnForcefulRetryOfTransactionHook(hook func())
- func SetOnStartOfTransactionToBeRetriedForcefullyHook(hook func())
- type AccessTokenStore
- type AnswerStore
- func (s *AnswerStore) GetCurrentAnswer(participantID, itemID, attemptID int64) (map[string]interface{}, bool)
- func (s *AnswerStore) SubmitNewAnswer(authorID, participantID, attemptID, itemID int64, answer string) (int64, error)
- func (s *AnswerStore) WithGradings() *AnswerStore
- func (s *AnswerStore) WithItems() *AnswerStore
- func (s *AnswerStore) WithResults() *AnswerStore
- func (s *AnswerStore) WithUsers() *AnswerStore
- type AttemptStore
- type Badge
- type BadgeGroupPathElement
- type BadgeInfo
- type BeforePropagationStepHookFunc
- type DB
- func (conn *DB) Close() error
- func (conn *DB) Count(dest interface{}) *DB
- func (conn *DB) Delete(where ...interface{}) *DB
- func (conn *DB) Error() error
- func (conn *DB) Exec(sqlQuery string, values ...interface{}) *DB
- func (conn *DB) GetContext() context.Context
- func (conn *DB) Group(query string) *DB
- func (conn *DB) HasRows() (bool, error)
- func (conn *DB) Having(query interface{}, args ...interface{}) *DB
- func (conn *DB) HavingMaxPermissionAtLeast(permissionKind, permissionName string) *DB
- func (conn *DB) InsertIgnoreMaps(tableName string, dataMaps []map[string]interface{}) error
- func (conn *DB) Joins(query string, args ...interface{}) *DB
- func (conn *DB) JoinsPermissionsForGroupToItems(groupID int64) *DB
- func (conn *DB) JoinsPermissionsForGroupToItemsWherePermissionAtLeast(groupID int64, permissionKind, neededPermission string) *DB
- func (conn *DB) JoinsUserAndDefaultItemStrings(user *User) *DB
- func (conn *DB) Limit(limit interface{}) *DB
- func (conn *DB) New() *DB
- func (conn *DB) Offset(offset interface{}) *DB
- func (conn *DB) Order(value interface{}, reorder ...bool) *DB
- func (conn *DB) Pluck(column string, values interface{}) *DB
- func (conn *DB) PluckFirst(column string, value interface{}) *DB
- func (conn *DB) Prepare(query string) (*SQLStmtWrapper, error)
- func (conn *DB) QueryExpr() interface{}
- func (conn *DB) Raw(query string, args ...interface{}) *DB
- func (conn *DB) RowsAffected() int64
- func (conn *DB) Scan(dest interface{}) *DB
- func (conn *DB) ScanAndHandleMaps(handler func(map[string]interface{}) error) *DB
- func (conn *DB) ScanIntoSliceOfMaps(dest *[]map[string]interface{}) *DB
- func (conn *DB) ScanIntoSlices(pointersToSlices ...interface{}) *DB
- func (conn *DB) Select(query interface{}, args ...interface{}) *DB
- func (conn *DB) Set(name string, value interface{}) *DB
- func (conn *DB) SubQuery() interface{}
- func (conn *DB) Table(name string) *DB
- func (conn *DB) Take(out interface{}, where ...interface{}) *DB
- func (conn *DB) Union(query *DB) *DB
- func (conn *DB) UnionAll(query *DB) *DB
- func (conn *DB) UpdateColumn(attrs ...interface{}) *DB
- func (conn *DB) UpdateColumns(attrs ...interface{}) *DB
- func (conn *DB) Where(query interface{}, args ...interface{}) *DB
- func (conn *DB) WhereGroupHasPermissionOnItems(groupID int64, permissionKind, neededPermission string) *DB
- func (conn *DB) WhereGroupRelationIsActual() *DB
- func (conn *DB) WhereItemHasResultStartedByUser(user *User) *DB
- func (conn *DB) WhereItemsAreSelfOrDescendantsOf(itemAncestorID int64) *DB
- func (conn *DB) WhereItemsAreVisible(groupID int64) *DB
- func (conn *DB) WhereItemsContentAreVisible(groupID int64) *DB
- func (conn *DB) WherePermissionIsAtLeast(permissionKind, permissionName string) *DB
- func (conn *DB) WhereSearchStringMatches(field, fallbackField, searchString string) *DB
- func (conn *DB) WhereUserHasPermissionOnItems(user *User, permissionKind, neededPermission string) *DB
- func (conn *DB) WhereUserHasViewPermissionOnItems(user *User, viewPermission string) *DB
- func (conn *DB) WhereUsersAreDescendantsOfGroup(groupID int64) *DB
- func (conn *DB) With(name string, query *DB) *DB
- func (conn *DB) WithCustomWriteLocks(shared, exclusive *golang.Set[string]) *DB
- func (conn *DB) WithExclusiveWriteLock() *DB
- func (conn *DB) WithPersonalInfoViewApprovals(manager *User) *DB
- func (conn *DB) WithSharedWriteLock() *DB
- type DataStore
- func (s *DataStore) AccessTokens() *AccessTokenStore
- func (s *DataStore) ActiveGroupAncestors() *GroupAncestorStore
- func (s *DataStore) ActiveGroupGroups() *GroupGroupStore
- func (s *DataStore) Answers() *AnswerStore
- func (s *DataStore) Attempts() *AttemptStore
- func (s *DataStore) ByID(id int64) *DB
- func (s *DataStore) CheckIfTeamParticipationsConflictWithExistingUserMemberships(teamID, userGroupID int64, withLock bool) (bool, error)
- func (s *DataStore) EnsureTransaction(txFunc func(*DataStore) error, txOptions ...*sql.TxOptions) error
- func (s *DataStore) GetGroupJoiningByCodeInfoByCode(code string, withLock bool) (*GroupJoiningByCodeInfo, error)
- func (s *DataStore) Gradings() *GradingStore
- func (s *DataStore) GroupAncestors() *GroupAncestorStore
- func (s *DataStore) GroupContestItems() *GroupContestItemStore
- func (s *DataStore) GroupGroups() *GroupGroupStore
- func (s *DataStore) GroupManagers() *GroupManagerStore
- func (s *DataStore) GroupMembershipChanges() *GroupMembershipChangeStore
- func (s *DataStore) GroupPendingRequests() *GroupPendingRequestStore
- func (s *DataStore) Groups() *GroupStore
- func (s *DataStore) InTransaction(txFunc func(*DataStore) error, txOptions ...*sql.TxOptions) error
- func (s *DataStore) InsertMap(dataMap map[string]interface{}) error
- func (s *DataStore) InsertMaps(dataMaps []map[string]interface{}) error
- func (s *DataStore) InsertOrUpdateMap(dataMap map[string]interface{}, updateColumns []string) error
- func (s *DataStore) InsertOrUpdateMaps(dataMap []map[string]interface{}, updateColumns []string) error
- func (s *DataStore) IsInTransaction() bool
- func (s *DataStore) IsResultsPropagationProhibited() bool
- func (s *DataStore) ItemAncestors() *ItemAncestorStore
- func (s *DataStore) ItemDependencies() *ItemDependencyStore
- func (s *DataStore) ItemItems() *ItemItemStore
- func (s *DataStore) ItemStrings() *ItemStringStore
- func (s *DataStore) Items() *ItemStore
- func (s *DataStore) Languages() *LanguageStore
- func (s *DataStore) MergeContext(ctx context.Context) context.Context
- func (s *DataStore) NewID() int64
- func (s *DataStore) NewThreadStore(db *DB) *ThreadStore
- func (s *DataStore) Permissions() *PermissionGeneratedStore
- func (s *DataStore) PermissionsGranted() *PermissionGrantedStore
- func (s *DataStore) Platforms() *PlatformStore
- func (s *DataStore) Results() *ResultStore
- func (s *DataStore) RetryOnDuplicateKeyError(keyName, nameInError string, f func(store *DataStore) error) error
- func (s *DataStore) RetryOnDuplicatePrimaryKeyError(f func(store *DataStore) error) error
- func (s *DataStore) SchedulePermissionsPropagation()
- func (s *DataStore) ScheduleResultsPropagation()
- func (s *DataStore) Sessions() *SessionStore
- func (s *DataStore) SetPropagationsModeToSync() (err error)
- func (s *DataStore) Threads() *ThreadStore
- func (s *DataStore) UserBatchPrefixes() *UserBatchPrefixStore
- func (s *DataStore) UserBatches() *UserBatchStore
- func (s *DataStore) Users() *UserStore
- func (s *DataStore) WithCustomWriteLocks(shared, exclusive *golang.Set[string]) *DataStore
- func (s *DataStore) WithExclusiveWriteLock() *DataStore
- func (s *DataStore) WithForeignKeyChecksDisabled(blockFunc func(*DataStore) error, txOptions ...*sql.TxOptions) error
- func (s *DataStore) WithNamedLock(lockName string, timeout time.Duration, funcToCall func(*DataStore) error) error
- func (s *DataStore) WithSharedWriteLock() *DataStore
- type GradingStore
- type GroupAncestorStore
- type GroupApprovals
- type GroupContestItemStore
- type GroupGroupStore
- func (s *GroupGroupStore) CreateNewAncestors() (err error)
- func (s *GroupGroupStore) CreateRelation(parentGroupID, childGroupID int64) (err error)
- func (s *GroupGroupStore) CreateRelationsWithoutChecking(relations []map[string]interface{}) (err error)
- func (s *GroupGroupStore) DeleteRelation(parentGroupID, childGroupID int64, shouldDeleteOrphans bool) (err error)
- func (s *GroupGroupStore) TeamGroupForTeamItemAndUser(itemID int64, user *User) *DB
- func (s *GroupGroupStore) Transition(action GroupGroupTransitionAction, parentGroupID int64, childGroupIDs []int64, ...) (results GroupGroupTransitionResults, ...)
- func (s *GroupGroupStore) WhereUserIsMember(user *User) *DB
- type GroupGroupTransitionAction
- type GroupGroupTransitionResult
- type GroupGroupTransitionResults
- type GroupJoiningByCodeInfo
- type GroupManagerStore
- type GroupMembershipAction
- type GroupMembershipChangeStore
- type GroupPendingRequestStore
- type GroupStore
- func (s *GroupStore) AncestorsOfJoinedGroups(store *DataStore, user *User) *DB
- func (s *GroupStore) AncestorsOfJoinedGroupsForGroup(store *DataStore, groupID int64) *DB
- func (s *GroupStore) AvailableGroupsBySearchString(user *User, searchString string) *DB
- func (s *GroupStore) CheckIfEntryConditionsStillSatisfiedForAllActiveParticipations(teamGroupID, userID int64, isAdding, withLock bool) (bool, error)
- func (s *GroupStore) CreateNew(name, groupType string) (groupID int64, err error)
- func (s *GroupStore) DeleteGroup(groupID int64) (err error)
- func (s *GroupStore) GenerateQueryCheckingIfActionBreaksEntryConditionsForActiveParticipations(teamGroupIDExpr *gorm.SqlExpr, userID int64, isAdding, withLock bool) *DB
- func (s *GroupStore) GetDirectParticipantIDsOf(groupID int64) (participantIDs []int64)
- func (s *GroupStore) HasParticipants(groupID int64) (hasParticipants bool, err error)
- func (s *GroupStore) IsVisibleFor(groupID int64, user *User) bool
- func (s *GroupStore) IsVisibleForGroup(groupID, visibleForGroupID int64) bool
- func (s *GroupStore) ManagedBy(user *User) *DB
- func (s *GroupStore) ManagedUsersAndAncestorsOfManagedGroupsForGroup(store *DataStore, groupID int64) *DB
- func (s *GroupStore) PickVisibleGroups(db *DB, user *User) *DB
- func (s *GroupStore) PickVisibleGroupsForGroup(db *DB, visibleForGroupID int64) *DB
- func (s *GroupStore) PossibleSubgroupsBySearchString(user *User, searchString string) *DB
- func (s *GroupStore) StoreBadges(badges []Badge, userID int64, newUser bool) (err error)
- func (s *GroupStore) TeamGroupForUser(teamGroupID int64, user *User) *DB
- type HintsInfo
- type ItemAccessDetails
- type ItemAccessDetailsWithID
- type ItemAncestorStore
- type ItemDependencyStore
- type ItemItemStore
- func (s *ItemItemStore) ChildrenOf(parentID int64) *ItemItemStore
- func (s *ItemItemStore) ContentViewPropagationIndexByName(name string) int
- func (s *ItemItemStore) ContentViewPropagationNameByIndex(index int) string
- func (s *ItemItemStore) CreateNewAncestors() (err error)
- func (s *ItemItemStore) UpperViewLevelsPropagationIndexByName(name string) int
- func (s *ItemItemStore) UpperViewLevelsPropagationNameByIndex(index int) string
- func (s *ItemItemStore) WithItemsRelationsLock(txFunc func(*DataStore) error) error
- type ItemStore
- func (s *ItemStore) BreadcrumbsHierarchyForAttempt(ids []int64, groupID, attemptID int64, withWriteLock bool) (attemptIDMap map[int64]int64, attemptNumberMap map[int64]int, err error)
- func (s *ItemStore) BreadcrumbsHierarchyForParentAttempt(ids []int64, groupID, parentAttemptID int64, withWriteLock bool) (attemptIDMap map[int64]int64, attemptNumberMap map[int64]int, err error)
- func (s *ItemStore) CheckSubmissionRights(participantID, itemID int64) (hasAccess bool, reason, err error)
- func (s *ItemStore) ContestManagedByUser(contestItemID int64, user *User) *DB
- func (s *ItemStore) DeleteItem(itemID int64) (err error)
- func (s *ItemStore) GetAncestorsRequestHelpPropagatedQuery(itemID int64) *DB
- func (s *ItemStore) GetItemIDFromTextID(textID string) (itemID int64, err error)
- func (s *ItemStore) GetSearchQuery(user *User, searchString string, typesList []string) *DB
- func (s *ItemStore) GroupHasPermissionOnItem(groupID, itemID int64, permissionKind, neededPermission string) bool
- func (s *ItemStore) HasCanRequestHelpTo(itemID, groupID int64) bool
- func (s *ItemStore) IsValidParticipationHierarchyForParentAttempt(ids []int64, groupID, parentAttemptID int64, ...) (bool, error)
- func (s *ItemStore) Visible(groupID int64) *DB
- func (s *ItemStore) VisibleByID(groupID, itemID int64) *DB
- type ItemStringStore
- type LanguageStore
- type LogConfig
- type MostRecentToken
- type ParentChild
- type PermissionGeneratedStore
- func (s *PermissionGeneratedStore) AggregatedPermissionsForItems(groupID int64) *DB
- func (s *PermissionGeneratedStore) AggregatedPermissionsForItemsOnWhichGroupHasPermission(groupID int64, permissionKind, neededPermission string) *DB
- func (s *PermissionGeneratedStore) AggregatedPermissionsForItemsOnWhichGroupHasViewPermission(groupID int64, viewPermission string) *DB
- func (s *PermissionGeneratedStore) AggregatedPermissionsForItemsVisibleToGroup(groupID int64) *DB
- func (s *PermissionGeneratedStore) MatchingGroupAncestors(groupID int64) *DB
- func (s *PermissionGeneratedStore) MatchingUserAncestors(user *User) *DB
- type PermissionGrantedStore
- func (s *PermissionGrantedStore) EditIndexByName(name string) int
- func (s *PermissionGrantedStore) EditNameByIndex(index int) string
- func (s *PermissionGrantedStore) GrantViewIndexByName(name string) int
- func (s *PermissionGrantedStore) GrantViewNameByIndex(index int) string
- func (s *PermissionGrantedStore) PermissionIndexByKindAndName(kind, name string) int
- func (s *PermissionGrantedStore) PermissionIsAtLeastSQLExpr(permissionKind, permissionName string) *gorm.SqlExpr
- func (s *PermissionGrantedStore) PermissionNameByKindAndIndex(kind string, index int) string
- func (s *PermissionGrantedStore) ViewIndexByName(name string) int
- func (s *PermissionGrantedStore) ViewNameByIndex(index int) string
- func (s *PermissionGrantedStore) WatchIndexByName(name string) int
- func (s *PermissionGrantedStore) WatchNameByIndex(index int) string
- type PlatformStore
- type PropagationStep
- type RawGeneratedPermissionFields
- type ResultStore
- func (s *ResultStore) ByID(participantID, attemptID, itemID int64) *DB
- func (s *ResultStore) GetHintsInfoForActiveAttempt(participantID, attemptID, itemID int64) (result *HintsInfo, err error)
- func (s *ResultStore) MarkAsToBePropagated(participantID, attemptID, itemID int64, propagateNow bool) error
- func (s *ResultStore) PropagateAndCollectUnlockedItemsForParticipant(participantID int64) (participantItemsUnlocked *golang.Set[int64], err error)
- type SQLStmtWrapper
- func (s *SQLStmtWrapper) Close() error
- func (s *SQLStmtWrapper) ExecContext(ctx context.Context, args ...interface{}) (result sql.Result, err error)
- func (s *SQLStmtWrapper) QueryContext(ctx context.Context, args ...interface{}) (rows *sql.Rows, err error)
- func (s *SQLStmtWrapper) QueryRowContext(ctx context.Context, args ...interface{}) (row *sql.Row)
- type SessionStore
- type ThreadStore
- func (s *ThreadStore) CanRetrieveThread(user *User, participantID, itemID int64) bool
- func (s *ThreadStore) GetThreadInfo(participantID, itemID int64, out interface{}) error
- func (s *ThreadStore) GetThreadQuery(participantID, itemID int64) *DB
- func (s *ThreadStore) GetThreadStatus(participantID, itemID int64) string
- func (s *ThreadStore) JoinsItem() *ThreadStore
- func (s *ThreadStore) JoinsUserParticipant() *ThreadStore
- func (s *ThreadStore) UpdateHelperGroupID(oldHelperGroupID, newHelperGroupID int64)
- func (s *ThreadStore) UserCanChangeStatus(user *User, oldStatus, newStatus string, participantID, itemID int64) bool
- func (s *ThreadStore) UserCanWrite(user *User, participantID, itemID int64) bool
- func (s *ThreadStore) WhereParticipantIsInGroup(groupID int64) *ThreadStore
- func (s *ThreadStore) WhereUserCanHelp(user *User) *ThreadStore
- type Time
- type User
- func (u *User) CanRequestHelpTo(s *DataStore, itemID, helperGroupID int64) bool
- func (u *User) CanSeeAnswer(s *DataStore, participantID, itemID int64) bool
- func (u *User) CanViewItemContent(s *DataStore, itemID int64) bool
- func (u *User) CanViewItemInfo(s *DataStore, itemID int64) bool
- func (u *User) CanWatchGroupMembers(s *DataStore, groupID int64) bool
- func (u *User) CanWatchItemAnswer(s *DataStore, itemID int64) bool
- func (u *User) CanWatchItemResult(s *DataStore, itemID int64) bool
- func (u *User) Clone() *User
- func (u *User) GetManagedGroupsWithCanGrantGroupAccessIds(store *DataStore) []int64
- func (u *User) HasItemPermission(s *DataStore, itemID int64, permissionType, permissionValue string) bool
- func (u *User) HasStartedResultOnItem(s *DataStore, itemID int64) bool
- func (u *User) HasValidatedItem(s *DataStore, itemID int64) bool
- func (u *User) IsItemOwner(s *DataStore, itemID int64) bool
- func (u *User) IsMemberOfGroupOrSelf(s *DataStore, groupID int64) bool
- type UserBatchPrefixStore
- type UserBatchStore
- type UserStore
- func (s *UserStore) ByID(id int64) *DB
- func (s *UserStore) DeleteTemporaryWithTraps(delay time.Duration) (err error)
- func (s *UserStore) DeleteWithTraps(user *User, isTemporary bool) (err error)
- func (s *UserStore) DeleteWithTrapsByScope(scopeFunc func(store *DataStore) *DB, isTemporary bool) (err error)
Constants ¶
const AccessTokenMaxLength = 2000
AccessTokenMaxLength is the maximum length of an access token.
Variables ¶
var ErrNamedLockWaitTimeoutExceeded = errors.New("named lock wait timeout exceeded")
ErrNamedLockWaitTimeoutExceeded is returned when we cannot acquire a named lock.
var ErrNoTransaction = errors.New("should be executed in a transaction")
ErrNoTransaction means that a called method/function cannot work outside of a transaction.
var ErrRelationCycle = errors.New("a group cannot become an ancestor of itself")
ErrRelationCycle is returned by CreateRelation() if the relation is impossible because it would create a cycle in the groups_groups graph.
Functions ¶
func CallBeforePropagationStepHook ¶ added in v2.21.4
func CallBeforePropagationStepHook(step PropagationStep)
CallBeforePropagationStepHook calls the hook that is called before each propagation step.
func ContextWithTransactionRetrying ¶ added in v2.23.3
ContextWithTransactionRetrying wraps the given context with a flag to retry each transaction once. Use it for testing purposes only.
func EscapeLikeString ¶
EscapeLikeString escapes string with the given escape character. This escapes the contents of a string (provided as string) by adding the escape character before percent signs (%), and underscore signs (_).
func IsDeadlockError ¶ added in v2.23.0
IsDeadlockError checks whether an error corresponds to a deadlock when trying to get a lock.
func IsDuplicateEntryError ¶
IsDuplicateEntryError checks whether an error corresponds to a duplicate of primary keys on insertion.
func IsDuplicateEntryErrorForKey ¶
IsDuplicateEntryErrorForKey checks whether an error corresponds to a duplicate of primary keys on insertion for a certain key.
func IsForeignConstraintError ¶
IsForeignConstraintError checks whether an error corresponds to a foreign key constraint fail on insert/update.
func IsLockWaitTimeoutExceededError ¶ added in v2.23.0
IsLockWaitTimeoutExceededError checks whether an error corresponds to a lock wait timeout exceeded.
func IsThreadClosedStatus ¶
IsThreadClosedStatus checks whether a status is considered closed.
func IsThreadOpenStatus ¶
IsThreadOpenStatus checks whether a status is considered open.
func MockDBEnumQueries ¶
MockDBEnumQueries stubs all the db queries for loading permission enums.
func MockNow ¶
func MockNow(timestamp string)
MockNow changes the DB expression for getting current DB time so that it will return the given timestamp.
func NewRawDBLogger ¶ added in v2.23.7
func NewRawDBLogger() instrumentedsql.Logger
NewRawDBLogger returns a logger for raw database actions.
func Now ¶
func Now() interface{}
Now returns a DB expression that returns current DB time (it is usually gorm.Expr("NOW()")).
func OpenRawDBConnection ¶
OpenRawDBConnection creates a new DB connection.
func ProhibitResultsPropagation ¶ added in v2.22.4
func ProhibitResultsPropagation(conn *DB)
ProhibitResultsPropagation marks the context inside the DB connection as prohibiting the propagation of results.
func PropagationStepSetAccess ¶ added in v2.21.4
func PropagationStepSetAccess() *golang.Set[PropagationStep]
PropagationStepSetAccess returns a set of access (permissions) propagation steps.
func PropagationStepSetResults ¶ added in v2.21.4
func PropagationStepSetResults() *golang.Set[PropagationStep]
PropagationStepSetResults returns a set of results propagation steps.
func QuoteName ¶
QuoteName surrounds a given table/column name in backtick quotes and escapes the content.
func RestoreNow ¶
func RestoreNow()
RestoreNow sets the DB expression for getting current DB time to its default value (gorm.Expr("NOW()")).
func SetBeforePropagationStepHook ¶ added in v2.21.4
func SetBeforePropagationStepHook(newHook BeforePropagationStepHookFunc)
SetBeforePropagationStepHook sets a hook that is called before each propagation step.
func SetOnForcefulRetryOfTransactionHook ¶ added in v2.23.3
func SetOnForcefulRetryOfTransactionHook(hook func())
SetOnForcefulRetryOfTransactionHook sets a hook to be called on the retry of a forcefully retried transaction. For testing purposes only.
func SetOnStartOfTransactionToBeRetriedForcefullyHook ¶ added in v2.23.3
func SetOnStartOfTransactionToBeRetriedForcefullyHook(hook func())
SetOnStartOfTransactionToBeRetriedForcefullyHook sets a hook to be called on the start of a transaction that will be forcefully retried. For testing purposes only.
Types ¶
type AccessTokenStore ¶
type AccessTokenStore struct {
*DataStore
}
AccessTokenStore implements database operations on `access_tokens`.
func (*AccessTokenStore) DeleteExpiredTokensOfUser ¶
func (s *AccessTokenStore) DeleteExpiredTokensOfUser(userID int64) error
DeleteExpiredTokensOfUser deletes all expired tokens of the given user.
func (*AccessTokenStore) GetMostRecentValidTokenForSession ¶
func (s *AccessTokenStore) GetMostRecentValidTokenForSession(sessionID int64) (MostRecentToken, error)
GetMostRecentValidTokenForSession returns the most recent valid token for the given sessionID.
func (*AccessTokenStore) InsertNewToken ¶
func (s *AccessTokenStore) InsertNewToken(sessionID int64, token string, secondsUntilExpiry int32) error
InsertNewToken inserts a new OAuth token for the given sessionID into the DB.
type AnswerStore ¶
type AnswerStore struct {
*DataStore
}
AnswerStore implements database operations on `answers`.
func (*AnswerStore) GetCurrentAnswer ¶
func (s *AnswerStore) GetCurrentAnswer(participantID, itemID, attemptID int64) (map[string]interface{}, bool)
GetCurrentAnswer returns the current answer of a participant-item-attempt triplet.
func (*AnswerStore) SubmitNewAnswer ¶
func (s *AnswerStore) SubmitNewAnswer(authorID, participantID, attemptID, itemID int64, answer string) (int64, error)
SubmitNewAnswer inserts a new row with type='Submission', created_at=NOW() into the `answers` table.
func (*AnswerStore) WithGradings ¶
func (s *AnswerStore) WithGradings() *AnswerStore
WithGradings creates a composable query for getting answers joined with gradings (via answer_id).
func (*AnswerStore) WithItems ¶
func (s *AnswerStore) WithItems() *AnswerStore
WithItems joins `items`.
func (*AnswerStore) WithResults ¶
func (s *AnswerStore) WithResults() *AnswerStore
WithResults creates a composable query for getting answers joined with results.
func (*AnswerStore) WithUsers ¶
func (s *AnswerStore) WithUsers() *AnswerStore
WithUsers creates a composable query for getting answers joined with users (via author_id).
type AttemptStore ¶
type AttemptStore struct {
*DataStore
}
AttemptStore implements database operations on `attempts`.
func (*AttemptStore) CreateNew ¶
func (s *AttemptStore) CreateNew(participantID, parentAttemptID, itemID, creatorID int64) (attemptID int64, err error)
CreateNew creates a new attempt (with id > 0) with parent_attempt_id = parentAttemptID and a new result. It also sets attempts.created_at, results.started_at, results.latest_activity_at, so the result should be propagated.
type Badge ¶
type Badge struct { Manager bool `json:"manager" validate:"set"` URL string `json:"url" validate:"min=1"` // length >= 1 BadgeInfo BadgeInfo `json:"badge_info"` }
Badge represents a badge from the login module.
type BadgeGroupPathElement ¶
type BadgeGroupPathElement struct { Manager bool `json:"manager" validate:"set"` Name string `json:"name" validate:"set"` URL string `json:"url" validate:"min=1"` // length >= 1 }
BadgeGroupPathElement represents an element of a badge's group path.
type BadgeInfo ¶
type BadgeInfo struct { Name string `json:"name" validate:"set"` GroupPath []BadgeGroupPathElement `json:"group_path"` }
BadgeInfo contains a name and group path of a badge.
type BeforePropagationStepHookFunc ¶ added in v2.21.4
type BeforePropagationStepHookFunc func(step PropagationStep)
BeforePropagationStepHookFunc is a type of a function that is called before each propagation step.
func GetBeforePropagationStepHook ¶ added in v2.21.4
func GetBeforePropagationStepHook() BeforePropagationStepHookFunc
GetBeforePropagationStepHook returns a hook that is called before each propagation step.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB contains information for current db connection (wraps *gorm.DB).
func OpenWithLogConfig ¶ added in v2.23.5
func OpenWithLogConfig(source interface{}, lc LogConfig, rawSQLQueriesLoggingEnabled bool) (*DB, error)
OpenWithLogConfig connects to the database and tests the connection. It uses the given logging settings.
func (*DB) Close ¶
Close closes current db connection. If database connection is not an io.Closer, returns an error.
func (*DB) Delete ¶
Delete deletes value matching given conditions, if the value has primary key, then will including the primary key as condition.
func (*DB) GetContext ¶ added in v2.23.7
GetContext returns the context of the DB connection.
func (*DB) HavingMaxPermissionAtLeast ¶
HavingMaxPermissionAtLeast returns a composable query filtered by `MAX(can_*_generated_value)` >= indexOf(`permissionName`) depending on the given permission kind.
func (*DB) InsertIgnoreMaps ¶
InsertIgnoreMaps reads fields from the given maps and inserts the values set in the first row (so keys in all maps should be same) into the given table ignoring errors (such as duplicates).
func (*DB) Joins ¶
Joins specifies Joins conditions
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
func (*DB) JoinsPermissionsForGroupToItems ¶ added in v2.21.4
JoinsPermissionsForGroupToItems returns a composable query with access rights (as permissions.*_generated_value) for all the items.
func (*DB) JoinsPermissionsForGroupToItemsWherePermissionAtLeast ¶
func (conn *DB) JoinsPermissionsForGroupToItemsWherePermissionAtLeast(groupID int64, permissionKind, neededPermission string) *DB
JoinsPermissionsForGroupToItemsWherePermissionAtLeast returns a composable query with access rights (as permissions.*_generated_value) for all the items on that the given group has 'permissionKind' >= `neededPermission`.
func (*DB) JoinsUserAndDefaultItemStrings ¶
JoinsUserAndDefaultItemStrings joins items_strings with the given view twice (as default_strings for item's default language and as user_strings for the user's default language).
func (*DB) Order ¶
Order specifies order when retrieve records from database, set reorder to `true` to overwrite defined conditions
db.Order("name DESC") db.Order("name DESC", true) // reorder db.Order(gorm.SqlExpr("name = ? DESC", "first")) // sql expression
func (*DB) Pluck ¶
Pluck is used to query a single column into a slice of values
var ids []int64 db.Table("users").Pluck("id", &ids)
The 'values' parameter should be a pointer to a slice.
func (*DB) PluckFirst ¶
PluckFirst is used to query a single column and take the first value
var id int64 db.Table("users").PluckFirst("id", &id)
The 'values' parameter should be a pointer to a value.
func (*DB) Prepare ¶ added in v2.23.5
func (conn *DB) Prepare(query string) (*SQLStmtWrapper, error)
Prepare creates a prepared statement for later queries or executions. As the method must be executed in a transaction, the returned statement is bound to the transaction.
func (*DB) QueryExpr ¶
func (conn *DB) QueryExpr() interface{}
QueryExpr returns the query as expr object.
func (*DB) Raw ¶
Raw uses raw sql as conditions
db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)
func (*DB) RowsAffected ¶
RowsAffected returns the number of rows affected by the last INSERT/UPDATE/DELETE statement.
func (*DB) ScanAndHandleMaps ¶
ScanAndHandleMaps scans values into maps and calls the given handler for each row.
func (*DB) ScanIntoSliceOfMaps ¶
ScanIntoSliceOfMaps scans value into a slice of maps.
func (*DB) ScanIntoSlices ¶
ScanIntoSlices scans multiple columns into slices.
func (*DB) Select ¶
Select specifies fields that you want to retrieve from database when querying, by default, will select all fields; When creating/updating, specify fields that you want to save to database.
func (*DB) Set ¶
Set sets setting by name, which could be used in callbacks, will clone a new db, and update its setting.
func (*DB) SubQuery ¶
func (conn *DB) SubQuery() interface{}
SubQuery returns the query as sub query.
func (*DB) Take ¶
Take returns a record that match given conditions, the order will depend on the database implementation.
func (*DB) UpdateColumn ¶
UpdateColumn updates attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) UpdateColumns ¶ added in v2.23.5
UpdateColumns is a synonym for UpdateColumn.
func (*DB) Where ¶
Where returns a new relation, filters records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
func (*DB) WhereGroupHasPermissionOnItems ¶
func (conn *DB) WhereGroupHasPermissionOnItems(groupID int64, permissionKind, neededPermission string) *DB
WhereGroupHasPermissionOnItems returns a subview of the items on that the given group has `can_[permissionKind]_generated` >= `neededPermission` basing on the given view.
func (*DB) WhereGroupRelationIsActual ¶
WhereGroupRelationIsActual restricts `groups_groups.type` to values corresponding to actual group membership and forces the relation to be not expired.
func (*DB) WhereItemHasResultStartedByUser ¶ added in v2.21.4
WhereItemHasResultStartedByUser makes sure that the user have a started result on the item, whatever the attempt.
func (*DB) WhereItemsAreSelfOrDescendantsOf ¶
WhereItemsAreSelfOrDescendantsOf filters items who are self or descendant of a given item.
func (*DB) WhereItemsAreVisible ¶
WhereItemsAreVisible returns a subview of the visible items for the given group basing on the given view.
func (*DB) WhereItemsContentAreVisible ¶
WhereItemsContentAreVisible returns a subview of the content visible items for the given group.
func (*DB) WherePermissionIsAtLeast ¶
WherePermissionIsAtLeast returns a composable query filtered by `can_*_generated_value` >= indexOf(`permissionName`) depending on the given permission kind.
func (*DB) WhereSearchStringMatches ¶
WhereSearchStringMatches returns a composable query where {field} matches the search string {searchString} All the words in the search string are matched with "AND". If fallbackField is not empty, it is used as a fallback if the field is NULL.
func (*DB) WhereUserHasPermissionOnItems ¶
func (conn *DB) WhereUserHasPermissionOnItems(user *User, permissionKind, neededPermission string) *DB
WhereUserHasPermissionOnItems returns a subview of the items on that the given user has `can_view_generated` >= `viewPermission` basing on the given view.
func (*DB) WhereUserHasViewPermissionOnItems ¶
WhereUserHasViewPermissionOnItems returns a subview of the items on that the given user has `can_view_generated` >= `viewPermission` basing on the given view.
func (*DB) WhereUsersAreDescendantsOfGroup ¶
WhereUsersAreDescendantsOfGroup joins `groups_ancestors_active` on ancestor_group_id=groupID & child_group_id=users.group_id.
func (*DB) WithCustomWriteLocks ¶ added in v2.23.2
WithCustomWriteLocks converts "SELECT ..." statement into "SELECT ... FOR SHARE OF ... FOR UPDATE ..." statement. For existing rows, it will read the latest committed data for the listed tables (instead of the data from the repeatable-read snapshot) and acquire shared/exclusive locks on them, preventing other transactions from modifying them.
func (*DB) WithExclusiveWriteLock ¶ added in v2.23.2
WithExclusiveWriteLock converts "SELECT ..." statement into "SELECT ... FOR UPDATE" statement. For existing rows, it will read the latest committed data (instead of the data from the repeatable-read snapshot) and acquire an exclusive lock on them, preventing other transactions from modifying them and even from getting exclusive/shared locks on them. For non-existing rows, it works similarly to a shared lock (FOR SHARE).
func (*DB) WithPersonalInfoViewApprovals ¶
WithPersonalInfoViewApprovals returns a subview with information on if a user (in `users` table) approved viewing their personal info for the given manager (`groups_groups.personal_info_view_approved` is true for a group managed by the given manager). The approvals can be checked as `personal_info_view_approvals.approved`.
func (*DB) WithSharedWriteLock ¶ added in v2.23.2
WithSharedWriteLock converts "SELECT ..." statement into "SELECT ... FOR SHARE" statement. For existing rows, it will read the latest committed data (instead of the data from the repeatable-read snapshot) and acquire a shared lock on them, preventing other transactions from modifying them.
type DataStore ¶
type DataStore struct { *DB // contains filtered or unexported fields }
DataStore gather all stores for database operations on business data.
func NewDataStoreWithContext ¶
NewDataStoreWithContext returns a new DataStore with the given context.
func NewDataStoreWithTable ¶
NewDataStoreWithTable returns a specialized DataStore.
func (*DataStore) AccessTokens ¶
func (s *DataStore) AccessTokens() *AccessTokenStore
AccessTokens returns a AccessTokenStore.
func (*DataStore) ActiveGroupAncestors ¶
func (s *DataStore) ActiveGroupAncestors() *GroupAncestorStore
ActiveGroupAncestors returns a GroupAncestorStore working with the `groups_ancestors_active` view.
func (*DataStore) ActiveGroupGroups ¶
func (s *DataStore) ActiveGroupGroups() *GroupGroupStore
ActiveGroupGroups returns a GroupGroupStore working with the `groups_groups_active` view.
func (*DataStore) Answers ¶
func (s *DataStore) Answers() *AnswerStore
Answers returns a AnswerStore.
func (*DataStore) Attempts ¶
func (s *DataStore) Attempts() *AttemptStore
Attempts returns a AttemptStore.
func (*DataStore) CheckIfTeamParticipationsConflictWithExistingUserMemberships ¶
func (s *DataStore) CheckIfTeamParticipationsConflictWithExistingUserMemberships( teamID, userGroupID int64, withLock bool, ) (bool, error)
CheckIfTeamParticipationsConflictWithExistingUserMemberships returns true if the given team has at least one active participation conflicting with active participations of the given user's teams.
func (*DataStore) EnsureTransaction ¶ added in v2.24.0
func (s *DataStore) EnsureTransaction(txFunc func(*DataStore) error, txOptions ...*sql.TxOptions) error
EnsureTransaction executes the given function in a transaction and commits. If a transaction is already started, it will execute the function in the current transaction.
func (*DataStore) GetGroupJoiningByCodeInfoByCode ¶
func (s *DataStore) GetGroupJoiningByCodeInfoByCode(code string, withLock bool) (*GroupJoiningByCodeInfo, error)
GetGroupJoiningByCodeInfoByCode returns GroupJoiningByCodeInfo for a given code (or null if there is no public team with this code or the code has expired).
func (*DataStore) Gradings ¶
func (s *DataStore) Gradings() *GradingStore
Gradings returns a GradingStore.
func (*DataStore) GroupAncestors ¶
func (s *DataStore) GroupAncestors() *GroupAncestorStore
GroupAncestors returns a GroupAncestorStore.
func (*DataStore) GroupContestItems ¶
func (s *DataStore) GroupContestItems() *GroupContestItemStore
GroupContestItems returns a GroupContestItemStore.
func (*DataStore) GroupGroups ¶
func (s *DataStore) GroupGroups() *GroupGroupStore
GroupGroups returns a GroupGroupStore.
func (*DataStore) GroupManagers ¶
func (s *DataStore) GroupManagers() *GroupManagerStore
GroupManagers returns a GroupManagerStore.
func (*DataStore) GroupMembershipChanges ¶
func (s *DataStore) GroupMembershipChanges() *GroupMembershipChangeStore
GroupMembershipChanges returns a GroupMembershipChangeStore.
func (*DataStore) GroupPendingRequests ¶
func (s *DataStore) GroupPendingRequests() *GroupPendingRequestStore
GroupPendingRequests returns a GroupPendingRequestStore.
func (*DataStore) InTransaction ¶
InTransaction executes the given function in a transaction and commits. If a propagation is scheduled, it will be run after the transaction commit, so we can run each step of the propagation in a separate transaction.
For testing purposes, it is possible to force this method to retry the transaction once by providing a context created with ContextWithTransactionRetrying.
func (*DataStore) InsertMap ¶
InsertMap reads fields from the given map and inserts the values which have been set into the store's table.
func (*DataStore) InsertMaps ¶
InsertMaps reads fields from the given map and inserts the values set in the first row (so all the rows should have the same keys) into the store's table.
func (*DataStore) InsertOrUpdateMap ¶
InsertOrUpdateMap reads fields from the given map and inserts the values which have been set into the store's table (like InsertMap does). If it is a duplicate, the listed columns will be updated.
func (*DataStore) InsertOrUpdateMaps ¶
func (s *DataStore) InsertOrUpdateMaps(dataMap []map[string]interface{}, updateColumns []string) error
InsertOrUpdateMaps reads fields from the given maps and inserts the values set in the first row (so all the maps should have the same keys) into the store's table (like InsertMaps does). If it is a duplicate, the listed columns will be updated. If updateColumns is nil, all the columns in dataMaps will be updated.
func (*DataStore) IsInTransaction ¶
IsInTransaction returns true if the store operates in a DB transaction at the moment.
func (*DataStore) IsResultsPropagationProhibited ¶ added in v2.22.4
IsResultsPropagationProhibited returns true if the propagation of results is prohibited in the context of the current DB connection.
func (*DataStore) ItemAncestors ¶
func (s *DataStore) ItemAncestors() *ItemAncestorStore
ItemAncestors returns an ItemAncestorStore.
func (*DataStore) ItemDependencies ¶
func (s *DataStore) ItemDependencies() *ItemDependencyStore
ItemDependencies returns an ItemDependencyStore.
func (*DataStore) ItemItems ¶
func (s *DataStore) ItemItems() *ItemItemStore
ItemItems returns an ItemItemStore.
func (*DataStore) ItemStrings ¶
func (s *DataStore) ItemStrings() *ItemStringStore
ItemStrings returns an ItemStringStore.
func (*DataStore) Languages ¶
func (s *DataStore) Languages() *LanguageStore
Languages returns a LanguageStore.
func (*DataStore) MergeContext ¶ added in v2.22.4
MergeContext returns a new context based on the given one, with DB-related values copied from the context of the current DB connection.
func (*DataStore) NewID ¶
NewID generates a positive random int64 to be used as id !!! To be safe, the insertion should be retried if the id conflicts with an existing entry.
func (*DataStore) NewThreadStore ¶
func (s *DataStore) NewThreadStore(db *DB) *ThreadStore
NewThreadStore returns a new thread store.
func (*DataStore) Permissions ¶
func (s *DataStore) Permissions() *PermissionGeneratedStore
Permissions returns a PermissionGeneratedStore.
func (*DataStore) PermissionsGranted ¶
func (s *DataStore) PermissionsGranted() *PermissionGrantedStore
PermissionsGranted returns a PermissionGrantedStore.
func (*DataStore) Platforms ¶
func (s *DataStore) Platforms() *PlatformStore
Platforms returns a PlatformStore.
func (*DataStore) Results ¶
func (s *DataStore) Results() *ResultStore
Results returns a ResultStore.
func (*DataStore) RetryOnDuplicateKeyError ¶
func (s *DataStore) RetryOnDuplicateKeyError(keyName, nameInError string, f func(store *DataStore) error) error
RetryOnDuplicateKeyError will retry the given function on getting duplicate entry errors for the given key.
func (*DataStore) RetryOnDuplicatePrimaryKeyError ¶
RetryOnDuplicatePrimaryKeyError will retry the given function on getting duplicate entry errors for primary keys.
func (*DataStore) SchedulePermissionsPropagation ¶
func (s *DataStore) SchedulePermissionsPropagation()
SchedulePermissionsPropagation schedules a run of the groups ancestors propagation after the transaction commit.
func (*DataStore) ScheduleResultsPropagation ¶
func (s *DataStore) ScheduleResultsPropagation()
ScheduleResultsPropagation schedules a run of ResultStore::processResultsRecomputeForItemsAndPropagate() after the transaction commit.
func (*DataStore) Sessions ¶
func (s *DataStore) Sessions() *SessionStore
Sessions returns a SessionStore.
func (*DataStore) SetPropagationsModeToSync ¶ added in v2.24.0
SetPropagationsModeToSync sets the mode of propagations to synchronous. In this mode, the propagation of permissions and results will be done synchronously before the transaction commit.
func (*DataStore) Threads ¶
func (s *DataStore) Threads() *ThreadStore
Threads returns a ThreadStore.
func (*DataStore) UserBatchPrefixes ¶
func (s *DataStore) UserBatchPrefixes() *UserBatchPrefixStore
UserBatchPrefixes returns a UserBatchPrefixStore.
func (*DataStore) UserBatches ¶
func (s *DataStore) UserBatches() *UserBatchStore
UserBatches returns a UserBatchStore.
func (*DataStore) WithCustomWriteLocks ¶ added in v2.23.2
WithCustomWriteLocks converts "SELECT ..." statement into "SELECT ... FOR SHARE OF ... FOR UPDATE ..." statement. For existing rows, it will read the latest committed data for the listed tables (instead of the data from the repeatable-read snapshot) and acquire shared/exclusive locks on them, preventing other transactions from modifying them.
func (*DataStore) WithExclusiveWriteLock ¶ added in v2.23.2
WithExclusiveWriteLock converts "SELECT ..." statement into "SELECT ... FOR UPDATE" statement. For existing rows, it will read the latest committed data (instead of the data from the repeatable-read snapshot) and acquire an exclusive lock on them, preventing other transactions from modifying them and even from getting exclusive/shared locks on them. For non-existing rows, it works similarly to a shared lock (FOR SHARE).
func (*DataStore) WithForeignKeyChecksDisabled ¶
func (s *DataStore) WithForeignKeyChecksDisabled(blockFunc func(*DataStore) error, txOptions ...*sql.TxOptions) error
WithForeignKeyChecksDisabled executes the given function with foreign keys checking disabled (wraps it up in a transaction if no transaction started).
func (*DataStore) WithNamedLock ¶
func (s *DataStore) WithNamedLock(lockName string, timeout time.Duration, funcToCall func(*DataStore) error) error
WithNamedLock wraps the given function in GET_LOCK/RELEASE_LOCK.
func (*DataStore) WithSharedWriteLock ¶ added in v2.23.2
WithSharedWriteLock converts "SELECT ..." statement into "SELECT ... FOR SHARE" statement. For existing rows, it will read the latest committed data (instead of the data from the repeatable-read snapshot) and acquire a shared lock on them, preventing other transactions from modifying them.
type GradingStore ¶
type GradingStore struct {
*DataStore
}
GradingStore implements database operations on `gradings`.
type GroupAncestorStore ¶
type GroupAncestorStore struct {
*DataStore
}
GroupAncestorStore implements database operations on `groups_ancestors` (which is a precomputed cache over groups_groups).
func (*GroupAncestorStore) ManagedByGroup ¶
func (s *GroupAncestorStore) ManagedByGroup(groupID int64) *DB
ManagedByGroup returns a composable query for getting all the groups_ancestors rows linking manager groups (as ancestor_group_id) to managed groups (as child_group_id) where the manager groups are ancestors of the given group. Basically the groups_ancestors.child_group_id are the groups the given group can manage.
The result may contain duplicated `groups_ancestors.ancestor_group_id`-`groups_ancestors.child_group_id` pairs since there can be different paths to a managed group through the `group_managers` table and the group ancestry graph.
func (*GroupAncestorStore) ManagedByUser ¶
func (s *GroupAncestorStore) ManagedByUser(user *User) *DB
ManagedByUser returns a composable query for getting all the groups_ancestors rows linking manager groups (as ancestor_group_id) to managed groups (as child_group_id) where the manager groups are ancestors of the given user. Basically the groups_ancestors.child_group_id are the groups the user can manage.
The result may contain duplicated `groups_ancestors.ancestor_group_id`-`groups_ancestors.child_group_id` pairs since there can be different paths to a managed group through the `group_managers` table and the group ancestry graph.
type GroupApprovals ¶
type GroupApprovals struct { PersonalInfoViewApproval bool LockMembershipApproval bool WatchApproval bool }
GroupApprovals represents all the approvals that can be given by a user to the group managers.
func (*GroupApprovals) FromString ¶
func (approvals *GroupApprovals) FromString(s string)
FromString initializes GroupApprovals from the given comma-separated list of approvals.
func (*GroupApprovals) ToArray ¶
func (approvals *GroupApprovals) ToArray() []string
ToArray converts GroupApprovals to a list of approvals.
type GroupContestItemStore ¶
type GroupContestItemStore struct {
*DataStore
}
GroupContestItemStore implements database operations on `groups_contest_items`.
type GroupGroupStore ¶
type GroupGroupStore struct {
*DataStore
}
GroupGroupStore implements database operations on `groups_groups` (which stores parent-child relationships between groups).
func (*GroupGroupStore) CreateNewAncestors ¶ added in v2.23.0
func (s *GroupGroupStore) CreateNewAncestors() (err error)
CreateNewAncestors creates ancestors for groups marked as 'todo' in `groups_propagate`.
func (*GroupGroupStore) CreateRelation ¶
func (s *GroupGroupStore) CreateRelation(parentGroupID, childGroupID int64) (err error)
CreateRelation creates a direct relation between two groups. On success, it creates new groups ancestors and schedules permissions propagation.
func (*GroupGroupStore) CreateRelationsWithoutChecking ¶
func (s *GroupGroupStore) CreateRelationsWithoutChecking(relations []map[string]interface{}) (err error)
CreateRelationsWithoutChecking creates multiple direct relations at once without checking for possible cycles in the graph and without deletion of old relations. This method is only suitable to create relations with new groups. Callers must check that parent groups are not users.
func (*GroupGroupStore) DeleteRelation ¶
func (s *GroupGroupStore) DeleteRelation(parentGroupID, childGroupID int64, shouldDeleteOrphans bool) (err error)
DeleteRelation deletes a relation between two groups. It can also delete orphaned groups.
func (*GroupGroupStore) TeamGroupForTeamItemAndUser ¶ added in v2.23.4
func (s *GroupGroupStore) TeamGroupForTeamItemAndUser(itemID int64, user *User) *DB
TeamGroupForTeamItemAndUser returns a composable query for getting a team
(as groups_groups_active.parent_group_id) that 1. the given user is a member of 2. has an unexpired attempt with root_item_id = `itemID`.
If more than one team is found (which should be impossible), the one with the smallest `groups.id` is returned.
func (*GroupGroupStore) Transition ¶
func (s *GroupGroupStore) Transition(action GroupGroupTransitionAction, parentGroupID int64, childGroupIDs []int64, approvals map[int64]GroupApprovals, performedByUserID int64, ) (results GroupGroupTransitionResults, approvalsToRequest map[int64]GroupApprovals, err error)
Transition performs a groups_groups relation transition according to groupGroupTransitionRules.
func (*GroupGroupStore) WhereUserIsMember ¶
func (s *GroupGroupStore) WhereUserIsMember(user *User) *DB
WhereUserIsMember returns a composable query of direct ancestors (parents) of user's self group, i.e. groups of which he is a direct member.
type GroupGroupTransitionAction ¶
type GroupGroupTransitionAction int
GroupGroupTransitionAction represents a groups_groups relation transition action.
const ( // AdminCreatesInvitation means a group admin invites new users to the group. AdminCreatesInvitation GroupGroupTransitionAction = iota // UserCreatesJoinRequest means a user creates a request to become a group member. UserCreatesJoinRequest // UserCreatesAcceptedJoinRequest means a user adds himself into a group that he owns // It doesn't check if the user owns the group / all needed approvals are given (a calling service should check that). UserCreatesAcceptedJoinRequest // UserAcceptsInvitation means a user accepts a group invitation. UserAcceptsInvitation // AdminAcceptsJoinRequest means a group admin accepts a request to join a group. // For this action we check that all the approvals required by the group are given in the join request // and set groups_groups.*_approved_at to group_pending_requests.at for each. AdminAcceptsJoinRequest // AdminAcceptsLeaveRequest means a group admin accepts a request to leave a group. AdminAcceptsLeaveRequest // AdminRefusesLeaveRequest means a group admin refuses a request to leave a group. AdminRefusesLeaveRequest // UserRefusesInvitation means a user refuses a group invitation. UserRefusesInvitation // AdminRefusesJoinRequest means a group admin refuses a request to join the group. AdminRefusesJoinRequest // AdminRemovesUser means a group admin removes a user from a group. It marks relations as "removed". // It doesn't check if a child is a user or not. AdminRemovesUser // AdminWithdrawsInvitation means a group admin withdraws an invitation. AdminWithdrawsInvitation // UserLeavesGroup means a user leaves a group. UserLeavesGroup // UserCreatesLeaveRequest means a user creates a request to leave a group // We don't check that groups.require_lock_membership_approval_until & groups_groups.lock_membership_approved_at // are not null (a calling service should check that by itself). UserCreatesLeaveRequest // UserCancelsJoinRequest means a user cancels his request to join a group. UserCancelsJoinRequest // UserCancelsLeaveRequest means a user cancels his request to leave a group. UserCancelsLeaveRequest // AdminRemovesDirectRelation removes a direct relation. AdminRemovesDirectRelation // UserJoinsGroupByBadge means we add a user into a group because of his badge returned by the login module. UserJoinsGroupByBadge // UserJoinsGroupByCode means a user joins a group using a group's code // We don't check the code here (a calling service should check the code by itself). UserJoinsGroupByCode // AdminStrengthensApprovalWithEmpty means an admin strengthens the approval requirements for a group and empties it. AdminStrengthensApprovalWithEmpty // AdminStrengthensApprovalWithReinvite means an admin strengthens the approval requirements for a group, // empties it and re-invites all the users. AdminStrengthensApprovalWithReinvite )
type GroupGroupTransitionResult ¶
type GroupGroupTransitionResult string
GroupGroupTransitionResult is an enum{cycle, invalid, success, unchanged}.
const ( // Cycle means that the transition wasn't performed because it would create a cycle in groups_groups graph. Cycle GroupGroupTransitionResult = "cycle" // Invalid means that the transition is impossible. Invalid GroupGroupTransitionResult = "invalid" // ApprovalsMissing means that one or more approvals required by the transition are missing. ApprovalsMissing GroupGroupTransitionResult = "approvals_missing" // Full means that the parent group is full (in terms of `groups.max_participants`) when `enforce_max_participants` is true // (The number of participants is computed as the number of non-expired users or teams which are direct children // of the group + invitations (join requests are not counted)). Full GroupGroupTransitionResult = "full" // Success means that the transition was performed successfully. Success GroupGroupTransitionResult = "success" // Unchanged means that the transition has been already performed. Unchanged GroupGroupTransitionResult = "unchanged" )
type GroupGroupTransitionResults ¶
type GroupGroupTransitionResults map[int64]GroupGroupTransitionResult
GroupGroupTransitionResults represents results of mass transition (format: map{ id -> GroupGroupTransitionResult }).
type GroupJoiningByCodeInfo ¶
type GroupJoiningByCodeInfo struct { GroupID int64 Type string CodeExpiresAtIsNull bool CodeLifetimeIsNull bool FrozenMembership bool }
GroupJoiningByCodeInfo represents info related to ability to join a team by code.
type GroupManagerStore ¶
type GroupManagerStore struct {
*DataStore
}
GroupManagerStore implements database operations on `group_managers` (which stores group managers and their permissions).
func (*GroupManagerStore) CanManageIndexByName ¶
func (s *GroupManagerStore) CanManageIndexByName(name string) int
CanManageIndexByName returns the index of the given group manager permission from the `can_manage` enum.
func (*GroupManagerStore) CanManageNameByIndex ¶
func (s *GroupManagerStore) CanManageNameByIndex(index int) string
CanManageNameByIndex returns the name of the given group manager permission from the `can_manage` enum.
type GroupMembershipAction ¶
type GroupMembershipAction string
GroupMembershipAction represents an action that changes relation between two groups.
const ( // InvitationCreated means a pending group admin's invitation for user to join a group was created. InvitationCreated GroupMembershipAction = "invitation_created" // JoinRequestCreated means a pending user's request to join a group was created. JoinRequestCreated GroupMembershipAction = "join_request_created" // InvitationAccepted means a user became a member of a group by accepting an invitation. InvitationAccepted GroupMembershipAction = "invitation_accepted" // JoinRequestAccepted means a user became a member of a group since a group admin accepted his request. JoinRequestAccepted GroupMembershipAction = "join_request_accepted" // LeaveRequestAccepted means a user left a group since a group admin accepted his leave request. LeaveRequestAccepted GroupMembershipAction = "leave_request_accepted" // InvitationRefused means a user refused an invitation to join a group. InvitationRefused GroupMembershipAction = "invitation_refused" // InvitationWithdrawn means an admin withdrew his invitation to join a group. InvitationWithdrawn GroupMembershipAction = "invitation_withdrawn" // JoinedByBadge means a user has been added into a group because of a badge returned by the login module. JoinedByBadge GroupMembershipAction = "joined_by_badge" // JoinedByCode means a user joined a group by the group's code. JoinedByCode GroupMembershipAction = "joined_by_code" // JoinRequestRefused means an admin refused a user's request to join a group. JoinRequestRefused GroupMembershipAction = "join_request_refused" // JoinRequestWithdrawn means a user withdrew his request to join a group. JoinRequestWithdrawn GroupMembershipAction = "join_request_withdrawn" // Removed means a user was removed from a group. Removed GroupMembershipAction = "removed" // Left means a user left a group. Left GroupMembershipAction = "left" // IsMember means a user is a member of a group. IsMember GroupMembershipAction = "is_member" // LeaveRequestCreated means a pending user's request to leave a group was created. LeaveRequestCreated GroupMembershipAction = "is_member,leave_request_created" // LeaveRequestExpired means a pending user's leave request for an expired membership. LeaveRequestExpired GroupMembershipAction = "leave_request_created" // LeaveRequestRefused means a manager refused a user's request to leave a group. LeaveRequestRefused GroupMembershipAction = "leave_request_refused" // LeaveRequestWithdrawn means a user withdrew his request to leave a group. LeaveRequestWithdrawn GroupMembershipAction = "leave_request_withdrawn" // RemovedDueToApprovalChange means a user has been removed from a group because of approval changes. RemovedDueToApprovalChange GroupMembershipAction = "removed_due_to_approval_change" // NoRelation means there is no row for the group pair in the groups_groups/group_pending_requests tables. NoRelation GroupMembershipAction = "" )
func (GroupMembershipAction) PendingType ¶
func (groupMembershipAction GroupMembershipAction) PendingType() string
PendingType converts the GroupMembershipAction into `group_pending_requests.type`.
type GroupMembershipChangeStore ¶
type GroupMembershipChangeStore struct {
*DataStore
}
GroupMembershipChangeStore implements database operations on `group_membership_changes` (which stores the history of group membership changes).
type GroupPendingRequestStore ¶
type GroupPendingRequestStore struct {
*DataStore
}
GroupPendingRequestStore implements database operations on `group_pending_requests` (which stores requests that require an action from a user).
type GroupStore ¶
type GroupStore struct {
*DataStore
}
GroupStore implements database operations on groups.
func (*GroupStore) AncestorsOfJoinedGroups ¶
func (s *GroupStore) AncestorsOfJoinedGroups(store *DataStore, user *User) *DB
AncestorsOfJoinedGroups returns a query selecting all group ancestors ids of a user.
func (*GroupStore) AncestorsOfJoinedGroupsForGroup ¶
func (s *GroupStore) AncestorsOfJoinedGroupsForGroup(store *DataStore, groupID int64) *DB
AncestorsOfJoinedGroupsForGroup returns a query selecting all group ancestors ids of a group.
func (*GroupStore) AvailableGroupsBySearchString ¶ added in v2.21.4
func (s *GroupStore) AvailableGroupsBySearchString(user *User, searchString string) *DB
AvailableGroupsBySearchString returns a query for searching for available groups of a user.
func (*GroupStore) CheckIfEntryConditionsStillSatisfiedForAllActiveParticipations ¶
func (s *GroupStore) CheckIfEntryConditionsStillSatisfiedForAllActiveParticipations( teamGroupID, userID int64, isAdding, withLock bool, ) (bool, error)
CheckIfEntryConditionsStillSatisfiedForAllActiveParticipations checks whether adding/removal of a user specified by userID would keep entry conditions satisfied for all active participations of teamGroupID. If at least one entry condition becomes broken for at least one active participation, the method returns false. An active participation is one that is started (`results.started_at` is not null for the `root_item_id`), still allows submissions and is not ended. Entry conditions are defined by items.entry_min_admitted_members_ratio & items.entry_max_team_size (for more info see description of the itemGetEntryState service). The isAdding parameter specifies if we are going to add or remove a user.
func (*GroupStore) CreateNew ¶
func (s *GroupStore) CreateNew(name, groupType string) (groupID int64, err error)
CreateNew creates a new group with given name and type.
func (*GroupStore) DeleteGroup ¶
func (s *GroupStore) DeleteGroup(groupID int64) (err error)
DeleteGroup deletes a group and emerging orphaned groups.
func (*GroupStore) GenerateQueryCheckingIfActionBreaksEntryConditionsForActiveParticipations ¶
func (s *GroupStore) GenerateQueryCheckingIfActionBreaksEntryConditionsForActiveParticipations( teamGroupIDExpr *gorm.SqlExpr, userID int64, isAdding, withLock bool, ) *DB
GenerateQueryCheckingIfActionBreaksEntryConditionsForActiveParticipations generates an SQL query checking whether adding/removal of a user specified by userID would break any of entry conditions for any of active participations of teamGroupID. If at least one entry condition becomes broken for at least one active participation, the query returns a row with 1. An active participation is one that is started (`results.started_at` is not null for the `root_item_id`), still allows submissions and is not ended. Entry conditions are defined by items.entry_min_admitted_members_ratio & items.entry_max_team_size (for more info see description of the itemGetEntryState service). The isAdding parameter specifies if we are going to add or remove a user.
func (*GroupStore) GetDirectParticipantIDsOf ¶
func (s *GroupStore) GetDirectParticipantIDsOf(groupID int64) (participantIDs []int64)
GetDirectParticipantIDsOf returns the participant IDs of the direct participants of a group.
func (*GroupStore) HasParticipants ¶
func (s *GroupStore) HasParticipants(groupID int64) (hasParticipants bool, err error)
HasParticipants checks whether a group has participants. Must be called inside a transaction.
func (*GroupStore) IsVisibleFor ¶
func (s *GroupStore) IsVisibleFor(groupID int64, user *User) bool
IsVisibleFor checks whether a group is visible to a user.
func (*GroupStore) IsVisibleForGroup ¶
func (s *GroupStore) IsVisibleForGroup(groupID, visibleForGroupID int64) bool
IsVisibleForGroup checks whether a group is visible to a group.
func (*GroupStore) ManagedBy ¶
func (s *GroupStore) ManagedBy(user *User) *DB
ManagedBy returns a composable query for getting all the groups the user can manage.
The `groups` in the result may be duplicated since there can be different paths to a managed group through the `group_managers` table and the group ancestry graph.
func (*GroupStore) ManagedUsersAndAncestorsOfManagedGroupsForGroup ¶
func (s *GroupStore) ManagedUsersAndAncestorsOfManagedGroupsForGroup(store *DataStore, groupID int64) *DB
ManagedUsersAndAncestorsOfManagedGroupsForGroup returns all groups which are ancestors of managed groups, and all users who are descendants from managed groups, for a group.
func (*GroupStore) PickVisibleGroups ¶
func (s *GroupStore) PickVisibleGroups(db *DB, user *User) *DB
PickVisibleGroups returns a query filtering only group which are visible for a user.
func (*GroupStore) PickVisibleGroupsForGroup ¶
func (s *GroupStore) PickVisibleGroupsForGroup(db *DB, visibleForGroupID int64) *DB
PickVisibleGroupsForGroup returns a query filtering only group which are visible for a group.
func (*GroupStore) PossibleSubgroupsBySearchString ¶ added in v2.21.4
func (s *GroupStore) PossibleSubgroupsBySearchString(user *User, searchString string) *DB
PossibleSubgroupsBySearchString returns a query for searching for possible subgroups of a user.
func (*GroupStore) StoreBadges ¶
func (s *GroupStore) StoreBadges(badges []Badge, userID int64, newUser bool) (err error)
StoreBadges stores badges into the DB. It also creates groups for badge group paths and makes the given user a manager or member of badge groups if needed.
For each badge:
- if the badge's group exists and the user is already a member (or a manager if badge.Manager is true) of it: does nothing;
- if the badge's group exists and the user is not already member (or a manager if badge.Manager is true) of it: makes him a member (or a manager) of the group;
- if the badge's group does not exist, creates a group with badge.BadgeInfo.Name as its name and type "Other" and adds it into the group identified by an url of the last element from badge.BadgeInfo.GroupPath. If this latter group does not exist, creates it (with the given name, and current user managership if `manager`=true) and puts it into the previous group from badge.BadgeInfo.GroupPath, etc.
- for every existing badge group or badge.BadgeInfo.GroupPath group makes the user a manager of the group (if he is not a manager yet).
func (*GroupStore) TeamGroupForUser ¶
func (s *GroupStore) TeamGroupForUser(teamGroupID int64, user *User) *DB
TeamGroupForUser returns a composable query for getting team group of the given user with given id.
type ItemAccessDetails ¶
type ItemAccessDetails struct { // MAX(permissions_generated.can_view_generated_value) converted back into the string representation CanView string `json:"can_view"` }
ItemAccessDetails represents access rights for an item.
func (*ItemAccessDetails) IsForbidden ¶
func (accessDetails *ItemAccessDetails) IsForbidden() bool
IsForbidden returns true when can_view_generated = 'none'.
func (*ItemAccessDetails) IsInfo ¶
func (accessDetails *ItemAccessDetails) IsInfo() bool
IsInfo returns true when can_view_generated = 'info'.
type ItemAccessDetailsWithID ¶
type ItemAccessDetailsWithID struct { ItemID int64 ItemAccessDetails }
ItemAccessDetailsWithID represents access rights for an item + ItemID.
type ItemAncestorStore ¶
type ItemAncestorStore struct {
*DataStore
}
ItemAncestorStore implements database operations on `items_ancestors`.
func (*ItemAncestorStore) DescendantsOf ¶
func (s *ItemAncestorStore) DescendantsOf(ancestorID int64) *ItemItemStore
DescendantsOf returns a composable query for getting descendants of the given item.
type ItemDependencyStore ¶
type ItemDependencyStore struct {
*DataStore
}
ItemDependencyStore implements database operations on `item_dependencies`.
type ItemItemStore ¶
type ItemItemStore struct {
*DataStore
}
ItemItemStore implements database operations on `items_items`.
func (*ItemItemStore) ChildrenOf ¶
func (s *ItemItemStore) ChildrenOf(parentID int64) *ItemItemStore
ChildrenOf returns a composable query for selecting children of the given item.
func (*ItemItemStore) ContentViewPropagationIndexByName ¶
func (s *ItemItemStore) ContentViewPropagationIndexByName(name string) int
ContentViewPropagationIndexByName returns the index of the given content view propagation level in the enum.
func (*ItemItemStore) ContentViewPropagationNameByIndex ¶
func (s *ItemItemStore) ContentViewPropagationNameByIndex(index int) string
ContentViewPropagationNameByIndex returns the content view propagation level name with the given index from the enum.
func (*ItemItemStore) CreateNewAncestors ¶ added in v2.23.0
func (s *ItemItemStore) CreateNewAncestors() (err error)
CreateNewAncestors populates items_ancestors table.
func (*ItemItemStore) UpperViewLevelsPropagationIndexByName ¶
func (s *ItemItemStore) UpperViewLevelsPropagationIndexByName(name string) int
UpperViewLevelsPropagationIndexByName returns the index of the given upper-level view propagation kind in the enum.
func (*ItemItemStore) UpperViewLevelsPropagationNameByIndex ¶
func (s *ItemItemStore) UpperViewLevelsPropagationNameByIndex(index int) string
UpperViewLevelsPropagationNameByIndex returns the upper-level view propagation kind name with the given index from the enum.
func (*ItemItemStore) WithItemsRelationsLock ¶
func (s *ItemItemStore) WithItemsRelationsLock(txFunc func(*DataStore) error) error
WithItemsRelationsLock wraps the given function in GET_LOCK/RELEASE_LOCK specific for modifying relations between items.
type ItemStore ¶
type ItemStore struct {
*DataStore
}
ItemStore implements database operations on items.
func (*ItemStore) BreadcrumbsHierarchyForAttempt ¶
func (s *ItemStore) BreadcrumbsHierarchyForAttempt(ids []int64, groupID, attemptID int64, withWriteLock bool) ( attemptIDMap map[int64]int64, attemptNumberMap map[int64]int, err error, )
BreadcrumbsHierarchyForAttempt returns attempts ids and 'order' (for items allowing multiple attempts) for the given list of item ids if it is a valid participation hierarchy for the given `attemptID` which means all the following statements are true:
- the first item in `ids` is an activity/skill item (groups.root_activity_id/root_skill_id) of a group the `groupID` is a descendant of or manages,
- `ids` is an ordered list of parent-child items,
- the `groupID` group has at least 'content' access on each of the items in `ids` except for the last one and at least 'info' access on the last one,
- the `groupID` group has a started result for each item, with `attemptID` (or its parent attempt each time we reach a root of an attempt) as the attempt.
func (*ItemStore) BreadcrumbsHierarchyForParentAttempt ¶
func (s *ItemStore) BreadcrumbsHierarchyForParentAttempt(ids []int64, groupID, parentAttemptID int64, withWriteLock bool) ( attemptIDMap map[int64]int64, attemptNumberMap map[int64]int, err error, )
BreadcrumbsHierarchyForParentAttempt returns attempts ids and 'order' (for items allowing multiple attempts) for the given list of item ids (but the last item) if it is a valid participation hierarchy for the given `parentAttemptID` which means all the following statements are true:
- the first item in `ids` is a root activity/skill (groups.root_activity_id/root_skill_id) of a group the `groupID` is a descendant of or manages,
- `ids` is an ordered list of parent-child items,
- the `groupID` group has at least 'content' access on each of the items in `ids` except for the last one and at least 'info' access on the last one,
- the `groupID` group has a started result for each item but the last, with `parentAttemptID` (or its parent attempt each time we reach a root of an attempt) as the attempt,
- if `ids` consists of only one item, the `parentAttemptID` is zero.
func (*ItemStore) CheckSubmissionRights ¶
func (s *ItemStore) CheckSubmissionRights(participantID, itemID int64) (hasAccess bool, reason, err error)
CheckSubmissionRights checks if the participant group can submit an answer for the given item (task), i.e. the item (task) exists and is not read-only and the participant has at least content:view permission on the item.
func (*ItemStore) ContestManagedByUser ¶
ContestManagedByUser returns a composable query for getting a contest with the given item id managed by the given user.
func (*ItemStore) DeleteItem ¶
DeleteItem deletes an item. Note the method fails if the item has children.
func (*ItemStore) GetAncestorsRequestHelpPropagatedQuery ¶
GetAncestorsRequestHelpPropagatedQuery gets all ancestors of an itemID while request_help_propagation = 1.
func (*ItemStore) GetItemIDFromTextID ¶
GetItemIDFromTextID gets the item_id from the text_id of an item.
func (*ItemStore) GetSearchQuery ¶
GetSearchQuery returns a query for searching items by title. It returns only items visible for the given user, which matches the given types.
func (*ItemStore) GroupHasPermissionOnItem ¶
func (s *ItemStore) GroupHasPermissionOnItem(groupID, itemID int64, permissionKind, neededPermission string) bool
GroupHasPermissionOnItem checks if a group has a certain permission on an item.
func (*ItemStore) HasCanRequestHelpTo ¶
HasCanRequestHelpTo checks whether there is a can_request_help_to permission on an item-group. The checks are made on item's ancestor while can_request_help_propagation=1, and on group's ancestors.
func (*ItemStore) IsValidParticipationHierarchyForParentAttempt ¶
func (s *ItemStore) IsValidParticipationHierarchyForParentAttempt( ids []int64, groupID, parentAttemptID int64, requireContentAccessToTheLastItem, withWriteLock bool, ) (bool, error)
IsValidParticipationHierarchyForParentAttempt checks if the given list of item ids is a valid participation hierarchy for the given `parentAttemptID` which means all the following statements are true:
- the first item in `ids` is a root activity/skill (groups.root_activity_id/root_skill_id) of a group the `groupID` is a descendant of or manages,
- `ids` is an ordered list of parent-child items,
- the `groupID` group has at least 'content' access on each of the items in `ids`,
- the `groupID` group has a started, allowing submission, not ended result for each item but the last, with `parentAttemptID` (or its parent attempt each time we reach a root of an attempt) as the attempt,
- if `ids` consists of only one item, the `parentAttemptID` is zero.
func (*ItemStore) VisibleByID ¶
VisibleByID returns a view of the visible item identified by itemID, for the given participant.
type ItemStringStore ¶
type ItemStringStore struct {
*DataStore
}
ItemStringStore implements database operations on `items_strings`.
type LanguageStore ¶
type LanguageStore struct {
*DataStore
}
LanguageStore implements database operations on languages.
func (*LanguageStore) ByTag ¶
func (s *LanguageStore) ByTag(tag string) *DB
ByTag returns a composable query for filtering by _table_.tag.
type MostRecentToken ¶
MostRecentToken represents the most recent token for a session.
type ParentChild ¶
ParentChild represents a (ParentID, ChildID) pair.
type PermissionGeneratedStore ¶
type PermissionGeneratedStore struct {
*DataStore
}
PermissionGeneratedStore implements database operations on `permissions_generated`.
func (*PermissionGeneratedStore) AggregatedPermissionsForItems ¶
func (s *PermissionGeneratedStore) AggregatedPermissionsForItems(groupID int64) *DB
AggregatedPermissionsForItems returns a composable query for getting access rights of the given group (as *_generated_value) and item ids (as item_id) for all items.
func (*PermissionGeneratedStore) AggregatedPermissionsForItemsOnWhichGroupHasPermission ¶
func (s *PermissionGeneratedStore) AggregatedPermissionsForItemsOnWhichGroupHasPermission( groupID int64, permissionKind, neededPermission string, ) *DB
AggregatedPermissionsForItemsOnWhichGroupHasPermission returns a composable query for getting access rights (as *_generated_value) and item ids (as item_id) for all the items on that the given group has 'permissionKind' >= `neededPermission`.
func (*PermissionGeneratedStore) AggregatedPermissionsForItemsOnWhichGroupHasViewPermission ¶
func (s *PermissionGeneratedStore) AggregatedPermissionsForItemsOnWhichGroupHasViewPermission(groupID int64, viewPermission string) *DB
AggregatedPermissionsForItemsOnWhichGroupHasViewPermission returns a composable query for getting access rights (as can_view_generated_value) and item ids (as item_id) for all the items on that the given group has `can_view_generated` >= `viewPermission`.
func (*PermissionGeneratedStore) AggregatedPermissionsForItemsVisibleToGroup ¶
func (s *PermissionGeneratedStore) AggregatedPermissionsForItemsVisibleToGroup(groupID int64) *DB
AggregatedPermissionsForItemsVisibleToGroup returns a composable query for getting access rights (as can_view_generated_value) and item ids (as item_id) for all the items that are visible to the given group.
func (*PermissionGeneratedStore) MatchingGroupAncestors ¶
func (s *PermissionGeneratedStore) MatchingGroupAncestors(groupID int64) *DB
MatchingGroupAncestors returns a composable query of generated permissions matching groups of which the given group is descendant.
func (*PermissionGeneratedStore) MatchingUserAncestors ¶
func (s *PermissionGeneratedStore) MatchingUserAncestors(user *User) *DB
MatchingUserAncestors returns a composable query of generated permissions matching groups of which the user is descendant.
type PermissionGrantedStore ¶
type PermissionGrantedStore struct {
*DataStore
}
PermissionGrantedStore implements database operations on `permissions_granted`.
func (*PermissionGrantedStore) EditIndexByName ¶
func (s *PermissionGrantedStore) EditIndexByName(name string) int
EditIndexByName returns the index of the given "edit" permission name in the 'can_edit' enum.
func (*PermissionGrantedStore) EditNameByIndex ¶
func (s *PermissionGrantedStore) EditNameByIndex(index int) string
EditNameByIndex returns the 'edit' permission name with the given index from 'can_edit' enum.
func (*PermissionGrantedStore) GrantViewIndexByName ¶
func (s *PermissionGrantedStore) GrantViewIndexByName(name string) int
GrantViewIndexByName returns the index of the given "grant view" permission name in the 'can_grant_view' enum.
func (*PermissionGrantedStore) GrantViewNameByIndex ¶
func (s *PermissionGrantedStore) GrantViewNameByIndex(index int) string
GrantViewNameByIndex returns the 'grant view' permission name with the given index from 'can_grant_view' enum.
func (*PermissionGrantedStore) PermissionIndexByKindAndName ¶
func (s *PermissionGrantedStore) PermissionIndexByKindAndName(kind, name string) int
PermissionIndexByKindAndName returns the index of the given permission in the enum.
func (*PermissionGrantedStore) PermissionIsAtLeastSQLExpr ¶
func (s *PermissionGrantedStore) PermissionIsAtLeastSQLExpr(permissionKind, permissionName string) *gorm.SqlExpr
PermissionIsAtLeastSQLExpr returns a gorm.SqlExpr for filtering by `can_*_generated_value` >= indexOf(`permissionName`) depending on the given permission kind.
func (*PermissionGrantedStore) PermissionNameByKindAndIndex ¶
func (s *PermissionGrantedStore) PermissionNameByKindAndIndex(kind string, index int) string
PermissionNameByKindAndIndex returns the permission name of the given kind with the given index from the enum.
func (*PermissionGrantedStore) ViewIndexByName ¶
func (s *PermissionGrantedStore) ViewIndexByName(name string) int
ViewIndexByName returns the index of the given view kind in the 'can_view' enum.
func (*PermissionGrantedStore) ViewNameByIndex ¶
func (s *PermissionGrantedStore) ViewNameByIndex(index int) string
ViewNameByIndex returns the view permission name with the given index from the 'can_view' enum.
func (*PermissionGrantedStore) WatchIndexByName ¶
func (s *PermissionGrantedStore) WatchIndexByName(name string) int
WatchIndexByName returns the index of the given "watch" permission name in the 'can_watch' enum.
func (*PermissionGrantedStore) WatchNameByIndex ¶
func (s *PermissionGrantedStore) WatchNameByIndex(index int) string
WatchNameByIndex returns the 'watch' permission name with the given index from 'can_watch' enum.
type PlatformStore ¶
type PlatformStore struct {
*DataStore
}
PlatformStore implements database operations on `platforms`.
func (PlatformStore) GetPublicKeyByItemID ¶
func (s PlatformStore) GetPublicKeyByItemID(itemID int64) (string, error)
GetPublicKeyByItemID returns the public key for a specific item ID. Returns an empty string if there is no public key but the platform exists. Returns an error if the platform doesn't exist.
type PropagationStep ¶ added in v2.21.4
type PropagationStep string
PropagationStep represents a step in the propagation process.
const ( // PropagationStepAccessMain is the main step of the access propagation. PropagationStepAccessMain PropagationStep = "access: main step" // PropagationStepResultsNamedLockAcquire is the step of acquiring the named lock for results propagation. PropagationStepResultsNamedLockAcquire PropagationStep = "results: acquire named lock" // PropagationStepResultsInsideNamedLockInsertIntoResultsPropagate is the step of inserting into results_propagate inside the named lock. PropagationStepResultsInsideNamedLockInsertIntoResultsPropagate PropagationStep = "results: inside named lock: " + "insert into results_propagate" // PropagationStepResultsInsideNamedLockMarkAndInsertResults is the step of marking and inserting results inside the named lock. PropagationStepResultsInsideNamedLockMarkAndInsertResults PropagationStep = "results: inside named lock: mark and insert results" // PropagationStepResultsInsideNamedLockMain is the main step of the results propagation inside the named lock. PropagationStepResultsInsideNamedLockMain PropagationStep = "results: inside named lock: main step" // PropagationStepResultsInsideNamedLockItemUnlocking is the step of unlocking the items inside the named lock. PropagationStepResultsInsideNamedLockItemUnlocking PropagationStep = "results: inside named lock: item unlocking" // PropagationStepResultsPropagationScheduling is the step of scheduling the propagation of permissions and results. PropagationStepResultsPropagationScheduling PropagationStep = "results: propagation scheduling" )
type RawGeneratedPermissionFields ¶
type RawGeneratedPermissionFields struct { CanViewGeneratedValue int CanGrantViewGeneratedValue int CanWatchGeneratedValue int CanEditGeneratedValue int IsOwnerGenerated bool }
RawGeneratedPermissionFields represents DB data fields for item permissions used by item-related services.
func (*RawGeneratedPermissionFields) AsItemPermissions ¶
func (raw *RawGeneratedPermissionFields) AsItemPermissions( permissionGrantedStore *PermissionGrantedStore, ) *structures.ItemPermissions
AsItemPermissions converts RawGeneratedPermissionFields into structures.ItemPermissions.
type ResultStore ¶
type ResultStore struct {
*DataStore
}
ResultStore implements database operations on `results`.
func (*ResultStore) ByID ¶
func (s *ResultStore) ByID(participantID, attemptID, itemID int64) *DB
ByID returns a composable query for getting a result row by the primary key (participant_id, attemptID, itemID).
func (*ResultStore) GetHintsInfoForActiveAttempt ¶
func (s *ResultStore) GetHintsInfoForActiveAttempt(participantID, attemptID, itemID int64) (result *HintsInfo, err error)
GetHintsInfoForActiveAttempt returns HintsInfo of the result identified by given participantID, attemptID, itemID and linked to an active attempt. If such a result doesn't exist, the gorm.ErrRecordNotFound error is returned.
func (*ResultStore) MarkAsToBePropagated ¶
func (s *ResultStore) MarkAsToBePropagated(participantID, attemptID, itemID int64, propagateNow bool) error
MarkAsToBePropagated marks a given result as 'to_be_propagated'.
func (*ResultStore) PropagateAndCollectUnlockedItemsForParticipant ¶ added in v2.24.0
func (s *ResultStore) PropagateAndCollectUnlockedItemsForParticipant(participantID int64) ( participantItemsUnlocked *golang.Set[int64], err error, )
PropagateAndCollectUnlockedItemsForParticipant recomputes fields of results and propagates permissions for unlocked items. It returns the set of unlocked items for the given participant.
Note: The method propagates results and permissions synchronously. It does not use propagations scheduling. Callers probably want to call this method inside a transaction and mark the transaction with DataStore.SetPropagationsModeToSync() to ensure it will not process results and permissions that are marked for propagation by other transactions.
Note 2: The method does not process the results_recompute_for_items table.
type SQLStmtWrapper ¶ added in v2.23.5
type SQLStmtWrapper struct {
// contains filtered or unexported fields
}
SQLStmtWrapper is a wrapper around a sql.Stmt that logs queries and execution plans. An SQLStmtWrapper is safe for concurrent use by multiple goroutines.
As the only possible way to get an object of this type is to call DB.Prepare,
If an SQLStmtWrapper is prepared on a Tx or Conn, it will be bound to a single underlying connection forever. If the Tx or Conn closes, the Stmt will become unusable and all operations will return an error. If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically.
func (*SQLStmtWrapper) Close ¶ added in v2.23.5
func (s *SQLStmtWrapper) Close() error
Close closes the statement.
func (*SQLStmtWrapper) ExecContext ¶ added in v2.23.5
func (s *SQLStmtWrapper) ExecContext(ctx context.Context, args ...interface{}) (result sql.Result, err error)
ExecContext executes a prepared statement with the given arguments and returns a sql.Result summarizing the effect of the statement.
func (*SQLStmtWrapper) QueryContext ¶ added in v2.23.5
func (s *SQLStmtWrapper) QueryContext(ctx context.Context, args ...interface{}) (rows *sql.Rows, err error)
QueryContext executes a prepared query statement with the given arguments and returns the query results as a *sql.Rows.
func (*SQLStmtWrapper) QueryRowContext ¶ added in v2.23.5
func (s *SQLStmtWrapper) QueryRowContext(ctx context.Context, args ...interface{}) (row *sql.Row)
QueryRowContext executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *sql.Row, which is always non-nil. If the query selects no rows, the *sql.Row.Scan will return sql.ErrNoRows. Otherwise, the *sql.Row.Scan scans the first selected row and discards the rest.
Example usage:
var name string err := nameByUseridStmt.QueryRow(ctx, id).Scan(&name)
type SessionStore ¶
type SessionStore struct {
*DataStore
}
SessionStore implements database operations on `sessions`.
func (*SessionStore) DeleteOldSessionsToKeepMaximum ¶
func (s *SessionStore) DeleteOldSessionsToKeepMaximum(userID int64, max int)
DeleteOldSessionsToKeepMaximum deletes old sessions to keep the maximum number of sessions.
func (*SessionStore) GetUserAndSessionIDByValidAccessToken ¶
func (s *SessionStore) GetUserAndSessionIDByValidAccessToken(token string) (user User, sessionID int64, err error)
GetUserAndSessionIDByValidAccessToken returns the user and session ID associated with the given access token.
type ThreadStore ¶
type ThreadStore struct {
*DataStore
}
ThreadStore implements database operations on threads.
func (*ThreadStore) CanRetrieveThread ¶
func (s *ThreadStore) CanRetrieveThread(user *User, participantID, itemID int64) bool
CanRetrieveThread checks whether a user can retrieve a thread.
func (*ThreadStore) GetThreadInfo ¶
func (s *ThreadStore) GetThreadInfo(participantID, itemID int64, out interface{}) error
GetThreadInfo retrieves a thread's information in an interface.
func (*ThreadStore) GetThreadQuery ¶
func (s *ThreadStore) GetThreadQuery(participantID, itemID int64) *DB
GetThreadQuery returns a query to get a thread's information.
func (*ThreadStore) GetThreadStatus ¶
func (s *ThreadStore) GetThreadStatus(participantID, itemID int64) string
GetThreadStatus retrieves a thread's status.
func (*ThreadStore) JoinsItem ¶
func (s *ThreadStore) JoinsItem() *ThreadStore
JoinsItem joins the items table in the query.
func (*ThreadStore) JoinsUserParticipant ¶
func (s *ThreadStore) JoinsUserParticipant() *ThreadStore
JoinsUserParticipant joins the user participant in the query.
func (*ThreadStore) UpdateHelperGroupID ¶
func (s *ThreadStore) UpdateHelperGroupID(oldHelperGroupID, newHelperGroupID int64)
UpdateHelperGroupID updates all occurrences of a certain helper_group_id to a new value.
func (*ThreadStore) UserCanChangeStatus ¶
func (s *ThreadStore) UserCanChangeStatus(user *User, oldStatus, newStatus string, participantID, itemID int64) bool
UserCanChangeStatus checks whether a user can change the status of a thread
- The participant of a thread can always switch the thread from open to any another other status. He can only switch it from non-open to an open status if he is allowed to request help on this item
- A user who has can_watch>=answer on the item AND can_watch_members on the participant: can always switch a thread to any open status (i.e. he can always open it but not close it)
- A user who can write on the thread can switch from an open status to another open status.
func (*ThreadStore) UserCanWrite ¶
func (s *ThreadStore) UserCanWrite(user *User, participantID, itemID int64) bool
UserCanWrite checks write permission from a user to a thread.
func (*ThreadStore) WhereParticipantIsInGroup ¶
func (s *ThreadStore) WhereParticipantIsInGroup(groupID int64) *ThreadStore
WhereParticipantIsInGroup filters the threads on the participant.
func (*ThreadStore) WhereUserCanHelp ¶
func (s *ThreadStore) WhereUserCanHelp(user *User) *ThreadStore
WhereUserCanHelp filters the thread where the user can help.
type Time ¶
Time is the same as time.Time, but it can be assigned from MySQL datetime string representation (implements Scanner interface), can convert itself to sql/driver.Value (implements Valuer interface) and marshal itself as JSON (implements json.Marshaler)
swagger:strfmt date-time
func (*Time) MarshalJSON ¶
MarshalJSON returns the JSON encoding of t.
func (*Time) ScanString ¶
ScanString assigns a value from string with a database driver value.
type User ¶
type User struct { GroupID int64 Login string LoginID *int64 DefaultLanguage string IsAdmin bool IsTempUser bool `sql:"column:temp_user"` AccessGroupID *int64 NotificationsReadAt *Time }
User represents data associated with the user (from the `users` table).
func (*User) CanRequestHelpTo ¶
CanRequestHelpTo checks whether the user can request help on an item to a group.
func (*User) CanSeeAnswer ¶
CanSeeAnswer checks whether the user can see an answer for a participantID-itemID couple.
- the user should have at least 'content' access rights on the item,
- the user is able to see answers related to his group's attempts, so the user should be a member of the participantID team or participantID should be equal to the user's self group
func (*User) CanViewItemContent ¶
CanViewItemContent checks whether the user has can_view >= content on an item.
func (*User) CanViewItemInfo ¶
CanViewItemInfo checks whether the user has can_view >= info on an item.
func (*User) CanWatchGroupMembers ¶
CanWatchGroupMembers checks whether the user can watch a group / a participant.
func (*User) CanWatchItemAnswer ¶
CanWatchItemAnswer checks whether the user has can_watch >= answer on an item.
func (*User) CanWatchItemResult ¶
CanWatchItemResult checks whether the user has can_watch >= result on an item.
func (*User) GetManagedGroupsWithCanGrantGroupAccessIds ¶
GetManagedGroupsWithCanGrantGroupAccessIds retrieves all group ids that the user manages and for which he can_grant_group_access.
func (*User) HasItemPermission ¶
func (u *User) HasItemPermission(s *DataStore, itemID int64, permissionType, permissionValue string) bool
HasItemPermission checks whether the user have a certain permission on an item.
func (*User) HasStartedResultOnItem ¶
HasStartedResultOnItem checks whether the user has a started result on an item.
func (*User) HasValidatedItem ¶
HasValidatedItem checks whether the user has validated an item.
func (*User) IsItemOwner ¶
IsItemOwner checks whether the user is the owner of an item.
type UserBatchPrefixStore ¶
type UserBatchPrefixStore struct {
*DataStore
}
UserBatchPrefixStore implements database operations on `user_batch_prefixes`.
type UserBatchStore ¶
type UserBatchStore struct {
*DataStore
}
UserBatchStore implements database operations on `user_batches`.
type UserStore ¶
type UserStore struct {
*DataStore
}
UserStore implements database operations on `users`.
func (*UserStore) DeleteTemporaryWithTraps ¶
DeleteTemporaryWithTraps deletes temporary users who don't have sessions or whose sessions expired more than `delay` ago. It also removes linked rows in the tables:
- [`filters`, `sessions`, `access_tokens`] having `user_id` = `users.group_id`;
- `answers` having `author_id`/`participant_id` = `users.group_id`;
- [`permissions_granted`, `permissions_generated`, `attempts`] having `group_id` = `users.group_id`;
- [`attempts`, `results`] having `participant_id` = `users.group_id`;
- `groups_groups` having `parent_group_id` or `child_group_id` equal to `users.group_id`;
- `groups_ancestors` having `ancestor_group_id` or `child_group_id` equal to `users.group_id`;
- [`groups_propagate`, `groups`] having `id` equal to `users.group_id`.
func (*UserStore) DeleteWithTraps ¶
DeleteWithTraps deletes a given user. It also removes linked rows in the same way as DeleteTemporaryWithTraps. For non-temporary users (when isTemporary is false), it also removes `permissions_granted` having source_group_id = users.group_id and schedules the permissions propagation.
func (*UserStore) DeleteWithTrapsByScope ¶
func (s *UserStore) DeleteWithTrapsByScope(scopeFunc func(store *DataStore) *DB, isTemporary bool) (err error)
DeleteWithTrapsByScope deletes users matching the given scope. It also removes linked rows in the same way as DeleteTemporaryWithTraps. For non-temporary users (when isTemporary is false), it also removes `permissions_granted` having source_group_id = users.group_id and schedules the permissions propagation.
Source Files ¶
- access_token_store.go
- ancestors.go
- answer_store.go
- approvals.go
- attempt_store.go
- badges.go
- data_store.go
- db.go
- db_enums.go
- errors.go
- grading_store.go
- group_ancestor_store.go
- group_contest_item_store.go
- group_group_store.go
- group_group_store_transitions.go
- group_groups.go
- group_manager_store.go
- group_membership_change_store.go
- group_pending_request_store.go
- group_store.go
- groups.go
- item_access_details.go
- item_ancestor_store.go
- item_item_store.go
- item_store.go
- item_string_store.go
- item_unlocking_rule_store.go
- items.go
- language_store.go
- mock_db.go
- mysql_conn_reset.go
- mysql_connection_wrapper.go
- mysql_connector_wrapper.go
- mysql_driver_wrapper.go
- now.go
- permission_generated_store.go
- permission_granted_store.go
- permission_granted_store_compute_all_access.go
- permissions.go
- platform_store.go
- propagation_steps.go
- query_logger.go
- raw_db_logger.go
- raw_generated_permission_fields.go
- result_store.go
- result_store_propagate.go
- search.go
- session_store.go
- sql_conn_wrapper.go
- sql_db_wrapper.go
- sql_stmt_wrapper.go
- sql_tx_wrapper.go
- thread.go
- thread_store.go
- time.go
- user.go
- user_batch_prefix_store.go
- user_batch_store.go
- user_store.go
- users.go
Directories ¶
Path | Synopsis |
---|---|
Package configdb makes sure the database has all the mandatory rows expected from the configuration.
|
Package configdb makes sure the database has all the mandatory rows expected from the configuration. |
Package mysqldb contains database-related functions that are specific to mysql.
|
Package mysqldb contains database-related functions that are specific to mysql. |