Documentation ¶
Overview ¶
Package database provides an interface for database operations.
Index ¶
- Variables
- func ClearAllDBEnums()
- func Default() interface{}
- func EscapeLikeString(v string, escapeCharacter byte) string
- func IsDuplicateEntryError(err error) bool
- func IsDuplicateEntryErrorForKey(err error, key string) bool
- func IsForeignConstraintError(err error) bool
- func IsLockDeadlockError(err error) bool
- func IsThreadClosedStatus(status string) bool
- func IsThreadOpenStatus(status string) bool
- func MockDBEnumQueries(sqlMock sqlmock.Sqlmock)
- func MockNow(timestamp string)
- func Now() interface{}
- func OpenRawDBConnection(sourceDSN string) (*sql.DB, error)
- func QuoteName(name string) string
- func RestoreNow()
- type AnswerStore
- func (s *AnswerStore) SubmitNewAnswer(authorID, participantID, attemptID, itemID int64, answer string) (int64, error)
- func (s *AnswerStore) Visible(user *User) *DB
- func (s *AnswerStore) WithItems() *AnswerStore
- func (s *AnswerStore) WithResults() *AnswerStore
- func (s *AnswerStore) WithUsers() *AnswerStore
- type AttemptStore
- type Badge
- type BadgeGroupPathElement
- type BadgeInfo
- 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) 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) 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) 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) 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 interface{}) *DB
- func (conn *DB) UnionAll(query interface{}) *DB
- func (conn *DB) UpdateColumn(attrs ...interface{}) *DB
- func (conn *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) *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) WhereItemsAreVisible(groupID int64) *DB
- func (conn *DB) WherePermissionIsAtLeast(permissionKind, permissionName string) *DB
- func (conn *DB) WhereUserHasPermissionOnItems(user *User, permissionKind, neededPermission string) *DB
- func (conn *DB) WhereUserHasViewPermissionOnItems(user *User, viewPermission string) *DB
- func (conn *DB) WhereUserHaveStartedResultOnItem(user *User) *DB
- func (conn *DB) WhereUsersAreDescendantsOfGroup(groupID int64) *DB
- func (conn *DB) WithPersonalInfoViewApprovals(manager *User) *DB
- func (conn *DB) WithWriteLock() *DB
- type DataStore
- 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) 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) 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) 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) NewID() int64
- func (s *DataStore) Permissions() *PermissionGeneratedStore
- func (s *DataStore) PermissionsGranted() *PermissionGrantedStore
- func (s *DataStore) Platforms() *PlatformStore
- func (s *DataStore) RefreshTokens() *RefreshTokenStore
- 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) ScheduleResultsPropagation()
- func (s *DataStore) Sessions() *SessionStore
- func (s *DataStore) Threads() *ThreadStore
- func (s *DataStore) UserBatchPrefixes() *UserBatchPrefixStore
- func (s *DataStore) UserBatches() *UserBatchStore
- func (s *DataStore) Users() *UserStore
- func (s *DataStore) WithForeignKeyChecksDisabled(blockFunc func(*DataStore) error) error
- func (s *DataStore) WithNamedLock(lockName string, timeout time.Duration, txFunc func(*DataStore) error) error
- func (s *DataStore) WithWriteLock() *DataStore
- type GradingStore
- type GroupAncestorStore
- type GroupApprovals
- type GroupContestItemStore
- type GroupGroupStore
- func (s *GroupGroupStore) After() (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) Transition(action GroupGroupTransitionAction, parentGroupID int64, childGroupIDs []int64, ...) (results GroupGroupTransitionResults, ...)
- func (s *GroupGroupStore) WhereUserIsMember(user *User) *DB
- func (s *GroupGroupStore) WithGroupsRelationsLock(txFunc func(*DataStore) error) error
- 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) 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) IsVisibleFor(groupID int64, user *User) bool
- func (s *GroupStore) ManagedBy(user *User) *DB
- func (s *GroupStore) ManagedUsersAndAncestorsOfManagedGroups(store *DataStore, user *User) *DB
- func (s *GroupStore) PickVisibleGroups(db *DB, user *User) *DB
- func (s *GroupStore) StoreBadges(badges []Badge, userID int64, newUser bool) (err error)
- func (s *GroupStore) TeamGroupForTeamItemAndUser(itemID int64, user *User) *DB
- func (s *GroupStore) TeamGroupForUser(teamGroupID int64, user *User) *DB
- type HintsInfo
- type ItemAccessDetails
- type ItemAccessDetailsWithID
- type ItemAncestorStore
- type ItemDependencyStore
- type ItemItemStore
- func (s *ItemItemStore) After() (err error)
- func (s *ItemItemStore) ChildrenOf(parentID int64) *ItemItemStore
- func (s *ItemItemStore) ContentViewPropagationIndexByName(name string) int
- func (s *ItemItemStore) ContentViewPropagationNameByIndex(index int) string
- 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) GetItemIDFromTextID(textID string) (itemID int64, err error)
- 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 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) After() (err error)
- 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 RawGeneratedPermissionFields
- type RefreshTokenStore
- type ResultStore
- 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) 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
- type Time
- type User
- func (u *User) CanRequestHelpTo(s *DataStore, itemID, helperGroupID int64) bool
- func (u *User) CanWatchGroupMembers(s *DataStore, groupID int64) bool
- func (u *User) CanWatchItemAnswer(s *DataStore, itemID int64) bool
- func (u *User) Clone() *User
- func (u *User) GetManagedGroupsWithCanGrantGroupAccessIds(store *DataStore) []int64
- func (u *User) HasValidatedItem(s *DataStore, itemID int64) bool
- type UserBatchPrefixStore
- type UserBatchStore
- type UserStore
Constants ¶
This section is empty.
Variables ¶
var ErrLockWaitTimeoutExceeded = errors.New("lock wait timeout exceeded")
ErrLockWaitTimeoutExceeded is returned when we cannot acquire a 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 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 IsDuplicateEntryError ¶ added in v1.7.0
IsDuplicateEntryError checks whether an error corresponds to a duplicate of primary keys on insertion.
func IsDuplicateEntryErrorForKey ¶ added in v1.7.0
IsDuplicateEntryErrorForKey checks whether an error corresponds to a duplicate of primary keys on insertion
for a certain key.
func IsForeignConstraintError ¶ added in v1.7.0
IsForeignConstraintError checks whether an error corresponds to a foreign key constraint fail on insert/update.
func IsLockDeadlockError ¶ added in v1.7.0
IsLockDeadlockError checks whether an error corresponds to a deadlock when trying to get a lock.
func IsThreadClosedStatus ¶ added in v1.8.0
IsThreadClosedStatus checks whether a status is considered closed
func IsThreadOpenStatus ¶ added in v1.8.0
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 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 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()"))
Types ¶
type AnswerStore ¶
type AnswerStore struct {
*DataStore
}
AnswerStore implements database operations on `answers`
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) Visible ¶
func (s *AnswerStore) Visible(user *User) *DB
Visible returns a composable query for getting answers with the following access rights restrictions:
- the user should have at least 'content' access rights to the answers.item_id item,
- the user is able to see answers related to his group's attempts, so the user should be a member of the answers.participant_id team or answers.participant_id should be equal to the user's self group
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 ¶ added in v1.3.0
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 ¶ added in v1.3.0
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 ¶ added in v1.3.0
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 DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB contains information for current db connection (wraps *gorm.DB)
func (*DB) Close ¶
Close close 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) 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) JoinsPermissionsForGroupToItemsWherePermissionAtLeast ¶
func (conn *DB) JoinsPermissionsForGroupToItemsWherePermissionAtLeast(groupID int64, permissionKind, neededPermission string) *DB
JoinsPermissionsForGroupToItemsWherePermissionAtLeast returns a composable query with access rights (as *_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) 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) Updates ¶
Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
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) WhereItemsAreVisible ¶
WhereItemsAreVisible returns a subview of the visible items for the given group basing on the given view
func (*DB) WherePermissionIsAtLeast ¶
WherePermissionIsAtLeast returns a composable query filtered by `can_*_generated_value` >= indexOf(`permissionName`) depending on the given permission kind
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) WhereUserHaveStartedResultOnItem ¶ added in v1.7.0
WhereUserHaveStartedResultOnItem makes sure that the user have a started result on the item, whatever the attempt
func (*DB) WhereUsersAreDescendantsOfGroup ¶
WhereUsersAreDescendantsOfGroup joins `groups_ancestors_active` on ancestor_group_id=groupID & child_group_id=users.group_id
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) WithWriteLock ¶
WithWriteLock converts "SELECT ..." statement into "SELECT ... FOR UPDATE" statement
type DataStore ¶
type DataStore struct { *DB // contains filtered or unexported fields }
DataStore gather all stores for database operations on business data
func NewDataStoreWithContext ¶ added in v1.3.0
NewDataStoreWithContext returns a new DataStore with the given context
func NewDataStoreWithTable ¶
NewDataStoreWithTable returns a specialized DataStore
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) 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
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) 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) NewID ¶
NewID generates a positive random int64 to be used as id !!! To be safe, the insertion should be be retried if the id conflicts with an existing entry
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) RefreshTokens ¶
func (s *DataStore) RefreshTokens() *RefreshTokenStore
RefreshTokens returns a RefreshTokenStore
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) ScheduleResultsPropagation ¶ added in v1.3.0
func (s *DataStore) ScheduleResultsPropagation()
ScheduleResultsPropagation schedules a run of ResultStore::propagate() on transaction commit
func (*DataStore) Sessions ¶
func (s *DataStore) Sessions() *SessionStore
Sessions returns a SessionStore
func (*DataStore) Threads ¶ added in v1.8.0
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) WithForeignKeyChecksDisabled ¶
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, txFunc func(*DataStore) error) error
WithNamedLock wraps the given function in GET_LOCK/RELEASE_LOCK
func (*DataStore) WithWriteLock ¶ added in v1.8.0
WithWriteLock converts "SELECT ..." statement into "SELECT ... FOR UPDATE" statement
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 ¶ added in v1.2.0
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) After ¶
func (s *GroupGroupStore) After() (err error)
After is a "listener" that calls GroupGroupStore::createNewAncestors()
func (*GroupGroupStore) CreateRelation ¶
func (s *GroupGroupStore) CreateRelation(parentGroupID, childGroupID int64) (err error)
CreateRelation creates a direct relation between two groups
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) 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
func (*GroupGroupStore) WithGroupsRelationsLock ¶
func (s *GroupGroupStore) WithGroupsRelationsLock(txFunc func(*DataStore) error) error
WithGroupsRelationsLock wraps the given function in GET_LOCK/RELEASE_LOCK specific for modifying relations between groups
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 )
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" // 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 ¶ added in v1.8.0
func (s *GroupStore) AncestorsOfJoinedGroups(store *DataStore, user *User) *DB
AncestorsOfJoinedGroups returns a query selecting all group ancestors ids 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. It also runs GroupGroupStore.createNewAncestors().
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) IsVisibleFor ¶ added in v1.8.0
func (s *GroupStore) IsVisibleFor(groupID int64, user *User) bool
IsVisibleFor checks whether a group is visible to a user.
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) ManagedUsersAndAncestorsOfManagedGroups ¶ added in v1.8.0
func (s *GroupStore) ManagedUsersAndAncestorsOfManagedGroups(store *DataStore, user *User) *DB
ManagedUsersAndAncestorsOfManagedGroups returns all groups which are ancestors of managed groups, and all users who are descendants from managed groups.
func (*GroupStore) PickVisibleGroups ¶ added in v1.8.0
func (s *GroupStore) PickVisibleGroups(db *DB, user *User) *DB
PickVisibleGroups returns a query filtering only group which are visible.
func (*GroupStore) StoreBadges ¶ added in v1.3.0
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) TeamGroupForTeamItemAndUser ¶
func (s *GroupStore) TeamGroupForTeamItemAndUser(itemID int64, user *User) *DB
TeamGroupForTeamItemAndUser returns a composable query for getting a team that
- the given user is a member of
- 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 (*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) After ¶
func (s *ItemItemStore) After() (err error)
After is a "listener" that calls ItemItemStore::createNewAncestors(), PermissionGrantedStore::computeAllAccess() and schedules a run of ResultStore.propagate()
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) 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) GetItemIDFromTextID ¶ added in v1.8.0
GetItemIDFromTextID gets the item_id from the text_id of an item
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 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) After ¶
func (s *PermissionGrantedStore) After() (err error)
After is a "listener" that calls PermissionGrantedStore::computeAllAccess()
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 ¶ added in v1.8.0
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`
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 RefreshTokenStore ¶
type RefreshTokenStore struct {
*DataStore
}
RefreshTokenStore implements database operations on `refresh_tokens`
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) error
MarkAsToBePropagated marks a given result as 'to_be_propagated'
type SessionStore ¶
type SessionStore struct {
*DataStore
}
SessionStore implements database operations on `sessions`
func (*SessionStore) InsertNewOAuth ¶
func (s *SessionStore) InsertNewOAuth(userID int64, token string, secondsUntilExpiry int32, issuer string) error
InsertNewOAuth inserts a new OAuth token for the given user into the DB
type ThreadStore ¶ added in v1.8.0
type ThreadStore struct {
*DataStore
}
ThreadStore implements database operations on threads
func (*ThreadStore) CanRetrieveThread ¶ added in v1.8.0
func (s *ThreadStore) CanRetrieveThread(user *User, participantID, itemID int64) bool
CanRetrieveThread checks whether a user can retrieve a thread
func (*ThreadStore) GetThreadInfo ¶ added in v1.8.0
func (s *ThreadStore) GetThreadInfo(participantID, itemID int64, out interface{}) error
GetThreadInfo retrieves a thread's information in an interface
func (*ThreadStore) GetThreadQuery ¶ added in v1.8.0
func (s *ThreadStore) GetThreadQuery(participantID, itemID int64) *DB
GetThreadQuery returns a query to get a thread's information
func (*ThreadStore) GetThreadStatus ¶ added in v1.8.0
func (s *ThreadStore) GetThreadStatus(participantID, itemID int64) string
GetThreadStatus retrieves a thread's status
func (*ThreadStore) UpdateHelperGroupID ¶ added in v1.8.0
func (s *ThreadStore) UpdateHelperGroupID(oldHelperGroupID, newHelperGroupID int64)
UpdateHelperGroupID updates all occurrences of a certain helper_group_id to a new value
func (*ThreadStore) UserCanChangeStatus ¶ added in v1.8.0
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 ¶ added in v1.8.0
func (s *ThreadStore) UserCanWrite(user *User, participantID, itemID int64) bool
UserCanWrite checks write permission from a user to a thread
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 ¶ added in v1.8.0
CanRequestHelpTo checks whether the user can request help on an item to a group.
func (*User) CanWatchGroupMembers ¶ added in v1.8.0
CanWatchGroupMembers checks whether the user can watch a group / a participant.
func (*User) CanWatchItemAnswer ¶ added in v1.8.0
CanWatchItemAnswer checks whether the user has can_watch >= answer on an item
func (*User) GetManagedGroupsWithCanGrantGroupAccessIds ¶ added in v1.8.0
GetManagedGroupsWithCanGrantGroupAccessIds retrieves all group ids that the user manages and for which he can_grant_group_access.
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 active sessions. It also removes linked rows in the tables:
- [`filters`, `sessions`, `refresh_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.
Source Files ¶
- 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
- now.go
- permission_generated_store.go
- permission_granted_store.go
- permission_granted_store_compute_all_access.go
- permissions.go
- platform_store.go
- raw_generated_permission_fields.go
- refresh_token_store.go
- result_store.go
- result_store_propagate.go
- session_store.go
- thread.go
- thread_store.go
- time.go
- user.go
- user_batch_prefix_store.go
- user_batch_store.go
- user_store.go
- users.go