Merge branch 'master' into mark-as-unread

Этот коммит содержится в:
Harrison Healey
2019-09-18 13:16:23 -04:00
родитель 42e927cc3f c7b583ccdd
Коммит 5f28ce9de0
190 изменённых файлов: 11424 добавлений и 2337 удалений

Просмотреть файл

@@ -4,10 +4,8 @@
package sqlstore
import (
"fmt"
"net/http"
"database/sql"
"net/http"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
@@ -62,7 +60,7 @@ func (s SqlChannelMemberHistoryStore) LogLeaveEvent(userId string, channelId str
if rows, err := sqlResult.RowsAffected(); err == nil && rows != 1 {
// there was no join event to update - this is best effort, so no need to raise an error
mlog.Warn(fmt.Sprintf("Channel join event for user %v and channel %v not found", userId, channelId), mlog.String("user_id", userId))
mlog.Warn("Channel join event for user and channel not found", mlog.String("user", userId), mlog.String("channel", channelId))
}
return nil
}

Просмотреть файл

@@ -2345,17 +2345,7 @@ func (s SqlChannelStore) SearchMore(userId string, teamId string, term string) (
}
func (s SqlChannelStore) buildLIKEClause(term string, searchColumns string) (likeClause, likeTerm string) {
likeTerm = term
// These chars must be removed from the like query.
for _, c := range ignoreLikeSearchChar {
likeTerm = strings.Replace(likeTerm, c, "", -1)
}
// These chars must be escaped in the like query.
for _, c := range escapeLikeSearchChar {
likeTerm = strings.Replace(likeTerm, c, "*"+c, -1)
}
likeTerm = sanitizeSearchTerm(term, "*")
if likeTerm == "" {
return
@@ -2515,6 +2505,7 @@ func (s SqlChannelStore) getSearchGroupChannelsQuery(userId, term string, isPost
for idx, term := range terms {
argName := fmt.Sprintf("Term%v", idx)
term = sanitizeSearchTerm(term, "\\")
likeClauses = append(likeClauses, fmt.Sprintf(baseLikeClause, ":"+argName))
args[argName] = "%" + term + "%"
}

Просмотреть файл

@@ -90,6 +90,7 @@ func (s SqlComplianceStore) ComplianceExport(job *model.Compliance) ([]*model.Co
keywordQuery = "AND ("
for index, keyword := range keywords {
keyword = sanitizeSearchTerm(keyword, "\\")
if index >= 1 {
keywordQuery += " OR LOWER(Posts.Message) LIKE :Keyword" + strconv.Itoa(index)
} else {
@@ -211,6 +212,7 @@ func (s SqlComplianceStore) MessageExport(after int64, limit int) ([]*model.Mess
`SELECT
Posts.Id AS PostId,
Posts.CreateAt AS PostCreateAt,
Posts.UpdateAt AS PostUpdateAt,
Posts.Message AS PostMessage,
Posts.Type AS PostType,
Posts.OriginalId AS PostOriginalId,
@@ -239,9 +241,9 @@ func (s SqlComplianceStore) MessageExport(after int64, limit int) ([]*model.Mess
LEFT OUTER JOIN Users ON Posts.UserId = Users.Id
LEFT JOIN Bots ON Bots.UserId = Posts.UserId
WHERE
Posts.CreateAt > :StartTime AND
(Posts.CreateAt > :StartTime OR Posts.EditAt > :StartTime) AND
Posts.Type = ''
ORDER BY PostCreateAt
ORDER BY PostUpdateAt
LIMIT :Limit`
var cposts []*model.MessageExport

Просмотреть файл

@@ -147,6 +147,8 @@ func (es SqlEmojiStore) Delete(emoji *model.Emoji, time int64) *model.AppError {
func (es SqlEmojiStore) Search(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError) {
var emojis []*model.Emoji
name = sanitizeSearchTerm(name, "\\")
term := ""
if !prefixOnly {
term = "%"

Просмотреть файл

@@ -853,7 +853,7 @@ func (s *SqlGroupStore) groupsBySyncableBaseQuery(st model.GroupSyncableType, t
}
if len(opts.Q) > 0 {
pattern := fmt.Sprintf("%%%s%%", opts.Q)
pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\"))
operatorKeyword := "ILIKE"
if s.DriverName() == model.DATABASE_DRIVER_MYSQL {
operatorKeyword = "LIKE"
@@ -919,7 +919,7 @@ func (s *SqlGroupStore) GetGroups(page, perPage int, opts model.GroupSearchOpts)
}
if len(opts.Q) > 0 {
pattern := fmt.Sprintf("%%%s%%", opts.Q)
pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\"))
operatorKeyword := "ILIKE"
if s.DriverName() == model.DATABASE_DRIVER_MYSQL {
operatorKeyword = "LIKE"

Просмотреть файл

@@ -115,18 +115,24 @@ func (s *SqlPostStore) Save(post *model.Post) (*model.Post, *model.AppError) {
post.Type != model.POST_ADD_TO_CHANNEL && post.Type != model.POST_REMOVE_FROM_CHANNEL &&
post.Type != model.POST_ADD_TO_TEAM && post.Type != model.POST_REMOVE_FROM_TEAM {
if _, err := s.GetMaster().Exec("UPDATE Channels SET LastPostAt = GREATEST(:LastPostAt, LastPostAt), TotalMsgCount = TotalMsgCount + 1 WHERE Id = :ChannelId", map[string]interface{}{"LastPostAt": time, "ChannelId": post.ChannelId}); err != nil {
mlog.Error(fmt.Sprintf("Error updating Channel LastPostAt: %v", err.Error()))
mlog.Error("Error updating Channel LastPostAt.", mlog.Err(err))
}
} else {
// don't update TotalMsgCount for unimportant messages so that the channel isn't marked as unread
if _, err := s.GetMaster().Exec("UPDATE Channels SET LastPostAt = :LastPostAt WHERE Id = :ChannelId AND LastPostAt < :LastPostAt", map[string]interface{}{"LastPostAt": time, "ChannelId": post.ChannelId}); err != nil {
mlog.Error(fmt.Sprintf("Error updating Channel LastPostAt: %v", err.Error()))
mlog.Error("Error updating Channel LastPostAt.", mlog.Err(err))
}
}
if len(post.RootId) > 0 {
if _, err := s.GetMaster().Exec("UPDATE Posts SET UpdateAt = :UpdateAt WHERE Id = :RootId", map[string]interface{}{"UpdateAt": time, "RootId": post.RootId}); err != nil {
mlog.Error(fmt.Sprintf("Error updating Post UpdateAt: %v", err.Error()))
mlog.Error("Error updating Post UpdateAt.", mlog.Err(err))
}
} else {
if count, err := s.GetMaster().SelectInt("SELECT COUNT(*) FROM Posts WHERE RootId = :Id", map[string]interface{}{"Id": post.Id}); err != nil {
mlog.Error(fmt.Sprintf("Error fetching post's thread: %v", err.Error()))
} else {
post.ReplyCount = count
}
}
@@ -266,7 +272,7 @@ func (s *SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offse
return pl, nil
}
func (s *SqlPostStore) Get(id string) (*model.PostList, *model.AppError) {
func (s *SqlPostStore) Get(id string, skipFetchThreads bool) (*model.PostList, *model.AppError) {
pl := model.NewPostList()
if len(id) == 0 {
@@ -274,35 +280,40 @@ func (s *SqlPostStore) Get(id string) (*model.PostList, *model.AppError) {
}
var post model.Post
err := s.GetReplica().SelectOne(&post, "SELECT * FROM Posts WHERE Id = :Id AND DeleteAt = 0", map[string]interface{}{"Id": id})
var postFetchQuery string
if skipFetchThreads {
postFetchQuery = "SELECT p.*, (SELECT count(Posts.Id) FROM Posts WHERE Posts.RootId = p.RootId) FROM Posts p WHERE p.Id = :Id AND p.DeleteAt = 0"
} else {
postFetchQuery = "SELECT * FROM Posts WHERE Id = :Id AND DeleteAt = 0"
}
err := s.GetReplica().SelectOne(&post, postFetchQuery, map[string]interface{}{"Id": id})
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPost", "store.sql_post.get.app_error", nil, "id="+id+err.Error(), http.StatusNotFound)
}
pl.AddPost(&post)
pl.AddOrder(id)
if !skipFetchThreads {
rootId := post.RootId
rootId := post.RootId
if rootId == "" {
rootId = post.Id
}
if rootId == "" {
rootId = post.Id
if len(rootId) == 0 {
return nil, model.NewAppError("SqlPostStore.GetPost", "store.sql_post.get.app_error", nil, "root_id="+rootId, http.StatusInternalServerError)
}
var posts []*model.Post
_, err = s.GetReplica().Select(&posts, "SELECT * FROM Posts WHERE (Id = :Id OR RootId = :RootId) AND DeleteAt = 0", map[string]interface{}{"Id": rootId, "RootId": rootId})
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPost", "store.sql_post.get.app_error", nil, "root_id="+rootId+err.Error(), http.StatusInternalServerError)
}
for _, p := range posts {
pl.AddPost(p)
pl.AddOrder(p.Id)
}
}
if len(rootId) == 0 {
return nil, model.NewAppError("SqlPostStore.GetPost", "store.sql_post.get.app_error", nil, "root_id="+rootId, http.StatusInternalServerError)
}
var posts []*model.Post
_, err = s.GetReplica().Select(&posts, "SELECT * FROM Posts WHERE (Id = :Id OR RootId = :RootId) AND DeleteAt = 0", map[string]interface{}{"Id": rootId, "RootId": rootId})
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPost", "store.sql_post.get.app_error", nil, "root_id="+rootId+err.Error(), http.StatusInternalServerError)
}
for _, p := range posts {
pl.AddPost(p)
pl.AddOrder(p.Id)
}
return pl, nil
}
@@ -445,14 +456,14 @@ func (s *SqlPostStore) PermanentDeleteByChannel(channelId string) *model.AppErro
return nil
}
func (s *SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFromCache bool) (*model.PostList, *model.AppError) {
if limit > 1000 {
return nil, model.NewAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+channelId, http.StatusBadRequest)
func (s *SqlPostStore) GetPosts(options model.GetPostsOptions, allowFromCache bool) (*model.PostList, *model.AppError) {
if options.PerPage > 1000 {
return nil, model.NewAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+options.ChannelId, http.StatusBadRequest)
}
offset := options.PerPage * options.Page
// Caching only occurs on limits of 30 and 60, the common limits requested by MM clients
if allowFromCache && offset == 0 && (limit == 60 || limit == 30) {
if cacheItem, ok := s.lastPostsCache.Get(fmt.Sprintf("%s%v", channelId, limit)); ok {
if allowFromCache && offset == 0 && (options.PerPage == 60 || options.PerPage == 30) {
if cacheItem, ok := s.lastPostsCache.Get(fmt.Sprintf("%s%v", options.ChannelId, options.PerPage)); ok {
if s.metrics != nil {
s.metrics.IncrementMemCacheHitCounter("Last Posts Cache")
}
@@ -466,13 +477,13 @@ func (s *SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFr
rpc := make(chan store.StoreResult, 1)
go func() {
posts, err := s.getRootPosts(channelId, offset, limit)
posts, err := s.getRootPosts(options.ChannelId, offset, options.PerPage, options.SkipFetchThreads)
rpc <- store.StoreResult{Data: posts, Err: err}
close(rpc)
}()
cpc := make(chan store.StoreResult, 1)
go func() {
posts, err := s.getParentsPosts(channelId, offset, limit)
posts, err := s.getParentsPosts(options.ChannelId, offset, options.PerPage, options.SkipFetchThreads)
cpc <- store.StoreResult{Data: posts, Err: err}
close(cpc)
}()
@@ -505,18 +516,18 @@ func (s *SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFr
list.MakeNonNil()
// Caching only occurs on limits of 30 and 60, the common limits requested by MM clients
if offset == 0 && (limit == 60 || limit == 30) {
s.lastPostsCache.AddWithExpiresInSecs(fmt.Sprintf("%s%v", channelId, limit), list, LAST_POSTS_CACHE_SEC)
if offset == 0 && (options.PerPage == 60 || options.PerPage == 30) {
s.lastPostsCache.AddWithExpiresInSecs(fmt.Sprintf("%s%v", options.ChannelId, options.PerPage), list, LAST_POSTS_CACHE_SEC)
}
return list, err
}
func (s *SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache bool) (*model.PostList, *model.AppError) {
func (s *SqlPostStore) GetPostsSince(options model.GetPostsSinceOptions, allowFromCache bool) (*model.PostList, *model.AppError) {
if allowFromCache {
// If the last post in the channel's time is less than or equal to the time we are getting posts since,
// we can safely return no posts.
if cacheItem, ok := s.lastPostTimeCache.Get(channelId); ok && cacheItem.(int64) <= time {
if cacheItem, ok := s.lastPostTimeCache.Get(options.ChannelId); ok && cacheItem.(int64) <= options.Time {
if s.metrics != nil {
s.metrics.IncrementMemCacheHitCounter("Last Post Time")
}
@@ -556,19 +567,19 @@ func (s *SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCach
AND ChannelId = :ChannelId
LIMIT 1000) temp_tab))
ORDER BY CreateAt DESC`,
map[string]interface{}{"ChannelId": channelId, "Time": time})
map[string]interface{}{"ChannelId": options.ChannelId, "Time": options.Time})
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPostsSince", "store.sql_post.get_posts_since.app_error", nil, "channelId="+channelId+err.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("SqlPostStore.GetPostsSince", "store.sql_post.get_posts_since.app_error", nil, "channelId="+options.ChannelId+err.Error(), http.StatusInternalServerError)
}
list := model.NewPostList()
latestUpdate := time
latestUpdate := options.Time
for _, p := range posts {
list.AddPost(p)
if p.UpdateAt > time {
if p.UpdateAt > options.Time {
list.AddOrder(p.Id)
}
if latestUpdate < p.UpdateAt {
@@ -576,21 +587,25 @@ func (s *SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCach
}
}
s.lastPostTimeCache.AddWithExpiresInSecs(channelId, latestUpdate, LAST_POST_TIME_CACHE_SEC)
s.lastPostTimeCache.AddWithExpiresInSecs(options.ChannelId, latestUpdate, LAST_POST_TIME_CACHE_SEC)
return list, nil
}
func (s *SqlPostStore) GetPostsBefore(channelId string, postId string, limit int, offset int) (*model.PostList, *model.AppError) {
return s.getPostsAround(channelId, postId, limit, offset, true)
func (s *SqlPostStore) GetPostsBefore(options model.GetPostsOptions) (*model.PostList, *model.AppError) {
return s.getPostsAround(true, options)
}
func (s *SqlPostStore) GetPostsAfter(channelId string, postId string, limit int, offset int) (*model.PostList, *model.AppError) {
return s.getPostsAround(channelId, postId, limit, offset, false)
func (s *SqlPostStore) GetPostsAfter(options model.GetPostsOptions) (*model.PostList, *model.AppError) {
return s.getPostsAround(false, options)
}
func (s *SqlPostStore) getPostsAround(channelId string, postId string, limit int, offset int, before bool) (*model.PostList, *model.AppError) {
var direction, sort string
func (s *SqlPostStore) getPostsAround(before bool, options model.GetPostsOptions) (*model.PostList, *model.AppError) {
offset := options.Page * options.PerPage
var posts, parents []*model.Post
var direction string
var sort string
if before {
direction = "<"
sort = "DESC"
@@ -598,23 +613,29 @@ func (s *SqlPostStore) getPostsAround(channelId string, postId string, limit int
direction = ">"
sort = "ASC"
}
replyCountSubQuery := s.getQueryBuilder().Select("COUNT(Posts.Id)").From("Posts").Where(sq.Expr("p.RootId = '' AND RootId = p.Id"))
query := s.getQueryBuilder().Select("p.*")
if options.SkipFetchThreads {
query = query.Column(sq.Alias(replyCountSubQuery, "ReplyCount"))
}
query = query.From("Posts p").
Where(sq.And{
sq.Expr(`CreateAt `+direction+` (SELECT CreateAt FROM Posts WHERE Id = ?)`, options.PostId),
sq.Eq{"ChannelId": options.ChannelId},
sq.Eq{"DeleteAt": int(0)},
}).
OrderBy("CreateAt " + sort).
Limit(uint64(options.PerPage)).
Offset(uint64(offset))
queryString, args, err := query.ToSql()
var posts, parents []*model.Post
_, err := s.GetReplica().Select(&posts,
`SELECT
*
FROM
Posts
WHERE
CreateAt `+direction+` (SELECT CreateAt FROM Posts WHERE Id = :PostId)
AND ChannelId = :ChannelId
AND DeleteAt = 0
ORDER BY CreateAt `+sort+`
LIMIT :Limit
OFFSET :Offset`,
map[string]interface{}{"ChannelId": channelId, "PostId": postId, "Limit": limit, "Offset": offset})
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPostContext", "store.sql_post.get_posts_around.get.app_error", nil, "channelId="+channelId+err.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("SqlPostStore.GetPostContext", "store.sql_post.get_posts_around.get.app_error", nil, "channelId="+options.ChannelId+err.Error(), http.StatusInternalServerError)
}
_, err = s.GetMaster().Select(&posts, queryString, args...)
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPostContext", "store.sql_post.get_posts_around.get.app_error", nil, "channelId="+options.ChannelId+err.Error(), http.StatusInternalServerError)
}
if len(posts) > 0 {
@@ -625,28 +646,29 @@ func (s *SqlPostStore) getPostsAround(channelId string, postId string, limit int
rootIds = append(rootIds, post.RootId)
}
}
rootQuery := s.getQueryBuilder().Select("p.*")
if options.SkipFetchThreads {
rootQuery = rootQuery.Column(sq.Alias(replyCountSubQuery, "ReplyCount"))
}
rootQuery = rootQuery.From("Posts p").
Where(sq.And{
sq.Or{
sq.Eq{"RootId": rootIds},
sq.Eq{"Id": rootIds},
},
sq.Eq{"ChannelId": options.ChannelId},
sq.Eq{"DeleteAt": 0},
}).
OrderBy("CreateAt DESC")
keys, params := MapStringsToQueryParams(rootIds, "PostId")
params["ChannelId"] = channelId
params["PostId"] = postId
params["Limit"] = limit
params["Offset"] = offset
_, err = s.GetReplica().Select(&parents,
`SELECT
*
FROM
Posts
WHERE
(Id IN `+keys+` OR RootId IN `+keys+`)
AND ChannelId = :ChannelId
AND DeleteAt = 0
ORDER BY CreateAt DESC`,
params)
rootQueryString, rootArgs, err := rootQuery.ToSql()
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPostContext", "store.sql_post.get_posts_around.get_parent.app_error", nil, "channelId="+channelId+err.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("SqlPostStore.GetPostContext", "store.sql_post.get_posts_around.get_parent.app_error", nil, "channelId="+options.ChannelId+err.Error(), http.StatusInternalServerError)
}
_, err = s.GetMaster().Select(&parents, rootQueryString, rootArgs...)
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetPostContext", "store.sql_post.get_posts_around.get_parent.app_error", nil, "channelId="+options.ChannelId+err.Error(), http.StatusInternalServerError)
}
}
@@ -745,20 +767,29 @@ func (s *SqlPostStore) GetPostAfterTime(channelId string, time int64) (*model.Po
return post, nil
}
func (s *SqlPostStore) getRootPosts(channelId string, offset int, limit int) ([]*model.Post, *model.AppError) {
func (s *SqlPostStore) getRootPosts(channelId string, offset int, limit int, skipFetchThreads bool) ([]*model.Post, *model.AppError) {
var posts []*model.Post
_, err := s.GetReplica().Select(&posts, "SELECT * FROM Posts WHERE ChannelId = :ChannelId AND DeleteAt = 0 ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset", map[string]interface{}{"ChannelId": channelId, "Offset": offset, "Limit": limit})
var fetchQuery string
if skipFetchThreads {
fetchQuery = "SELECT p.*, (SELECT COUNT(Posts.Id) FROM Posts WHERE p.RootId = '' AND Posts.RootId = p.Id) as ReplyCount FROM Posts p WHERE ChannelId = :ChannelId AND DeleteAt = 0 ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset"
} else {
fetchQuery = "SELECT * FROM Posts WHERE ChannelId = :ChannelId AND DeleteAt = 0 ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset"
}
_, err := s.GetReplica().Select(&posts, fetchQuery, map[string]interface{}{"ChannelId": channelId, "Offset": offset, "Limit": limit})
if err != nil {
return nil, model.NewAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_root_posts.app_error", nil, "channelId="+channelId+err.Error(), http.StatusInternalServerError)
}
return posts, nil
}
func (s *SqlPostStore) getParentsPosts(channelId string, offset int, limit int) ([]*model.Post, *model.AppError) {
func (s *SqlPostStore) getParentsPosts(channelId string, offset int, limit int, skipFetchThreads bool) ([]*model.Post, *model.AppError) {
var posts []*model.Post
replyCountQuery := ""
if skipFetchThreads {
replyCountQuery = ` ,(SELECT COUNT(Posts.Id) FROM Posts WHERE q2.RootId = '' AND Posts.RootId = q2.Id) as ReplyCount`
}
_, err := s.GetReplica().Select(&posts,
`SELECT
q2.*
`SELECT q2.*`+replyCountQuery+`
FROM
Posts q2
INNER JOIN
@@ -1043,7 +1074,7 @@ func (s *SqlPostStore) Search(teamId string, userId string, params *model.Search
_, err := s.GetSearchReplica().Select(&posts, searchQuery, queryParams)
if err != nil {
mlog.Warn(fmt.Sprintf("Query error searching posts: %v", err.Error()))
mlog.Warn("Query error searching posts.", mlog.Err(err))
// Don't return the error to the caller as it is of no use to the user. Instead return an empty set of search results.
} else {
for _, p := range posts {
@@ -1232,7 +1263,7 @@ func (s *SqlPostStore) GetPostsByIds(postIds []string) ([]*model.Post, *model.Ap
_, err := s.GetReplica().Select(&posts, query, params)
if err != nil {
mlog.Error(fmt.Sprint(err))
mlog.Error("Query error getting posts.", mlog.Err(err))
return nil, model.NewAppError("SqlPostStore.GetPostsByIds", "store.sql_post.get_posts_by_ids.app_error", nil, "", http.StatusInternalServerError)
}
return posts, nil
@@ -1321,7 +1352,7 @@ func (s *SqlPostStore) determineMaxPostSize() int {
table_name = 'posts'
AND column_name = 'message'
`); err != nil {
mlog.Error(utils.T("store.sql_post.query_max_post_size.error") + err.Error())
mlog.Error("Unable to determine the maximum supported post size", mlog.Err(err))
}
} else if s.DriverName() == model.DATABASE_DRIVER_MYSQL {
// The Post.Message column in MySQL has historically been TEXT, with a maximum
@@ -1337,7 +1368,7 @@ func (s *SqlPostStore) determineMaxPostSize() int {
AND column_name = 'Message'
LIMIT 0, 1
`); err != nil {
mlog.Error(utils.T("store.sql_post.query_max_post_size.error") + err.Error())
mlog.Error("Unable to determine the maximum supported post size", mlog.Err(err))
}
} else {
mlog.Warn("No implementation found to determine the maximum supported post size")
@@ -1353,7 +1384,7 @@ func (s *SqlPostStore) determineMaxPostSize() int {
maxPostSize = model.POST_MESSAGE_MAX_RUNES_V1
}
mlog.Info(fmt.Sprintf("Post.Message supports at most %d characters (%d bytes)", maxPostSize, maxPostSizeBytes))
mlog.Info("Post.Message has size restrictions", mlog.Int("max_characters", maxPostSize), mlog.Int32("max_bytes", maxPostSizeBytes))
return maxPostSize
}

Просмотреть файл

@@ -4,7 +4,6 @@
package sqlstore
import (
"context"
"database/sql"
"fmt"
"net/http"
@@ -15,6 +14,10 @@ import (
"github.com/mattermost/mattermost-server/store"
)
type SqlRoleStore struct {
SqlStore
}
type Role struct {
Id string
Name string
@@ -68,7 +71,9 @@ func (role Role) ToModel() *model.Role {
}
}
func initSqlSupplierRoles(sqlStore SqlStore) {
func NewSqlRoleStore(sqlStore SqlStore) store.RoleStore {
s := &SqlRoleStore{sqlStore}
for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(Role{}, "Roles").SetKeys(false, "Id")
table.ColMap("Id").SetMaxSize(26)
@@ -77,9 +82,13 @@ func initSqlSupplierRoles(sqlStore SqlStore) {
table.ColMap("Description").SetMaxSize(1024)
table.ColMap("Permissions").SetMaxSize(4096)
}
return s
}
func (s *SqlSupplier) RoleSave(ctx context.Context, role *model.Role, hints ...store.LayeredStoreHint) (*model.Role, *model.AppError) {
func (s SqlRoleStore) CreateIndexesIfNotExists() {
}
func (s *SqlRoleStore) Save(role *model.Role) (*model.Role, *model.AppError) {
// Check the role is valid before proceeding.
if !role.IsValidWithoutId() {
return nil, model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.invalid_role.app_error", nil, "", http.StatusBadRequest)
@@ -91,7 +100,7 @@ func (s *SqlSupplier) RoleSave(ctx context.Context, role *model.Role, hints ...s
return nil, model.NewAppError("SqlRoleStore.RoleSave", "store.sql_role.save.open_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
}
defer finalizeTransaction(transaction)
createdRole, appErr := s.createRole(ctx, role, transaction, hints...)
createdRole, appErr := s.createRole(role, transaction)
if appErr != nil {
transaction.Rollback()
return nil, appErr
@@ -112,7 +121,7 @@ func (s *SqlSupplier) RoleSave(ctx context.Context, role *model.Role, hints ...s
return dbRole.ToModel(), nil
}
func (s *SqlSupplier) createRole(ctx context.Context, role *model.Role, transaction *gorp.Transaction, hints ...store.LayeredStoreHint) (*model.Role, *model.AppError) {
func (s *SqlRoleStore) createRole(role *model.Role, transaction *gorp.Transaction) (*model.Role, *model.AppError) {
// Check the role is valid before proceeding.
if !role.IsValidWithoutId() {
return nil, model.NewAppError("SqlRoleStore.Save", "store.sql_role.save.invalid_role.app_error", nil, "", http.StatusBadRequest)
@@ -131,7 +140,7 @@ func (s *SqlSupplier) createRole(ctx context.Context, role *model.Role, transact
return dbRole.ToModel(), nil
}
func (s *SqlSupplier) RoleGet(ctx context.Context, roleId string, hints ...store.LayeredStoreHint) (*model.Role, *model.AppError) {
func (s *SqlRoleStore) Get(roleId string) (*model.Role, *model.AppError) {
var dbRole Role
if err := s.GetReplica().SelectOne(&dbRole, "SELECT * from Roles WHERE Id = :Id", map[string]interface{}{"Id": roleId}); err != nil {
@@ -144,7 +153,7 @@ func (s *SqlSupplier) RoleGet(ctx context.Context, roleId string, hints ...store
return dbRole.ToModel(), nil
}
func (s *SqlSupplier) RoleGetAll(ctx context.Context, hints ...store.LayeredStoreHint) ([]*model.Role, *model.AppError) {
func (s *SqlRoleStore) GetAll() ([]*model.Role, *model.AppError) {
var dbRoles []Role
if _, err := s.GetReplica().Select(&dbRoles, "SELECT * from Roles", map[string]interface{}{}); err != nil {
@@ -161,7 +170,7 @@ func (s *SqlSupplier) RoleGetAll(ctx context.Context, hints ...store.LayeredStor
return roles, nil
}
func (s *SqlSupplier) RoleGetByName(ctx context.Context, name string, hints ...store.LayeredStoreHint) (*model.Role, *model.AppError) {
func (s *SqlRoleStore) GetByName(name string) (*model.Role, *model.AppError) {
var dbRole Role
if err := s.GetReplica().SelectOne(&dbRole, "SELECT * from Roles WHERE Name = :Name", map[string]interface{}{"Name": name}); err != nil {
@@ -174,7 +183,7 @@ func (s *SqlSupplier) RoleGetByName(ctx context.Context, name string, hints ...s
return dbRole.ToModel(), nil
}
func (s *SqlSupplier) RoleGetByNames(ctx context.Context, names []string, hints ...store.LayeredStoreHint) ([]*model.Role, *model.AppError) {
func (s *SqlRoleStore) GetByNames(names []string) ([]*model.Role, *model.AppError) {
var dbRoles []*Role
if len(names) == 0 {
@@ -202,7 +211,7 @@ func (s *SqlSupplier) RoleGetByNames(ctx context.Context, names []string, hints
return roles, nil
}
func (s *SqlSupplier) RoleDelete(ctx context.Context, roleId string, hints ...store.LayeredStoreHint) (*model.Role, *model.AppError) {
func (s *SqlRoleStore) Delete(roleId string) (*model.Role, *model.AppError) {
// Get the role.
var role *Role
if err := s.GetReplica().SelectOne(&role, "SELECT * from Roles WHERE Id = :Id", map[string]interface{}{"Id": roleId}); err != nil {
@@ -224,7 +233,7 @@ func (s *SqlSupplier) RoleDelete(ctx context.Context, roleId string, hints ...st
return role.ToModel(), nil
}
func (s *SqlSupplier) RolePermanentDeleteAll(ctx context.Context, hints ...store.LayeredStoreHint) *model.AppError {
func (s *SqlRoleStore) PermanentDeleteAll() *model.AppError {
if _, err := s.GetMaster().Exec("DELETE FROM Roles"); err != nil {
return model.NewAppError("SqlRoleStore.PermanentDeleteAll", "store.sql_role.permanent_delete_all.app_error", nil, err.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -4,7 +4,6 @@
package sqlstore
import (
"context"
"database/sql"
"fmt"
"net/http"
@@ -16,7 +15,13 @@ import (
"github.com/mattermost/mattermost-server/store"
)
func initSqlSupplierSchemes(sqlStore SqlStore) {
type SqlSchemeStore struct {
SqlStore
}
func NewSqlSchemeStore(sqlStore SqlStore) store.SchemeStore {
s := &SqlSchemeStore{sqlStore}
for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.Scheme{}, "Schemes").SetKeys(false, "Id")
table.ColMap("Id").SetMaxSize(26)
@@ -31,9 +36,14 @@ func initSqlSupplierSchemes(sqlStore SqlStore) {
table.ColMap("DefaultChannelUserRole").SetMaxSize(64)
table.ColMap("DefaultChannelGuestRole").SetMaxSize(64)
}
return s
}
func (s *SqlSupplier) SchemeSave(ctx context.Context, scheme *model.Scheme, hints ...store.LayeredStoreHint) (*model.Scheme, *model.AppError) {
func (s SqlSchemeStore) CreateIndexesIfNotExists() {
}
func (s *SqlSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, *model.AppError) {
if len(scheme.Id) == 0 {
transaction, err := s.GetMaster().Begin()
if err != nil {
@@ -41,7 +51,7 @@ func (s *SqlSupplier) SchemeSave(ctx context.Context, scheme *model.Scheme, hint
}
defer finalizeTransaction(transaction)
newScheme, appErr := s.createScheme(ctx, scheme, transaction, hints...)
newScheme, appErr := s.createScheme(scheme, transaction)
if appErr != nil {
return nil, appErr
}
@@ -68,11 +78,11 @@ func (s *SqlSupplier) SchemeSave(ctx context.Context, scheme *model.Scheme, hint
return scheme, nil
}
func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, transaction *gorp.Transaction, hints ...store.LayeredStoreHint) (*model.Scheme, *model.AppError) {
func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Transaction) (*model.Scheme, *model.AppError) {
// Fetch the default system scheme roles to populate default permissions.
defaultRoleNames := []string{model.TEAM_ADMIN_ROLE_ID, model.TEAM_USER_ROLE_ID, model.TEAM_GUEST_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_GUEST_ROLE_ID}
defaultRoles := make(map[string]*model.Role)
roles, err := s.RoleGetByNames(ctx, defaultRoleNames)
roles, err := s.SqlStore.Role().GetByNames(defaultRoleNames)
if err != nil {
return nil, err
}
@@ -108,7 +118,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
SchemeManaged: true,
}
savedRole, err := s.createRole(ctx, teamAdminRole, transaction)
savedRole, err := s.SqlStore.Role().(*SqlRoleStore).createRole(teamAdminRole, transaction)
if err != nil {
return nil, err
}
@@ -122,7 +132,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
SchemeManaged: true,
}
savedRole, err = s.createRole(ctx, teamUserRole, transaction)
savedRole, err = s.SqlStore.Role().(*SqlRoleStore).createRole(teamUserRole, transaction)
if err != nil {
return nil, err
}
@@ -136,7 +146,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
SchemeManaged: true,
}
savedRole, err = s.createRole(ctx, teamGuestRole, transaction)
savedRole, err = s.SqlStore.Role().(*SqlRoleStore).createRole(teamGuestRole, transaction)
if err != nil {
return nil, err
}
@@ -151,7 +161,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
SchemeManaged: true,
}
savedRole, err := s.createRole(ctx, channelAdminRole, transaction)
savedRole, err := s.SqlStore.Role().(*SqlRoleStore).createRole(channelAdminRole, transaction)
if err != nil {
return nil, err
}
@@ -165,7 +175,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
SchemeManaged: true,
}
savedRole, err = s.createRole(ctx, channelUserRole, transaction)
savedRole, err = s.SqlStore.Role().(*SqlRoleStore).createRole(channelUserRole, transaction)
if err != nil {
return nil, err
}
@@ -179,7 +189,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
SchemeManaged: true,
}
savedRole, err = s.createRole(ctx, channelGuestRole, transaction)
savedRole, err = s.SqlStore.Role().(*SqlRoleStore).createRole(channelGuestRole, transaction)
if err != nil {
return nil, err
}
@@ -205,7 +215,7 @@ func (s *SqlSupplier) createScheme(ctx context.Context, scheme *model.Scheme, tr
return scheme, nil
}
func (s *SqlSupplier) SchemeGet(ctx context.Context, schemeId string, hints ...store.LayeredStoreHint) (*model.Scheme, *model.AppError) {
func (s *SqlSchemeStore) Get(schemeId string) (*model.Scheme, *model.AppError) {
var scheme model.Scheme
if err := s.GetReplica().SelectOne(&scheme, "SELECT * from Schemes WHERE Id = :Id", map[string]interface{}{"Id": schemeId}); err != nil {
if err == sql.ErrNoRows {
@@ -217,7 +227,7 @@ func (s *SqlSupplier) SchemeGet(ctx context.Context, schemeId string, hints ...s
return &scheme, nil
}
func (s *SqlSupplier) SchemeGetByName(ctx context.Context, schemeName string, hints ...store.LayeredStoreHint) (*model.Scheme, *model.AppError) {
func (s *SqlSchemeStore) GetByName(schemeName string) (*model.Scheme, *model.AppError) {
var scheme model.Scheme
if err := s.GetReplica().SelectOne(&scheme, "SELECT * from Schemes WHERE Name = :Name", map[string]interface{}{"Name": schemeName}); err != nil {
@@ -230,7 +240,7 @@ func (s *SqlSupplier) SchemeGetByName(ctx context.Context, schemeName string, hi
return &scheme, nil
}
func (s *SqlSupplier) SchemeDelete(ctx context.Context, schemeId string, hints ...store.LayeredStoreHint) (*model.Scheme, *model.AppError) {
func (s *SqlSchemeStore) Delete(schemeId string) (*model.Scheme, *model.AppError) {
// Get the scheme
var scheme model.Scheme
if err := s.GetReplica().SelectOne(&scheme, "SELECT * from Schemes WHERE Id = :Id", map[string]interface{}{"Id": schemeId}); err != nil {
@@ -290,7 +300,7 @@ func (s *SqlSupplier) SchemeDelete(ctx context.Context, schemeId string, hints .
return &scheme, nil
}
func (s *SqlSupplier) SchemeGetAllPage(ctx context.Context, scope string, offset int, limit int, hints ...store.LayeredStoreHint) ([]*model.Scheme, *model.AppError) {
func (s *SqlSchemeStore) GetAllPage(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) {
var schemes []*model.Scheme
scopeClause := ""
@@ -305,7 +315,7 @@ func (s *SqlSupplier) SchemeGetAllPage(ctx context.Context, scope string, offset
return schemes, nil
}
func (s *SqlSupplier) SchemePermanentDeleteAll(ctx context.Context, hints ...store.LayeredStoreHint) *model.AppError {
func (s *SqlSchemeStore) PermanentDeleteAll() *model.AppError {
if _, err := s.GetMaster().Exec("DELETE from Schemes"); err != nil {
return model.NewAppError("SqlSchemeStore.PermanentDeleteAll", "store.sql_scheme.permanent_delete_all.app_error", nil, err.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -152,11 +152,10 @@ func NewSqlSupplier(settings model.SqlSettings, metrics einterfaces.MetricsInter
supplier.oldStores.UserTermsOfService = NewSqlUserTermsOfServiceStore(supplier)
supplier.oldStores.linkMetadata = NewSqlLinkMetadataStore(supplier)
supplier.oldStores.reaction = NewSqlReactionStore(supplier)
supplier.oldStores.role = NewSqlRoleStore(supplier)
supplier.oldStores.scheme = NewSqlSchemeStore(supplier)
supplier.oldStores.group = NewSqlGroupStore(supplier)
initSqlSupplierRoles(supplier)
initSqlSupplierSchemes(supplier)
err := supplier.GetMaster().CreateTablesIfNotExists()
if err != nil {
mlog.Critical("Error creating database tables.", mlog.Err(err))

Просмотреть файл

@@ -293,6 +293,8 @@ func (s SqlTeamStore) GetByName(name string) (*model.Team, *model.AppError) {
func (s SqlTeamStore) SearchAll(term string) ([]*model.Team, *model.AppError) {
var teams []*model.Team
term = sanitizeSearchTerm(term, "\\")
if _, err := s.GetReplica().Select(&teams, "SELECT * FROM Teams WHERE Name LIKE :Term OR DisplayName LIKE :Term", map[string]interface{}{"Term": term + "%"}); err != nil {
return nil, model.NewAppError("SqlTeamStore.SearchAll", "store.sql_team.search_all_team.app_error", nil, "term="+term+", "+err.Error(), http.StatusInternalServerError)
}
@@ -303,6 +305,8 @@ func (s SqlTeamStore) SearchAll(term string) ([]*model.Team, *model.AppError) {
func (s SqlTeamStore) SearchOpen(term string) ([]*model.Team, *model.AppError) {
var teams []*model.Team
term = sanitizeSearchTerm(term, "\\")
if _, err := s.GetReplica().Select(&teams, "SELECT * FROM Teams WHERE Type = 'O' AND AllowOpenInvite = true AND (Name LIKE :Term OR DisplayName LIKE :Term)", map[string]interface{}{"Term": term + "%"}); err != nil {
return nil, model.NewAppError("SqlTeamStore.SearchOpen", "store.sql_team.search_open_team.app_error", nil, "term="+term+", "+err.Error(), http.StatusInternalServerError)
}
@@ -313,6 +317,8 @@ func (s SqlTeamStore) SearchOpen(term string) ([]*model.Team, *model.AppError) {
func (s SqlTeamStore) SearchPrivate(term string) ([]*model.Team, *model.AppError) {
var teams []*model.Team
term = sanitizeSearchTerm(term, "\\")
query :=
`SELECT *
FROM

Просмотреть файл

@@ -20,6 +20,7 @@ import (
)
const (
CURRENT_SCHEMA_VERSION = VERSION_5_15_0
VERSION_5_16_0 = "5.16.0"
VERSION_5_15_0 = "5.15.0"
VERSION_5_14_0 = "5.14.0"

Просмотреть файл

@@ -6,7 +6,6 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/stretchr/testify/require"
)
@@ -36,25 +35,25 @@ func TestStoreUpgrade(t *testing.T) {
t.Run("upgrade from earliest supported version", func(t *testing.T) {
saveSchemaVersion(sqlStore, VERSION_3_0_0)
err := UpgradeDatabase(sqlStore, model.CurrentVersion)
err := UpgradeDatabase(sqlStore, CURRENT_SCHEMA_VERSION)
require.NoError(t, err)
require.Equal(t, model.CurrentVersion, sqlStore.GetCurrentSchemaVersion())
require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion())
})
t.Run("upgrade from no existing version", func(t *testing.T) {
saveSchemaVersion(sqlStore, "")
err := UpgradeDatabase(sqlStore, model.CurrentVersion)
err := UpgradeDatabase(sqlStore, CURRENT_SCHEMA_VERSION)
require.NoError(t, err)
require.Equal(t, model.CurrentVersion, sqlStore.GetCurrentSchemaVersion())
require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion())
})
t.Run("upgrade schema running earlier minor version", func(t *testing.T) {
saveSchemaVersion(sqlStore, "5.1.0")
err := UpgradeDatabase(sqlStore, "5.8.0")
require.NoError(t, err)
// Assert model.CurrentVersion, not 5.8.0, since the migrations will move
// Assert CURRENT_SCHEMA_VERSION, not 5.8.0, since the migrations will move
// past 5.8.0 regardless of the input parameter.
require.Equal(t, model.CurrentVersion, sqlStore.GetCurrentSchemaVersion())
require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion())
})
t.Run("upgrade schema running later minor version", func(t *testing.T) {
@@ -66,9 +65,9 @@ func TestStoreUpgrade(t *testing.T) {
t.Run("upgrade schema running earlier major version", func(t *testing.T) {
saveSchemaVersion(sqlStore, "4.1.0")
err := UpgradeDatabase(sqlStore, model.CurrentVersion)
err := UpgradeDatabase(sqlStore, CURRENT_SCHEMA_VERSION)
require.NoError(t, err)
require.Equal(t, model.CurrentVersion, sqlStore.GetCurrentSchemaVersion())
require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion())
})
t.Run("upgrade schema running later major version", func(t *testing.T) {
@@ -94,12 +93,12 @@ func TestSaveSchemaVersion(t *testing.T) {
})
t.Run("set current version", func(t *testing.T) {
saveSchemaVersion(sqlStore, model.CurrentVersion)
saveSchemaVersion(sqlStore, CURRENT_SCHEMA_VERSION)
props, err := ss.System().Get()
require.Nil(t, err)
require.Equal(t, model.CurrentVersion, props["Version"])
require.Equal(t, model.CurrentVersion, sqlStore.GetCurrentSchemaVersion())
require.Equal(t, CURRENT_SCHEMA_VERSION, props["Version"])
require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion())
})
})
}

Просмотреть файл

@@ -179,6 +179,7 @@ func (s SqlUserAccessTokenStore) GetByUser(userId string, offset, limit int) ([]
}
func (s SqlUserAccessTokenStore) Search(term string) ([]*model.UserAccessToken, *model.AppError) {
term = sanitizeSearchTerm(term, "\\")
tokens := []*model.UserAccessToken{}
params := map[string]interface{}{"Term": term + "%"}
query := `

Просмотреть файл

@@ -409,11 +409,13 @@ func applyRoleFilter(query sq.SelectBuilder, role string, isPostgreSQL bool) sq.
return query
}
roleParam := fmt.Sprintf("%%%s%%", role)
if isPostgreSQL {
roleParam := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(role, "\\"))
return query.Where("u.Roles LIKE LOWER(?)", roleParam)
}
roleParam := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(role, "*"))
return query.Where("u.Roles LIKE ? ESCAPE '*'", roleParam)
}
@@ -665,7 +667,8 @@ func (us SqlUserStore) GetProfilesNotInChannel(teamId string, channelId string,
return users, nil
}
func (us SqlUserStore) GetProfilesWithoutTeam(offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) {
func (us SqlUserStore) GetProfilesWithoutTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) {
isPostgreSQL := us.DriverName() == model.DATABASE_DRIVER_POSTGRES
query := us.usersQuery.
Where(`(
SELECT
@@ -677,9 +680,15 @@ func (us SqlUserStore) GetProfilesWithoutTeam(offset int, limit int, viewRestric
AND TeamMembers.DeleteAt = 0
) = 0`).
OrderBy("u.Username ASC").
Offset(uint64(offset)).Limit(uint64(limit))
Offset(uint64(options.Page * options.PerPage)).Limit(uint64(options.PerPage))
query = applyViewRestrictionsFilter(query, viewRestrictions, true)
query = applyViewRestrictionsFilter(query, options.ViewRestrictions, true)
query = applyRoleFilter(query, options.Role, isPostgreSQL)
if options.Inactive {
query = query.Where("u.DeleteAt != 0")
}
queryString, args, err := query.ToSql()
if err != nil {
@@ -1222,15 +1231,6 @@ func (us SqlUserStore) SearchInChannel(channelId string, term string, options *m
return us.performSearch(query, term, options)
}
var escapeLikeSearchChar = []string{
"%",
"_",
}
var ignoreLikeSearchChar = []string{
"*",
}
var spaceFulltextSearchChar = []string{
"<",
">",
@@ -1265,15 +1265,7 @@ func generateSearchQuery(query sq.SelectBuilder, terms []string, fields []string
}
func (us SqlUserStore) performSearch(query sq.SelectBuilder, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
// These chars must be removed from the like query.
for _, c := range ignoreLikeSearchChar {
term = strings.Replace(term, c, "", -1)
}
// These chars must be escaped in the like query.
for _, c := range escapeLikeSearchChar {
term = strings.Replace(term, c, "*"+c, -1)
}
term = sanitizeSearchTerm(term, "*")
searchType := USER_SEARCH_TYPE_NAMES_NO_FULL_NAME
if options.AllowEmails {

Просмотреть файл

@@ -8,11 +8,27 @@ import (
"database/sql"
"fmt"
"strconv"
"strings"
"github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/mlog"
)
var escapeLikeSearchChar = []string{
"%",
"_",
}
func sanitizeSearchTerm(term string, escapeChar string) string {
term = strings.Replace(term, escapeChar, "", -1)
for _, c := range escapeLikeSearchChar {
term = strings.Replace(term, c, escapeChar+c, -1)
}
return term
}
// Converts a list of strings into a list of query parameters and a named parameter map that can
// be used as part of a SQL query.
func MapStringsToQueryParams(list []string, paramPrefix string) (string, map[string]interface{}) {

Просмотреть файл

@@ -2,6 +2,8 @@ package sqlstore
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestMapStringsToQueryParams(t *testing.T) {
@@ -30,3 +32,29 @@ func TestMapStringsToQueryParams(t *testing.T) {
}
})
}
func TestSanitizeSearchTerm(t *testing.T) {
term := "test"
result := sanitizeSearchTerm(term, "\\")
require.Equal(t, result, term)
term = "%%%"
expected := "\\%\\%\\%"
result = sanitizeSearchTerm(term, "\\")
require.Equal(t, result, expected)
term = "%\\%\\%"
expected = "\\%\\%\\%"
result = sanitizeSearchTerm(term, "\\")
require.Equal(t, result, expected)
term = "%_test_%"
expected = "\\%\\_test\\_\\%"
result = sanitizeSearchTerm(term, "\\")
require.Equal(t, result, expected)
term = "**test_%"
expected = "test*_*%"
result = sanitizeSearchTerm(term, "*")
require.Equal(t, result, expected)
}