database

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2023 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package database provides an interface for database operations.

Index

Constants

This section is empty.

Variables

View Source
var ErrLockWaitTimeoutExceeded = errors.New("lock wait timeout exceeded")

ErrLockWaitTimeoutExceeded is returned when we cannot acquire a lock.

View Source
var ErrNoTransaction = errors.New("should be executed in a transaction")

ErrNoTransaction means that a called method/function cannot work outside of a transaction.

View Source
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 ClearAllDBEnums

func ClearAllDBEnums()

ClearAllDBEnums clears all cached permission enums.

func Default

func Default() interface{}

Default returns gorm.Expr("DEFAULT").

func EscapeLikeString

func EscapeLikeString(v string, escapeCharacter byte) string

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

func IsDuplicateEntryError(err error) bool

IsDuplicateEntryError checks whether an error corresponds to a duplicate of primary keys on insertion.

func IsDuplicateEntryErrorForKey added in v1.7.0

func IsDuplicateEntryErrorForKey(err error, key string) bool

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

func IsForeignConstraintError(err error) bool

IsForeignConstraintError checks whether an error corresponds to a foreign key constraint fail on insert/update.

func IsLockDeadlockError added in v1.7.0

func IsLockDeadlockError(err error) bool

IsLockDeadlockError checks whether an error corresponds to a deadlock when trying to get a lock.

func IsThreadClosedStatus added in v1.8.0

func IsThreadClosedStatus(status string) bool

IsThreadClosedStatus checks whether a status is considered closed.

func IsThreadOpenStatus added in v1.8.0

func IsThreadOpenStatus(status string) bool

IsThreadOpenStatus checks whether a status is considered open.

func MockDBEnumQueries

func MockDBEnumQueries(sqlMock sqlmock.Sqlmock)

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

func OpenRawDBConnection(sourceDSN string) (*sql.DB, error)

OpenRawDBConnection creates a new DB connection.

func QuoteName

func QuoteName(name string) string

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) GetCurrentAnswer added in v1.9.0

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 added in v1.9.0

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 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 NewDBMock

func NewDBMock() (*DB, sqlmock.Sqlmock)

NewDBMock generate a DB mock the database engine.

func Open

func Open(source interface{}) (*DB, error)

Open connects to the database and tests the connection. nolint: gosec

func (*DB) Close

func (conn *DB) Close() error

Close close current db connection. If database connection is not an io.Closer, returns an error.

func (*DB) Count

func (conn *DB) Count(dest interface{}) *DB

Count gets how many records for a model.

func (*DB) Delete

func (conn *DB) Delete(where ...interface{}) *DB

Delete deletes value matching given conditions, if the value has primary key, then will including the primary key as condition.

func (*DB) Error

func (conn *DB) Error() error

Error returns current errors.

func (*DB) Exec

func (conn *DB) Exec(sqlQuery string, values ...interface{}) *DB

Exec executes raw sql.

func (*DB) Group

func (conn *DB) Group(query string) *DB

Group specifies the group method on the find.

func (*DB) HasRows

func (conn *DB) HasRows() (bool, error)

HasRows returns true if at least one row is found.

func (*DB) Having

func (conn *DB) Having(query interface{}, args ...interface{}) *DB

Having specifies HAVING conditions for GROUP BY.

func (*DB) HavingMaxPermissionAtLeast

func (conn *DB) HavingMaxPermissionAtLeast(permissionKind, permissionName string) *DB

HavingMaxPermissionAtLeast returns a composable query filtered by `MAX(can_*_generated_value)` >= indexOf(`permissionName`) depending on the given permission kind.

func (*DB) InsertIgnoreMaps

func (conn *DB) InsertIgnoreMaps(tableName string, dataMaps []map[string]interface{}) error

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

func (conn *DB) Joins(query string, args ...interface{}) *DB

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

func (conn *DB) JoinsUserAndDefaultItemStrings(user *User) *DB

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) Limit

func (conn *DB) Limit(limit interface{}) *DB

Limit specifies the number of records to be retrieved.

func (*DB) New

func (conn *DB) New() *DB

New clones a new db connection without search conditions.

func (*DB) Order

func (conn *DB) Order(value interface{}, reorder ...bool) *DB

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

func (conn *DB) Pluck(column string, values interface{}) *DB

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

func (conn *DB) PluckFirst(column string, value interface{}) *DB

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

func (conn *DB) Raw(query string, args ...interface{}) *DB

Raw uses raw sql as conditions

db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)

func (*DB) RowsAffected

func (conn *DB) RowsAffected() int64

RowsAffected returns the number of rows affected by the last INSERT/UPDATE/DELETE statement.

func (*DB) Scan

func (conn *DB) Scan(dest interface{}) *DB

Scan scans value to a struct.

func (*DB) ScanAndHandleMaps

func (conn *DB) ScanAndHandleMaps(handler func(map[string]interface{}) error) *DB

ScanAndHandleMaps scans values into maps and calls the given handler for each row.

func (*DB) ScanIntoSliceOfMaps

func (conn *DB) ScanIntoSliceOfMaps(dest *[]map[string]interface{}) *DB

ScanIntoSliceOfMaps scans value into a slice of maps.

func (*DB) ScanIntoSlices

func (conn *DB) ScanIntoSlices(pointersToSlices ...interface{}) *DB

ScanIntoSlices scans multiple columns into slices.

func (*DB) Select

func (conn *DB) Select(query interface{}, args ...interface{}) *DB

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

func (conn *DB) Set(name string, value interface{}) *DB

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) Table

func (conn *DB) Table(name string) *DB

Table specifies the table you would like to run db operations.

func (*DB) Take

func (conn *DB) Take(out interface{}, where ...interface{}) *DB

Take returns a record that match given conditions, the order will depend on the database implementation.

func (*DB) Union

func (conn *DB) Union(query interface{}) *DB

Union specifies UNION of two queries (receiver UNION query).

func (*DB) UnionAll

func (conn *DB) UnionAll(query interface{}) *DB

UnionAll specifies UNION ALL of two queries (receiver UNION ALL query).

func (*DB) UpdateColumn

func (conn *DB) UpdateColumn(attrs ...interface{}) *DB

UpdateColumn updates attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update

func (*DB) Updates

func (conn *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) *DB

Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update

func (*DB) Where

func (conn *DB) Where(query interface{}, args ...interface{}) *DB

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

func (conn *DB) WhereGroupRelationIsActual() *DB

WhereGroupRelationIsActual restricts `groups_groups.type` to values corresponding to actual group membership and forces the relation to be not expired.

func (*DB) WhereItemsAreSelfOrDescendantsOf added in v1.9.0

func (conn *DB) WhereItemsAreSelfOrDescendantsOf(itemAncestorID int64) *DB

WhereItemsAreSelfOrDescendantsOf filters items who are self or descendant of a given item.

func (*DB) WhereItemsAreVisible

func (conn *DB) WhereItemsAreVisible(groupID int64) *DB

WhereItemsAreVisible returns a subview of the visible items for the given group basing on the given view.

func (*DB) WhereItemsContentAreVisible added in v1.9.0

func (conn *DB) WhereItemsContentAreVisible(groupID int64) *DB

WhereItemsContentAreVisible returns a subview of the content visible items for the given group.

func (*DB) WherePermissionIsAtLeast

func (conn *DB) WherePermissionIsAtLeast(permissionKind, permissionName string) *DB

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

func (conn *DB) WhereUserHasViewPermissionOnItems(user *User, viewPermission string) *DB

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

func (conn *DB) WhereUserHaveStartedResultOnItem(user *User) *DB

WhereUserHaveStartedResultOnItem makes sure that the user have a started result on the item, whatever the attempt.

func (*DB) WhereUsersAreDescendantsOfGroup

func (conn *DB) WhereUsersAreDescendantsOfGroup(groupID int64) *DB

WhereUsersAreDescendantsOfGroup joins `groups_ancestors_active` on ancestor_group_id=groupID & child_group_id=users.group_id.

func (*DB) WithPersonalInfoViewApprovals

func (conn *DB) WithPersonalInfoViewApprovals(manager *User) *DB

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

func (conn *DB) WithWriteLock() *DB

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 NewDataStore

func NewDataStore(conn *DB) *DataStore

NewDataStore returns a DataStore.

func NewDataStoreWithContext added in v1.3.0

func NewDataStoreWithContext(ctx context.Context, conn *DB) *DataStore

NewDataStoreWithContext returns a new DataStore with the given context.

func NewDataStoreWithTable

func NewDataStoreWithTable(conn *DB, tableName string) *DataStore

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) ByID

func (s *DataStore) ByID(id int64) *DB

ByID returns a composable query for filtering by _table_.id.

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) Groups

func (s *DataStore) Groups() *GroupStore

Groups returns a GroupStore.

func (*DataStore) InTransaction

func (s *DataStore) InTransaction(txFunc func(*DataStore) error) error

InTransaction executes the given function in a transaction and commits.

func (*DataStore) InsertMap

func (s *DataStore) InsertMap(dataMap map[string]interface{}) error

InsertMap reads fields from the given map and inserts the values which have been set into the store's table.

func (*DataStore) InsertMaps

func (s *DataStore) InsertMaps(dataMaps []map[string]interface{}) error

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

func (s *DataStore) InsertOrUpdateMap(dataMap map[string]interface{}, updateColumns []string) error

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) Items

func (s *DataStore) Items() *ItemStore

Items returns a ItemStore.

func (*DataStore) Languages

func (s *DataStore) Languages() *LanguageStore

Languages returns a LanguageStore.

func (*DataStore) NewID

func (s *DataStore) NewID() int64

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) NewThreadStore added in v1.9.0

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) 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

func (s *DataStore) RetryOnDuplicatePrimaryKeyError(f func(store *DataStore) error) error

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) Users

func (s *DataStore) Users() *UserStore

Users returns a UserStore.

func (*DataStore) WithForeignKeyChecksDisabled

func (s *DataStore) WithForeignKeyChecksDisabled(blockFunc func(*DataStore) error) 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, txFunc func(*DataStore) error) error

WithNamedLock wraps the given function in GET_LOCK/RELEASE_LOCK.

func (*DataStore) WithWriteLock added in v1.8.0

func (s *DataStore) WithWriteLock() *DataStore

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) AncestorsOfJoinedGroupsForGroup added in v1.10.0

func (s *GroupStore) AncestorsOfJoinedGroupsForGroup(store *DataStore, groupID int64) *DB

AncestorsOfJoinedGroupsForGroup returns a query selecting all group ancestors ids of a group.

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) IsVisibleForGroup added in v1.10.0

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) 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, for a user.

func (*GroupStore) ManagedUsersAndAncestorsOfManagedGroupsForGroup added in v1.10.0

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 added in v1.8.0

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 added in v1.10.0

func (s *GroupStore) PickVisibleGroupsForGroup(db *DB, visibleForGroupID int64) *DB

PickVisibleGroupsForGroup returns a query filtering only group which are visible for a group.

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:

  1. 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;
  2. 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;
  3. 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.
  4. 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

  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 (*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 HintsInfo

type HintsInfo struct {
	HintsRequested *string
	HintsCached    int32
}

HintsInfo contains information on requested hints and their cached count.

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

func (s *ItemStore) ContestManagedByUser(contestItemID int64, user *User) *DB

ContestManagedByUser returns a composable query for getting a contest with the given item id managed by the given user.

func (*ItemStore) DeleteItem

func (s *ItemStore) DeleteItem(itemID int64) (err error)

DeleteItem deletes an item. Note the method fails if the item has children.

func (*ItemStore) GetAncestorsRequestHelpPropagatedQuery added in v1.12.0

func (s *ItemStore) GetAncestorsRequestHelpPropagatedQuery(itemID int64) *DB

GetAncestorsRequestHelpPropagatedQuery gets all ancestors of an itemID while request_help_propagation = 1.

func (*ItemStore) GetItemIDFromTextID added in v1.8.0

func (s *ItemStore) GetItemIDFromTextID(textID string) (itemID int64, err error)

GetItemIDFromTextID gets the item_id from the text_id of an item.

func (*ItemStore) GroupHasPermissionOnItem added in v1.9.0

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 added in v1.13.0

func (s *ItemStore) HasCanRequestHelpTo(itemID, groupID int64) bool

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) Visible

func (s *ItemStore) Visible(groupID int64) *DB

Visible returns a view of the visible items for the given participant.

func (*ItemStore) VisibleByID

func (s *ItemStore) VisibleByID(groupID, itemID int64) *DB

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

type ParentChild struct {
	ParentID int64
	ChildID  int64
}

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`.

func (PlatformStore) GetPublicKeyByItemID added in v1.9.0

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 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) JoinsItem added in v1.9.0

func (s *ThreadStore) JoinsItem() *ThreadStore

JoinsItem joins the items table in the query.

func (*ThreadStore) JoinsUserParticipant added in v1.9.0

func (s *ThreadStore) JoinsUserParticipant() *ThreadStore

JoinsUserParticipant joins the user participant in the query.

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.

func (*ThreadStore) WhereParticipantIsInGroup added in v1.9.0

func (s *ThreadStore) WhereParticipantIsInGroup(groupID int64) *ThreadStore

WhereParticipantIsInGroup filters the threads on the participant.

func (*ThreadStore) WhereUserCanHelp added in v1.9.0

func (s *ThreadStore) WhereUserCanHelp(user *User) *ThreadStore

WhereUserCanHelp filters the thread where the user can help.

type Time

type Time time.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

func (t *Time) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of t.

func (*Time) Scan

func (t *Time) Scan(src interface{}) (err error)

Scan assigns a value from a database driver value ([]byte).

func (*Time) ScanString

func (t *Time) ScanString(str string) (err error)

ScanString assigns a value from string with a database driver value.

func (*Time) Value

func (t *Time) Value() (driver.Value, error)

Value returns a database driver Value (*time.Time).

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

func (u *User) CanRequestHelpTo(s *DataStore, itemID, helperGroupID int64) bool

CanRequestHelpTo checks whether the user can request help on an item to a group.

func (*User) CanSeeAnswer added in v1.9.0

func (u *User) CanSeeAnswer(s *DataStore, participantID, itemID int64) bool

CanSeeAnswer checks whether the user can see an answer for a participantID-itemID couple.

  1. the user should have at least 'content' access rights on the item,
  2. 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 added in v1.9.0

func (u *User) CanViewItemContent(s *DataStore, itemID int64) bool

CanViewItemContent checks whether the user has can_view >= content on an item.

func (*User) CanViewItemInfo added in v1.9.0

func (u *User) CanViewItemInfo(s *DataStore, itemID int64) bool

CanViewItemInfo checks whether the user has can_view >= info on an item.

func (*User) CanWatchGroupMembers added in v1.8.0

func (u *User) CanWatchGroupMembers(s *DataStore, groupID int64) bool

CanWatchGroupMembers checks whether the user can watch a group / a participant.

func (*User) CanWatchItemAnswer added in v1.8.0

func (u *User) CanWatchItemAnswer(s *DataStore, itemID int64) bool

CanWatchItemAnswer checks whether the user has can_watch >= answer on an item.

func (*User) CanWatchItemResult added in v1.9.0

func (u *User) CanWatchItemResult(s *DataStore, itemID int64) bool

CanWatchItemResult checks whether the user has can_watch >= result on an item.

func (*User) Clone

func (u *User) Clone() *User

Clone returns a deep copy of the given User structure.

func (*User) GetManagedGroupsWithCanGrantGroupAccessIds added in v1.8.0

func (u *User) GetManagedGroupsWithCanGrantGroupAccessIds(store *DataStore) []int64

GetManagedGroupsWithCanGrantGroupAccessIds retrieves all group ids that the user manages and for which he can_grant_group_access.

func (*User) HasItemPermission added in v1.9.0

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 added in v1.9.0

func (u *User) HasStartedResultOnItem(s *DataStore, itemID int64) bool

HasStartedResultOnItem checks whether the user has a started result on an item.

func (*User) HasValidatedItem added in v1.8.0

func (u *User) HasValidatedItem(s *DataStore, itemID int64) bool

HasValidatedItem checks whether the user has validated an item.

func (*User) IsItemOwner added in v1.13.2

func (u *User) IsItemOwner(s *DataStore, itemID int64) bool

IsItemOwner checks whether the user is the owner of an item.

func (*User) IsMemberOfGroupOrSelf added in v1.9.0

func (u *User) IsMemberOfGroupOrSelf(s *DataStore, groupID int64) bool

IsMemberOfGroupOrSelf checks whether the user is a member of a group, or is the group.

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) ByID

func (s *UserStore) ByID(id int64) *DB

ByID returns a composable query for filtering by _table_.group_id.

func (*UserStore) DeleteTemporaryWithTraps

func (s *UserStore) DeleteTemporaryWithTraps() (err error)

DeleteTemporaryWithTraps deletes temporary users who don't have active sessions. It also removes linked rows in the tables:

  1. [`filters`, `sessions`, `refresh_tokens`] having `user_id` = `users.group_id`;
  2. `answers` having `author_id`/`participant_id` = `users.group_id`;
  3. [`permissions_granted`, `permissions_generated`, `attempts`] having `group_id` = `users.group_id`;
  4. [`attempts`, `results`] having `participant_id` = `users.group_id`;
  5. `groups_groups` having `parent_group_id` or `child_group_id` equal to `users.group_id`;
  6. `groups_ancestors` having `ancestor_group_id` or `child_group_id` equal to `users.group_id`;
  7. [`groups_propagate`, `groups`] having `id` equal to `users.group_id`.

func (*UserStore) DeleteWithTraps

func (s *UserStore) DeleteWithTraps(user *User) (err error)

DeleteWithTraps deletes a given user. It also removes linked rows in the same way as DeleteTemporaryWithTraps.

func (*UserStore) DeleteWithTrapsByScope

func (s *UserStore) DeleteWithTrapsByScope(scopeFunc func(store *DataStore) *DB) (err error)

DeleteWithTrapsByScope deletes users matching the given scope. It also removes linked rows in the same way as DeleteTemporaryWithTraps.

Directories

Path Synopsis
Package mysqldb contains database-related functions that are specific to mysql.
Package mysqldb contains database-related functions that are specific to mysql.

Jump to

Keyboard shortcuts

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