Migrates Channel.GetByName to sync by default (#11187)

* Channel.GetByName and Channel.GetByNameIncludedDeleted sync by default

* Suggested changes

* Fix some vars shadowing

* Rename of vars inside goroutine

* Shadow variable corrected
Этот коммит содержится в:
Rodrigo Villablanca Vásquez
2019-06-20 09:21:36 -04:00
коммит произвёл Jesús Espino
родитель 4494a56162
Коммит 59e7bf1c23
14 изменённых файлов: 165 добавлений и 143 удалений

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

@@ -74,37 +74,38 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin
var err *model.AppError var err *model.AppError
for _, channelName := range a.DefaultChannelNames() { for _, channelName := range a.DefaultChannelNames() {
if result := <-a.Srv.Store.Channel().GetByName(teamId, channelName, true); result.Err != nil { channel, channelErr := a.Srv.Store.Channel().GetByName(teamId, channelName, true)
err = result.Err if channelErr != nil {
} else { err = channelErr
channel := result.Data.(*model.Channel) continue
if channel.Type != model.CHANNEL_OPEN {
continue
}
cm := &model.ChannelMember{
ChannelId: channel.Id,
UserId: user.Id,
SchemeGuest: user.IsGuest(),
SchemeUser: !user.IsGuest(),
SchemeAdmin: shouldBeAdmin,
NotifyProps: model.GetDefaultChannelNotifyProps(),
}
if cmResult := <-a.Srv.Store.Channel().SaveMember(cm); cmResult.Err != nil {
err = cmResult.Err
}
if result = <-a.Srv.Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); result.Err != nil {
mlog.Warn(fmt.Sprintf("Failed to update ChannelMemberHistory table %v", result.Err))
}
if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages {
a.postJoinMessageForDefaultChannel(user, requestor, channel)
}
a.InvalidateCacheForChannelMembers(channel.Id)
} }
if channel.Type != model.CHANNEL_OPEN {
continue
}
cm := &model.ChannelMember{
ChannelId: channel.Id,
UserId: user.Id,
SchemeGuest: user.IsGuest(),
SchemeUser: !user.IsGuest(),
SchemeAdmin: shouldBeAdmin,
NotifyProps: model.GetDefaultChannelNotifyProps(),
}
if cmResult := <-a.Srv.Store.Channel().SaveMember(cm); cmResult.Err != nil {
err = cmResult.Err
}
if result := <-a.Srv.Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); result.Err != nil {
mlog.Warn(fmt.Sprintf("Failed to update ChannelMemberHistory table %v", result.Err))
}
if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages {
a.postJoinMessageForDefaultChannel(user, requestor, channel)
}
a.InvalidateCacheForChannelMembers(channel.Id)
} }
if a.IsESIndexingEnabled() { if a.IsESIndexingEnabled() {
@@ -280,10 +281,10 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan
} }
func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Channel, *model.AppError) { func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Channel, *model.AppError) {
result := <-a.Srv.Store.Channel().GetByName("", model.GetDMNameFromIds(userId, otherUserId), true) channel, err := a.Srv.Store.Channel().GetByName("", model.GetDMNameFromIds(userId, otherUserId), true)
if result.Err != nil { if err != nil {
if result.Err.Id == store.MISSING_CHANNEL_ERROR { if err.Id == store.MISSING_CHANNEL_ERROR {
channel, err := a.createDirectChannel(userId, otherUserId) channel, err = a.createDirectChannel(userId, otherUserId)
if err != nil { if err != nil {
if err.Id == store.CHANNEL_EXISTS_ERROR { if err.Id == store.CHANNEL_EXISTS_ERROR {
return channel, nil return channel, nil
@@ -309,8 +310,8 @@ func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Chann
if a.IsESIndexingEnabled() { if a.IsESIndexingEnabled() {
a.Srv.Go(func() { a.Srv.Go(func() {
for _, id := range []string{userId, otherUserId} { for _, id := range []string{userId, otherUserId} {
if err := a.indexUserFromId(id); err != nil { if indexUserErr := a.indexUserFromId(id); indexUserErr != nil {
mlog.Error("Encountered error indexing user", mlog.String("user_id", id), mlog.Err(err)) mlog.Error("Encountered error indexing user", mlog.String("user_id", id), mlog.Err(indexUserErr))
} }
} }
}) })
@@ -322,9 +323,9 @@ func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Chann
return channel, nil return channel, nil
} }
return nil, model.NewAppError("GetOrCreateDMChannel", "web.incoming_webhook.channel.app_error", nil, "err="+result.Err.Message, result.Err.StatusCode) return nil, model.NewAppError("GetOrCreateDMChannel", "web.incoming_webhook.channel.app_error", nil, "err="+err.Message, err.StatusCode)
} }
return result.Data.(*model.Channel), nil return channel, nil
} }
func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Channel, *model.AppError) { func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Channel, *model.AppError) {
@@ -1161,25 +1162,26 @@ func (a *App) GetChannel(channelId string) (*model.Channel, *model.AppError) {
} }
func (a *App) GetChannelByName(channelName, teamId string, includeDeleted bool) (*model.Channel, *model.AppError) { func (a *App) GetChannelByName(channelName, teamId string, includeDeleted bool) (*model.Channel, *model.AppError) {
var result store.StoreResult var channel *model.Channel
var err *model.AppError
if includeDeleted { if includeDeleted {
result = <-a.Srv.Store.Channel().GetByNameIncludeDeleted(teamId, channelName, false) channel, err = a.Srv.Store.Channel().GetByNameIncludeDeleted(teamId, channelName, false)
} else { } else {
result = <-a.Srv.Store.Channel().GetByName(teamId, channelName, false) channel, err = a.Srv.Store.Channel().GetByName(teamId, channelName, false)
} }
if result.Err != nil && result.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { if err != nil && err.Id == "store.sql_channel.get_by_name.missing.app_error" {
result.Err.StatusCode = http.StatusNotFound err.StatusCode = http.StatusNotFound
return nil, result.Err return nil, err
} }
if result.Err != nil { if err != nil {
result.Err.StatusCode = http.StatusBadRequest err.StatusCode = http.StatusBadRequest
return nil, result.Err return nil, err
} }
return result.Data.(*model.Channel), nil return channel, nil
} }
func (a *App) GetChannelsByNames(channelNames []string, teamId string) ([]*model.Channel, *model.AppError) { func (a *App) GetChannelsByNames(channelNames []string, teamId string) ([]*model.Channel, *model.AppError) {
@@ -1204,25 +1206,25 @@ func (a *App) GetChannelByNameForTeamName(channelName, teamName string, includeD
return nil, err return nil, err
} }
var result store.StoreResult var result *model.Channel
if includeDeleted { if includeDeleted {
result = <-a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, channelName, false) result, err = a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, channelName, false)
} else { } else {
result = <-a.Srv.Store.Channel().GetByName(team.Id, channelName, false) result, err = a.Srv.Store.Channel().GetByName(team.Id, channelName, false)
} }
if result.Err != nil && result.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { if err != nil && err.Id == "store.sql_channel.get_by_name.missing.app_error" {
result.Err.StatusCode = http.StatusNotFound err.StatusCode = http.StatusNotFound
return nil, result.Err return nil, err
} }
if result.Err != nil { if err != nil {
result.Err.StatusCode = http.StatusBadRequest err.StatusCode = http.StatusBadRequest
return nil, result.Err return nil, err
} }
return result.Data.(*model.Channel), nil return result, nil
} }
func (a *App) GetChannelsForUser(teamId string, userId string, includeDeleted bool) (*model.ChannelList, *model.AppError) { func (a *App) GetChannelsForUser(teamId string, userId string, includeDeleted bool) (*model.ChannelList, *model.AppError) {

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

@@ -162,7 +162,9 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi
defer th.TearDown() defer th.TearDown()
// figure out the initial number of users in town square // figure out the initial number of users in town square
townSquareChannelId := store.Must(th.App.Srv.Store.Channel().GetByName(th.BasicTeam.Id, "town-square", true)).(*model.Channel).Id channel, err := th.App.Srv.Store.Channel().GetByName(th.BasicTeam.Id, "town-square", true)
require.Nil(t, err)
townSquareChannelId := channel.Id
initialNumTownSquareUsers := len(store.Must(th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId)).([]*model.ChannelMemberHistoryResult)) initialNumTownSquareUsers := len(store.Must(th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId)).([]*model.ChannelMemberHistoryResult))
// create a new user that joins the default channels // create a new user that joins the default channels
@@ -188,7 +190,9 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing
defer th.TearDown() defer th.TearDown()
// figure out the initial number of users in off-topic // figure out the initial number of users in off-topic
offTopicChannelId := store.Must(th.App.Srv.Store.Channel().GetByName(th.BasicTeam.Id, "off-topic", true)).(*model.Channel).Id channel, err := th.App.Srv.Store.Channel().GetByName(th.BasicTeam.Id, "off-topic", true)
require.Nil(t, err)
offTopicChannelId := channel.Id
initialNumTownSquareUsers := len(store.Must(th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId)).([]*model.ChannelMemberHistoryResult)) initialNumTownSquareUsers := len(store.Must(th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId)).([]*model.ChannelMemberHistoryResult))
// create a new user that joins the default channels // create a new user that joins the default channels
@@ -453,7 +457,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) {
assert.Equal(t, groupUserIds, channelMemberHistoryUserIds) assert.Equal(t, groupUserIds, channelMemberHistoryUserIds)
postList, err := th.App.Srv.Store.Post().GetPosts(channel.Id, 0, 1, false) postList, err := th.App.Srv.Store.Post().GetPosts(channel.Id, 0, 1, false)
require.Nil(t,err) require.Nil(t, err)
if assert.Len(t, postList.Order, 1) { if assert.Len(t, postList.Order, 1) {
post := postList.Posts[postList.Order[0]] post := postList.Posts[postList.Order[0]]

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

@@ -43,13 +43,11 @@ func (me *JoinProvider) DoCommand(a *App, args *model.CommandArgs, message strin
channelName = message[1:] channelName = message[1:]
} }
result := <-a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true) channel, err := a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true)
if result.Err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
channel := result.Data.(*model.Channel)
if channel.Name != channelName { if channel.Name != channelName {
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_join.missing.app_error")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_join.missing.app_error")}
} }
@@ -67,7 +65,7 @@ func (me *JoinProvider) DoCommand(a *App, args *model.CommandArgs, message strin
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if err := a.JoinChannel(channel, args.UserId); err != nil { if err = a.JoinChannel(channel, args.UserId); err != nil {
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -64,8 +64,8 @@ func (me *msgProvider) DoCommand(a *App, args *model.CommandArgs, message string
channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id) channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id)
targetChannelId := "" targetChannelId := ""
if channel := <-a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil { if channel, channelErr := a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channelErr != nil {
if channel.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { if channelErr.Id == "store.sql_channel.get_by_name.missing.app_error" {
if !a.SessionHasPermissionTo(args.Session, model.PERMISSION_CREATE_DIRECT_CHANNEL) { if !a.SessionHasPermissionTo(args.Session, model.PERMISSION_CREATE_DIRECT_CHANNEL) {
return &model.CommandResponse{Text: args.T("api.command_msg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_msg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
@@ -77,11 +77,10 @@ func (me *msgProvider) DoCommand(a *App, args *model.CommandArgs, message string
targetChannelId = directChannel.Id targetChannelId = directChannel.Id
} }
} else { } else {
mlog.Error(channel.Err.Error()) mlog.Error(channelErr.Error())
return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
} else { } else {
channel := channel.Data.(*model.Channel)
targetChannelId = channel.Id targetChannelId = channel.Id
} }

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

@@ -53,13 +53,11 @@ func (me *MuteProvider) DoCommand(a *App, args *model.CommandArgs, message strin
} }
if len(channelName) > 0 && len(message) > 0 { if len(channelName) > 0 && len(message) > 0 {
data := (<-a.Srv.Store.Channel().GetByName(channel.TeamId, channelName, true)).Data channel, _ = a.Srv.Store.Channel().GetByName(channel.TeamId, channelName, true)
if data == nil { if channel == nil {
return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
channel = data.(*model.Channel)
} }
channelMember := a.ToggleMuteChannel(channel.Id, args.UserId) channelMember := a.ToggleMuteChannel(channel.Id, args.UserId)

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

@@ -226,8 +226,8 @@ func (a *App) ImportChannel(data *ChannelImportData, dryRun bool) *model.AppErro
} }
var channel *model.Channel var channel *model.Channel
if result := <-a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); result.Err == nil { if result, err := a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); err == nil {
channel = result.Data.(*model.Channel) channel = result
} else { } else {
channel = &model.Channel{} channel = &model.Channel{}
} }
@@ -946,13 +946,12 @@ func (a *App) ImportPost(data *PostImportData, dryRun bool) *model.AppError {
return model.NewAppError("BulkImport", "app.import.import_post.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, err.Error(), http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.import_post.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, err.Error(), http.StatusBadRequest)
} }
result := <-a.Srv.Store.Channel().GetByName(team.Id, *data.Channel, false) channel, err := a.Srv.Store.Channel().GetByName(team.Id, *data.Channel, false)
if result.Err != nil { if err != nil {
return model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]interface{}{"ChannelName": *data.Channel}, result.Err.Error(), http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]interface{}{"ChannelName": *data.Channel}, err.Error(), http.StatusBadRequest)
} }
channel := result.Data.(*model.Channel)
result = <-a.Srv.Store.User().GetByUsername(*data.User) result := <-a.Srv.Store.User().GetByUsername(*data.User)
if result.Err != nil { if result.Err != nil {
return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": *data.User}, result.Err.Error(), http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": *data.User}, result.Err.Error(), http.StatusBadRequest)
} }

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

@@ -506,9 +506,9 @@ func (a *App) SlackAddChannels(teamId string, slackchannels []SlackChannel, post
newChannel = SlackSanitiseChannelProperties(newChannel) newChannel = SlackSanitiseChannelProperties(newChannel)
var mChannel *model.Channel var mChannel *model.Channel
if result := <-a.Srv.Store.Channel().GetByName(teamId, sChannel.Name, true); result.Err == nil { var err *model.AppError
if mChannel, err = a.Srv.Store.Channel().GetByName(teamId, sChannel.Name, true); err == nil {
// The channel already exists as an active channel. Merge with the existing one. // The channel already exists as an active channel. Merge with the existing one.
mChannel = result.Data.(*model.Channel)
importerLog.WriteString(utils.T("api.slackimport.slack_add_channels.merge", map[string]interface{}{"DisplayName": newChannel.DisplayName})) importerLog.WriteString(utils.T("api.slackimport.slack_add_channels.merge", map[string]interface{}{"DisplayName": newChannel.DisplayName}))
} else if result := <-a.Srv.Store.Channel().GetDeletedByName(teamId, sChannel.Name); result.Err == nil { } else if result := <-a.Srv.Store.Channel().GetDeletedByName(teamId, sChannel.Name); result.Err == nil {
// The channel already exists but has been deleted. Generate a random string for the handle instead. // The channel already exists but has been deleted. Generate a random string for the handle instead.

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

@@ -834,17 +834,16 @@ func (a *App) LeaveTeam(team *model.Team, user *model.User, requestorId string)
for _, channel := range *channelList { for _, channel := range *channelList {
if !channel.IsGroupOrDirect() { if !channel.IsGroupOrDirect() {
a.InvalidateCacheForChannelMembers(channel.Id) a.InvalidateCacheForChannelMembers(channel.Id)
if err := a.Srv.Store.Channel().RemoveMember(channel.Id, user.Id); err != nil { if err = a.Srv.Store.Channel().RemoveMember(channel.Id, user.Id); err != nil {
return err return err
} }
} }
} }
result := <-a.Srv.Store.Channel().GetByName(team.Id, model.DEFAULT_CHANNEL, false) channel, err := a.Srv.Store.Channel().GetByName(team.Id, model.DEFAULT_CHANNEL, false)
if result.Err != nil { if err != nil {
return result.Err return err
} }
channel := result.Data.(*model.Channel)
if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages {
if requestorId == user.Id { if requestorId == user.Id {

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

@@ -599,9 +599,19 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq
} }
} }
} else if channelName[0] == '#' { } else if channelName[0] == '#' {
cchan = a.Srv.Store.Channel().GetByName(hook.TeamId, channelName[1:], true) cchan = make(store.StoreChannel, 1)
go func() {
chnn, chnnErr := a.Srv.Store.Channel().GetByName(hook.TeamId, channelName[1:], true)
cchan <- store.StoreResult{Data: chnn, Err: chnnErr}
close(cchan)
}()
} else { } else {
cchan = a.Srv.Store.Channel().GetByName(hook.TeamId, channelName, true) cchan = make(store.StoreChannel, 1)
go func() {
chnn, chnnErr := a.Srv.Store.Channel().GetByName(hook.TeamId, channelName, true)
cchan <- store.StoreResult{Data: chnn, Err: chnnErr}
close(cchan)
}()
} }
} else { } else {
var err *model.AppError var err *model.AppError

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

@@ -43,10 +43,10 @@ func getChannelFromChannelArg(a *app.App, channelArg string) *model.Channel {
return nil return nil
} }
if result := <-a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, channelPart, true); result.Err == nil { if result, err := a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, channelPart, true); err == nil {
channel = result.Data.(*model.Channel) channel = result
} else { } else {
fmt.Println(result.Err.Error()) fmt.Println(err.Error())
} }
} }

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

@@ -1139,7 +1139,7 @@ func (s SqlChannelStore) GetTeamChannels(teamId string) (*model.ChannelList, *mo
return data, nil return data, nil
} }
func (s SqlChannelStore) GetByName(teamId string, name string, allowFromCache bool) store.StoreChannel { func (s SqlChannelStore) GetByName(teamId string, name string, allowFromCache bool) (*model.Channel, *model.AppError) {
return s.getByName(teamId, name, false, allowFromCache) return s.getByName(teamId, name, false, allowFromCache)
} }
@@ -1199,45 +1199,40 @@ func (s SqlChannelStore) GetByNames(teamId string, names []string, allowFromCach
return channels, nil return channels, nil
} }
func (s SqlChannelStore) GetByNameIncludeDeleted(teamId string, name string, allowFromCache bool) store.StoreChannel { func (s SqlChannelStore) GetByNameIncludeDeleted(teamId string, name string, allowFromCache bool) (*model.Channel, *model.AppError) {
return s.getByName(teamId, name, true, allowFromCache) return s.getByName(teamId, name, true, allowFromCache)
} }
func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bool, allowFromCache bool) store.StoreChannel { func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bool, allowFromCache bool) (*model.Channel, *model.AppError) {
var query string var query string
if includeDeleted { if includeDeleted {
query = "SELECT * FROM Channels WHERE (TeamId = :TeamId OR TeamId = '') AND Name = :Name" query = "SELECT * FROM Channels WHERE (TeamId = :TeamId OR TeamId = '') AND Name = :Name"
} else { } else {
query = "SELECT * FROM Channels WHERE (TeamId = :TeamId OR TeamId = '') AND Name = :Name AND DeleteAt = 0" query = "SELECT * FROM Channels WHERE (TeamId = :TeamId OR TeamId = '') AND Name = :Name AND DeleteAt = 0"
} }
return store.Do(func(result *store.StoreResult) { channel := model.Channel{}
channel := model.Channel{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := channelByNameCache.Get(teamId + name); ok { if cacheItem, ok := channelByNameCache.Get(teamId + name); ok {
if s.metrics != nil {
s.metrics.IncrementMemCacheHitCounter("Channel By Name")
}
result.Data = cacheItem.(*model.Channel)
return
}
if s.metrics != nil { if s.metrics != nil {
s.metrics.IncrementMemCacheMissCounter("Channel By Name") s.metrics.IncrementMemCacheHitCounter("Channel By Name")
} }
return cacheItem.(*model.Channel), nil
} }
if s.metrics != nil {
if err := s.GetReplica().SelectOne(&channel, query, map[string]interface{}{"TeamId": teamId, "Name": name}); err != nil { s.metrics.IncrementMemCacheMissCounter("Channel By Name")
if err == sql.ErrNoRows {
result.Err = model.NewAppError("SqlChannelStore.GetByName", store.MISSING_CHANNEL_ERROR, nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusNotFound)
return
}
result.Err = model.NewAppError("SqlChannelStore.GetByName", "store.sql_channel.get_by_name.existing.app_error", nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusInternalServerError)
return
} }
}
result.Data = &channel if err := s.GetReplica().SelectOne(&channel, query, map[string]interface{}{"TeamId": teamId, "Name": name}); err != nil {
channelByNameCache.AddWithExpiresInSecs(teamId+name, &channel, CHANNEL_CACHE_SEC) if err == sql.ErrNoRows {
}) return nil, model.NewAppError("SqlChannelStore.GetByName", store.MISSING_CHANNEL_ERROR, nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusNotFound)
}
return nil, model.NewAppError("SqlChannelStore.GetByName", "store.sql_channel.get_by_name.existing.app_error", nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusInternalServerError)
}
channelByNameCache.AddWithExpiresInSecs(teamId+name, &channel, CHANNEL_CACHE_SEC)
return &channel, nil
} }
func (s SqlChannelStore) GetDeletedByName(teamId string, name string) store.StoreChannel { func (s SqlChannelStore) GetDeletedByName(teamId string, name string) store.StoreChannel {

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

@@ -142,9 +142,9 @@ type ChannelStore interface {
SetDeleteAt(channelId string, deleteAt int64, updateAt int64) *model.AppError SetDeleteAt(channelId string, deleteAt int64, updateAt int64) *model.AppError
PermanentDeleteByTeam(teamId string) StoreChannel PermanentDeleteByTeam(teamId string) StoreChannel
PermanentDelete(channelId string) StoreChannel PermanentDelete(channelId string) StoreChannel
GetByName(team_id string, name string, allowFromCache bool) StoreChannel GetByName(team_id string, name string, allowFromCache bool) (*model.Channel, *model.AppError)
GetByNames(team_id string, names []string, allowFromCache bool) ([]*model.Channel, *model.AppError) GetByNames(team_id string, names []string, allowFromCache bool) ([]*model.Channel, *model.AppError)
GetByNameIncludeDeleted(team_id string, name string, allowFromCache bool) StoreChannel GetByNameIncludeDeleted(team_id string, name string, allowFromCache bool) (*model.Channel, *model.AppError)
GetDeletedByName(team_id string, name string) StoreChannel GetDeletedByName(team_id string, name string) StoreChannel
GetDeleted(team_id string, offset int, limit int) (*model.ChannelList, *model.AppError) GetDeleted(team_id string, offset int, limit int) (*model.ChannelList, *model.AppError)
GetChannels(teamId string, userId string, includeDeleted bool) (*model.ChannelList, *model.AppError) GetChannels(teamId string, userId string, includeDeleted bool) (*model.ChannelList, *model.AppError)

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

@@ -659,27 +659,27 @@ func testChannelStoreGetByName(t *testing.T, ss store.Store) {
_, err := ss.Channel().Save(&o1, -1) _, err := ss.Channel().Save(&o1, -1)
require.Nil(t, err) require.Nil(t, err)
result := <-ss.Channel().GetByName(o1.TeamId, o1.Name, true) result, err := ss.Channel().GetByName(o1.TeamId, o1.Name, true)
require.Nil(t, result.Err) require.Nil(t, err)
require.Equal(t, o1.ToJson(), result.Data.(*model.Channel).ToJson(), "invalid returned channel") require.Equal(t, o1.ToJson(), result.ToJson(), "invalid returned channel")
channelID := result.Data.(*model.Channel).Id channelID := result.Id
result = <-ss.Channel().GetByName(o1.TeamId, "", true) result, err = ss.Channel().GetByName(o1.TeamId, "", true)
require.NotNil(t, result.Err, "Missing id should have failed") require.NotNil(t, err, "Missing id should have failed")
result = <-ss.Channel().GetByName(o1.TeamId, o1.Name, false) result, err = ss.Channel().GetByName(o1.TeamId, o1.Name, false)
require.Nil(t, result.Err) require.Nil(t, err)
require.Equal(t, o1.ToJson(), result.Data.(*model.Channel).ToJson(), "invalid returned channel") require.Equal(t, o1.ToJson(), result.ToJson(), "invalid returned channel")
result = <-ss.Channel().GetByName(o1.TeamId, "", false) result, err = ss.Channel().GetByName(o1.TeamId, "", false)
require.NotNil(t, result.Err, "Missing id should have failed") require.NotNil(t, err, "Missing id should have failed")
err = ss.Channel().Delete(channelID, model.GetMillis()) err = ss.Channel().Delete(channelID, model.GetMillis())
require.Nil(t, err, "channel should have been deleted") require.Nil(t, err, "channel should have been deleted")
result = <-ss.Channel().GetByName(o1.TeamId, o1.Name, false) result, err = ss.Channel().GetByName(o1.TeamId, o1.Name, false)
require.NotNil(t, result.Err, "Deleted channel should not be returned by GetByName()") require.NotNil(t, err, "Deleted channel should not be returned by GetByName()")
} }
func testChannelStoreGetByNames(t *testing.T, ss store.Store) { func testChannelStoreGetByNames(t *testing.T, ss store.Store) {

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

@@ -311,35 +311,53 @@ func (_m *ChannelStore) GetAllDirectChannelsForExportAfter(limit int, afterId st
} }
// GetByName provides a mock function with given fields: team_id, name, allowFromCache // GetByName provides a mock function with given fields: team_id, name, allowFromCache
func (_m *ChannelStore) GetByName(team_id string, name string, allowFromCache bool) store.StoreChannel { func (_m *ChannelStore) GetByName(team_id string, name string, allowFromCache bool) (*model.Channel, *model.AppError) {
ret := _m.Called(team_id, name, allowFromCache) ret := _m.Called(team_id, name, allowFromCache)
var r0 store.StoreChannel var r0 *model.Channel
if rf, ok := ret.Get(0).(func(string, string, bool) store.StoreChannel); ok { if rf, ok := ret.Get(0).(func(string, string, bool) *model.Channel); ok {
r0 = rf(team_id, name, allowFromCache) r0 = rf(team_id, name, allowFromCache)
} else { } else {
if ret.Get(0) != nil { if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel) r0 = ret.Get(0).(*model.Channel)
} }
} }
return r0 var r1 *model.AppError
if rf, ok := ret.Get(1).(func(string, string, bool) *model.AppError); ok {
r1 = rf(team_id, name, allowFromCache)
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).(*model.AppError)
}
}
return r0, r1
} }
// GetByNameIncludeDeleted provides a mock function with given fields: team_id, name, allowFromCache // GetByNameIncludeDeleted provides a mock function with given fields: team_id, name, allowFromCache
func (_m *ChannelStore) GetByNameIncludeDeleted(team_id string, name string, allowFromCache bool) store.StoreChannel { func (_m *ChannelStore) GetByNameIncludeDeleted(team_id string, name string, allowFromCache bool) (*model.Channel, *model.AppError) {
ret := _m.Called(team_id, name, allowFromCache) ret := _m.Called(team_id, name, allowFromCache)
var r0 store.StoreChannel var r0 *model.Channel
if rf, ok := ret.Get(0).(func(string, string, bool) store.StoreChannel); ok { if rf, ok := ret.Get(0).(func(string, string, bool) *model.Channel); ok {
r0 = rf(team_id, name, allowFromCache) r0 = rf(team_id, name, allowFromCache)
} else { } else {
if ret.Get(0) != nil { if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel) r0 = ret.Get(0).(*model.Channel)
} }
} }
return r0 var r1 *model.AppError
if rf, ok := ret.Get(1).(func(string, string, bool) *model.AppError); ok {
r1 = rf(team_id, name, allowFromCache)
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).(*model.AppError)
}
}
return r0, r1
} }
// GetByNames provides a mock function with given fields: team_id, names, allowFromCache // GetByNames provides a mock function with given fields: team_id, names, allowFromCache