github.com/haalcala/mattermost-server-change-repo/v5@v5.33.2/store/sqlstore/context.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package sqlstore 5 6 import ( 7 "context" 8 9 "github.com/mattermost/gorp" 10 ) 11 12 // storeContextKey is the base type for all context keys for the store. 13 type storeContextKey string 14 15 // contextValue is a type to hold some pre-determined context values. 16 type contextValue string 17 18 // Different possible values of contextValue. 19 const ( 20 useMaster contextValue = "useMaster" 21 ) 22 23 // WithMaster adds the context value that master DB should be selected for this request. 24 func WithMaster(ctx context.Context) context.Context { 25 return context.WithValue(ctx, storeContextKey(useMaster), true) 26 } 27 28 // hasMaster is a helper function to check whether master DB should be selected or not. 29 func hasMaster(ctx context.Context) bool { 30 if v := ctx.Value(storeContextKey(useMaster)); v != nil { 31 if res, ok := v.(bool); ok && res { 32 return true 33 } 34 } 35 return false 36 } 37 38 // DBFromContext is a helper utility that returns the DB handle from a given context. 39 func (ss *SqlStore) DBFromContext(ctx context.Context) *gorp.DbMap { 40 if hasMaster(ctx) { 41 return ss.GetMaster() 42 } 43 return ss.GetReplica() 44 }