Move sql store code into store/sqlstore package (#7502)

* move sql store code into store/sqlstore package

* move non-sql constants back up to store

* fix api test

* derp
Этот коммит содержится в:
Chris
2017-09-25 09:11:25 -05:00
коммит произвёл Joram Wilander
родитель b2c5b97601
Коммит 49fe5fbf3d
58 изменённых файлов: 2770 добавлений и 2699 удалений

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

@@ -349,7 +349,7 @@ test-postgres:
@sed -i'' -e 's|"DriverName": "mysql"|"DriverName": "postgres"|g' config/config.json @sed -i'' -e 's|"DriverName": "mysql"|"DriverName": "postgres"|g' config/config.json
@sed -i'' -e 's|"DataSource": "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8"|"DataSource": "postgres://mmuser:mostest@dockerhost:5432?sslmode=disable"|g' config/config.json @sed -i'' -e 's|"DataSource": "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8"|"DataSource": "postgres://mmuser:mostest@dockerhost:5432?sslmode=disable"|g' config/config.json
$(GO) test $(GOFLAGS) -run=$(TESTS) -test.v -test.timeout=2000s -covermode=count -coverprofile=cprofile.out -coverpkg=$(ALL_PACKAGES_COMMA) github.com/mattermost/mattermost-server/store || exit 1; \ $(GO) test $(GOFLAGS) -run=$(TESTS) -test.v -test.timeout=2000s -covermode=count -coverprofile=cprofile.out -coverpkg=$(ALL_PACKAGES_COMMA) github.com/mattermost/mattermost-server/store/sqlstore || exit 1; \
if [ -f cprofile.out ]; then \ if [ -f cprofile.out ]; then \
tail -n +2 cprofile.out >> cover.out; \ tail -n +2 cprofile.out >> cover.out; \
rm cprofile.out; \ rm cprofile.out; \

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

@@ -11,6 +11,7 @@ import (
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/sqlstore"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -393,7 +394,7 @@ func TestUpdateChannel(t *testing.T) {
utils.SetDefaultRolesBasedOnConfig() utils.SetDefaultRolesBasedOnConfig()
MakeUserChannelUser(th.BasicUser, channel2) MakeUserChannelUser(th.BasicUser, channel2)
MakeUserChannelUser(th.BasicUser, channel3) MakeUserChannelUser(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.UpdateChannel(channel2); err == nil { if _, err := Client.UpdateChannel(channel2); err == nil {
t.Fatal("should have errored not channel admin") t.Fatal("should have errored not channel admin")
@@ -415,7 +416,7 @@ func TestUpdateChannel(t *testing.T) {
MakeUserChannelAdmin(th.BasicUser, channel2) MakeUserChannelAdmin(th.BasicUser, channel2)
MakeUserChannelAdmin(th.BasicUser, channel3) MakeUserChannelAdmin(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.UpdateChannel(channel2); err != nil { if _, err := Client.UpdateChannel(channel2); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -629,7 +630,7 @@ func TestUpdateChannelHeader(t *testing.T) {
utils.SetDefaultRolesBasedOnConfig() utils.SetDefaultRolesBasedOnConfig()
MakeUserChannelUser(th.BasicUser, channel2) MakeUserChannelUser(th.BasicUser, channel2)
MakeUserChannelUser(th.BasicUser, channel3) MakeUserChannelUser(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.UpdateChannelHeader(data2); err == nil { if _, err := Client.UpdateChannelHeader(data2); err == nil {
t.Fatal("should have errored not channel admin") t.Fatal("should have errored not channel admin")
@@ -640,7 +641,7 @@ func TestUpdateChannelHeader(t *testing.T) {
MakeUserChannelAdmin(th.BasicUser, channel2) MakeUserChannelAdmin(th.BasicUser, channel2)
MakeUserChannelAdmin(th.BasicUser, channel3) MakeUserChannelAdmin(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.UpdateChannelHeader(data2); err != nil { if _, err := Client.UpdateChannelHeader(data2); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -811,7 +812,7 @@ func TestUpdateChannelPurpose(t *testing.T) {
utils.SetDefaultRolesBasedOnConfig() utils.SetDefaultRolesBasedOnConfig()
MakeUserChannelUser(th.BasicUser, channel2) MakeUserChannelUser(th.BasicUser, channel2)
MakeUserChannelUser(th.BasicUser, channel3) MakeUserChannelUser(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.UpdateChannelPurpose(data2); err == nil { if _, err := Client.UpdateChannelPurpose(data2); err == nil {
t.Fatal("should have errored not channel admin") t.Fatal("should have errored not channel admin")
@@ -822,7 +823,7 @@ func TestUpdateChannelPurpose(t *testing.T) {
MakeUserChannelAdmin(th.BasicUser, channel2) MakeUserChannelAdmin(th.BasicUser, channel2)
MakeUserChannelAdmin(th.BasicUser, channel3) MakeUserChannelAdmin(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.UpdateChannelPurpose(data2); err != nil { if _, err := Client.UpdateChannelPurpose(data2); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -1386,7 +1387,7 @@ func TestDeleteChannel(t *testing.T) {
MakeUserChannelAdmin(th.BasicUser, channel2) MakeUserChannelAdmin(th.BasicUser, channel2)
MakeUserChannelAdmin(th.BasicUser, channel3) MakeUserChannelAdmin(th.BasicUser, channel3)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
if _, err := Client.DeleteChannel(channel2.Id); err != nil { if _, err := Client.DeleteChannel(channel2.Id); err != nil {
t.Fatal(err) t.Fatal(err)

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

@@ -12,7 +12,7 @@ import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store/sqlstore"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -936,7 +936,7 @@ func TestDeleteChannel(t *testing.T) {
// successful delete by channel admin // successful delete by channel admin
MakeUserChannelAdmin(user, publicChannel6) MakeUserChannelAdmin(user, publicChannel6)
MakeUserChannelAdmin(user, privateChannel7) MakeUserChannelAdmin(user, privateChannel7)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
_, resp = Client.DeleteChannel(publicChannel6.Id) _, resp = Client.DeleteChannel(publicChannel6.Id)
CheckNoError(t, resp) CheckNoError(t, resp)
@@ -990,7 +990,7 @@ func TestDeleteChannel(t *testing.T) {
// // cannot delete by channel admin // // cannot delete by channel admin
MakeUserChannelAdmin(user, publicChannel6) MakeUserChannelAdmin(user, publicChannel6)
MakeUserChannelAdmin(user, privateChannel7) MakeUserChannelAdmin(user, privateChannel7)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
_, resp = Client.DeleteChannel(publicChannel6.Id) _, resp = Client.DeleteChannel(publicChannel6.Id)
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
@@ -1032,7 +1032,7 @@ func TestDeleteChannel(t *testing.T) {
// cannot delete by channel admin // cannot delete by channel admin
MakeUserChannelAdmin(user, publicChannel6) MakeUserChannelAdmin(user, publicChannel6)
MakeUserChannelAdmin(user, privateChannel7) MakeUserChannelAdmin(user, privateChannel7)
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
_, resp = Client.DeleteChannel(publicChannel6.Id) _, resp = Client.DeleteChannel(publicChannel6.Id)
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)

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

@@ -17,6 +17,7 @@ import (
"github.com/mattermost/mattermost-server/jobs" "github.com/mattermost/mattermost-server/jobs"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/sqlstore"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -117,10 +118,10 @@ func (a *App) InvalidateAllCachesSkipSend() {
l4g.Info(utils.T("api.context.invalidate_all_caches")) l4g.Info(utils.T("api.context.invalidate_all_caches"))
sessionCache.Purge() sessionCache.Purge()
ClearStatusCache() ClearStatusCache()
store.ClearChannelCaches() sqlstore.ClearChannelCaches()
store.ClearUserCaches() sqlstore.ClearUserCaches()
store.ClearPostCaches() sqlstore.ClearPostCaches()
store.ClearWebhookCaches() sqlstore.ClearWebhookCaches()
a.LoadLicense() a.LoadLicense()
} }
@@ -187,7 +188,7 @@ func (a *App) RecycleDatabaseConnection() {
oldStore := a.Srv.Store oldStore := a.Srv.Store
l4g.Warn(utils.T("api.admin.recycle_db_start.warn")) l4g.Warn(utils.T("api.admin.recycle_db_start.warn"))
a.Srv.Store = store.NewLayeredStore(a.Metrics, a.Cluster) a.Srv.Store = store.NewLayeredStore(sqlstore.NewSqlSupplier(a.Metrics), a.Metrics, a.Cluster)
jobs.Srv.Store = a.Srv.Store jobs.Srv.Store = a.Srv.Store

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

@@ -20,6 +20,7 @@ import (
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/sqlstore"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -84,7 +85,7 @@ func (a *App) NewServer() {
} }
func (a *App) InitStores() { func (a *App) InitStores() {
a.Srv.Store = store.NewLayeredStore(a.Metrics, a.Cluster) a.Srv.Store = store.NewLayeredStore(sqlstore.NewSqlSupplier(a.Metrics), a.Metrics, a.Cluster)
} }
type VaryBy struct{} type VaryBy struct{}

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

@@ -10,6 +10,7 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/jobs" "github.com/mattermost/mattermost-server/jobs"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/sqlstore"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -36,7 +37,7 @@ func jobserverCmdF(cmd *cobra.Command, args []string) {
} }
defer l4g.Close() defer l4g.Close()
jobs.Srv.Store = store.NewLayeredStore(a.Metrics, a.Cluster) jobs.Srv.Store = store.NewLayeredStore(sqlstore.NewSqlSupplier(a.Metrics), a.Metrics, a.Cluster)
defer jobs.Srv.Store.Close() defer jobs.Srv.Store.Close()
jobs.Srv.LoadLicense() jobs.Srv.LoadLicense()

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

@@ -6,6 +6,7 @@ import (
"github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/sqlstore"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -32,5 +33,7 @@ func printVersion(a *app.App) {
CommandPrintln("Build Date: " + model.BuildDate) CommandPrintln("Build Date: " + model.BuildDate)
CommandPrintln("Build Hash: " + model.BuildHash) CommandPrintln("Build Hash: " + model.BuildHash)
CommandPrintln("Build Enterprise Ready: " + model.BuildEnterpriseReady) CommandPrintln("Build Enterprise Ready: " + model.BuildEnterpriseReady)
CommandPrintln("DB Version: " + a.Srv.Store.(*store.LayeredStore).DatabaseLayer.GetCurrentSchemaVersion()) if supplier, ok := a.Srv.Store.(*store.LayeredStore).DatabaseLayer.(*sqlstore.SqlSupplier); ok {
CommandPrintln("DB Version: " + supplier.GetCurrentSchemaVersion())
}
} }

15
store/constants.go Обычный файл
Просмотреть файл

@@ -0,0 +1,15 @@
package store
const (
MISSING_CHANNEL_ERROR = "store.sql_channel.get_by_name.missing.app_error"
MISSING_CHANNEL_MEMBER_ERROR = "store.sql_channel.get_member.missing.app_error"
CHANNEL_EXISTS_ERROR = "store.sql_channel.save_channel.exists.app_error"
MISSING_ACCOUNT_ERROR = "store.sql_user.missing_account.const"
MISSING_AUTH_ACCOUNT_ERROR = "store.sql_user.get_by_auth.missing_account.app_error"
USER_SEARCH_OPTION_NAMES_ONLY = "names_only"
USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME = "names_only_no_full_name"
USER_SEARCH_OPTION_ALL_NO_FULL_NAME = "all_no_full_name"
USER_SEARCH_OPTION_ALLOW_INACTIVE = "allow_inactive"
)

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

@@ -15,19 +15,24 @@ const (
ENABLE_EXPERIMENTAL_REDIS = false ENABLE_EXPERIMENTAL_REDIS = false
) )
type LayeredStoreDatabaseLayer interface {
LayeredStoreSupplier
Store
}
type LayeredStore struct { type LayeredStore struct {
TmpContext context.Context TmpContext context.Context
ReactionStore ReactionStore ReactionStore ReactionStore
DatabaseLayer *SqlSupplier DatabaseLayer LayeredStoreDatabaseLayer
LocalCacheLayer *LocalCacheSupplier LocalCacheLayer *LocalCacheSupplier
RedisLayer *RedisSupplier RedisLayer *RedisSupplier
LayerChainHead LayeredStoreSupplier LayerChainHead LayeredStoreSupplier
} }
func NewLayeredStore(metrics einterfaces.MetricsInterface, cluster einterfaces.ClusterInterface) Store { func NewLayeredStore(db LayeredStoreDatabaseLayer, metrics einterfaces.MetricsInterface, cluster einterfaces.ClusterInterface) Store {
store := &LayeredStore{ store := &LayeredStore{
TmpContext: context.TODO(), TmpContext: context.TODO(),
DatabaseLayer: NewSqlSupplier(metrics), DatabaseLayer: db,
LocalCacheLayer: NewLocalCacheSupplier(metrics, cluster), LocalCacheLayer: NewLocalCacheSupplier(metrics, cluster),
} }

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

@@ -1,40 +0,0 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package store
import (
"testing"
"github.com/mattermost/mattermost-server/model"
)
func TestStoreUpgrade(t *testing.T) {
Setup()
saveSchemaVersion(store.(*LayeredStore).DatabaseLayer, VERSION_3_0_0)
UpgradeDatabase(store.(*LayeredStore).DatabaseLayer)
saveSchemaVersion(store.(*LayeredStore).DatabaseLayer, "")
UpgradeDatabase(store.(*LayeredStore).DatabaseLayer)
}
func TestSaveSchemaVersion(t *testing.T) {
Setup()
saveSchemaVersion(store.(*LayeredStore).DatabaseLayer, VERSION_3_0_0)
if result := <-store.System().Get(); result.Err != nil {
t.Fatal(result.Err)
} else {
props := result.Data.(model.StringMap)
if props["Version"] != VERSION_3_0_0 {
t.Fatal("version not updated")
}
}
if store.(*LayeredStore).DatabaseLayer.GetCurrentSchemaVersion() != VERSION_3_0_0 {
t.Fatal("version not updated")
}
saveSchemaVersion(store.(*LayeredStore).DatabaseLayer, model.CurrentVersion)
}

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

@@ -1,12 +1,13 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -14,7 +15,7 @@ type SqlAuditStore struct {
SqlStore SqlStore
} }
func NewSqlAuditStore(sqlStore SqlStore) AuditStore { func NewSqlAuditStore(sqlStore SqlStore) store.AuditStore {
s := &SqlAuditStore{sqlStore} s := &SqlAuditStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -34,12 +35,12 @@ func (s SqlAuditStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_audits_user_id", "Audits", "UserId") s.CreateIndexIfNotExists("idx_audits_user_id", "Audits", "UserId")
} }
func (s SqlAuditStore) Save(audit *model.Audit) StoreChannel { func (s SqlAuditStore) Save(audit *model.Audit) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
audit.Id = model.NewId() audit.Id = model.NewId()
audit.CreateAt = model.GetMillis() audit.CreateAt = model.GetMillis()
@@ -55,12 +56,12 @@ func (s SqlAuditStore) Save(audit *model.Audit) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlAuditStore) Get(user_id string, offset int, limit int) StoreChannel { func (s SqlAuditStore) Get(user_id string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if limit > 1000 { if limit > 1000 {
limit = 1000 limit = 1000
@@ -92,12 +93,12 @@ func (s SqlAuditStore) Get(user_id string, offset int, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlAuditStore) PermanentDeleteByUser(userId string) StoreChannel { func (s SqlAuditStore) PermanentDeleteByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM Audits WHERE UserId = :userId", if _, err := s.GetMaster().Exec("DELETE FROM Audits WHERE UserId = :userId",
map[string]interface{}{"userId": userId}); err != nil { map[string]interface{}{"userId": userId}); err != nil {
@@ -111,11 +112,11 @@ func (s SqlAuditStore) PermanentDeleteByUser(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlAuditStore) PermanentDeleteBatch(endTime int64, limit int64) StoreChannel { func (s SqlAuditStore) PermanentDeleteBatch(endTime int64, limit int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var query string var query string
if *utils.Cfg.SqlSettings.DriverName == "postgres" { if *utils.Cfg.SqlSettings.DriverName == "postgres" {

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

@@ -1,32 +1,33 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"time" "time"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestSqlAuditStore(t *testing.T) { func TestSqlAuditStore(t *testing.T) {
Setup() ss := Setup()
audit := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"} audit := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"}
Must(store.Audit().Save(audit)) store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
Must(store.Audit().Save(audit)) store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
Must(store.Audit().Save(audit)) store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
audit.ExtraInfo = "extra" audit.ExtraInfo = "extra"
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
Must(store.Audit().Save(audit)) store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
c := store.Audit().Get(audit.UserId, 0, 100) c := ss.Audit().Get(audit.UserId, 0, 100)
result := <-c result := <-c
audits := result.Data.(model.Audits) audits := result.Data.(model.Audits)
@@ -38,7 +39,7 @@ func TestSqlAuditStore(t *testing.T) {
t.Fatal("Failed to save property for extra info") t.Fatal("Failed to save property for extra info")
} }
c = store.Audit().Get("missing", 0, 100) c = ss.Audit().Get("missing", 0, 100)
result = <-c result = <-c
audits = result.Data.(model.Audits) audits = result.Data.(model.Audits)
@@ -46,7 +47,7 @@ func TestSqlAuditStore(t *testing.T) {
t.Fatal("Should have returned empty because user_id is missing") t.Fatal("Should have returned empty because user_id is missing")
} }
c = store.Audit().Get("", 0, 100) c = ss.Audit().Get("", 0, 100)
result = <-c result = <-c
audits = result.Data.(model.Audits) audits = result.Data.(model.Audits)
@@ -54,36 +55,36 @@ func TestSqlAuditStore(t *testing.T) {
t.Fatal("Failed to save and retrieve 4 audit logs") t.Fatal("Failed to save and retrieve 4 audit logs")
} }
if r2 := <-store.Audit().PermanentDeleteByUser(audit.UserId); r2.Err != nil { if r2 := <-ss.Audit().PermanentDeleteByUser(audit.UserId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
} }
func TestAuditStorePermanentDeleteBatch(t *testing.T) { func TestAuditStorePermanentDeleteBatch(t *testing.T) {
Setup() ss := Setup()
a1 := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"} a1 := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"}
Must(store.Audit().Save(a1)) store.Must(ss.Audit().Save(a1))
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
a2 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"} a2 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"}
Must(store.Audit().Save(a2)) store.Must(ss.Audit().Save(a2))
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
cutoff := model.GetMillis() cutoff := model.GetMillis()
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
a3 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"} a3 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"}
Must(store.Audit().Save(a3)) store.Must(ss.Audit().Save(a3))
if r := <-store.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 3 { if r := <-ss.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 3 {
t.Fatal("Expected 3 audits. Got ", len(r.Data.(model.Audits))) t.Fatal("Expected 3 audits. Got ", len(r.Data.(model.Audits)))
} }
Must(store.Audit().PermanentDeleteBatch(cutoff, 1000000)) store.Must(ss.Audit().PermanentDeleteBatch(cutoff, 1000000))
if r := <-store.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 1 { if r := <-ss.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 1 {
t.Fatal("Expected 1 audit. Got ", len(r.Data.(model.Audits))) t.Fatal("Expected 1 audit. Got ", len(r.Data.(model.Audits)))
} }
if r2 := <-store.Audit().PermanentDeleteByUser(a1.UserId); r2.Err != nil { if r2 := <-ss.Audit().PermanentDeleteByUser(a1.UserId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -14,14 +14,11 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
const ( const (
MISSING_CHANNEL_ERROR = "store.sql_channel.get_by_name.missing.app_error"
MISSING_CHANNEL_MEMBER_ERROR = "store.sql_channel.get_member.missing.app_error"
CHANNEL_EXISTS_ERROR = "store.sql_channel.save_channel.exists.app_error"
ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_SIZE = model.SESSION_CACHE_SIZE ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_SIZE = model.SESSION_CACHE_SIZE
ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_SEC = 900 // 15 mins ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_SEC = 900 // 15 mins
@@ -53,7 +50,7 @@ func ClearChannelCaches() {
channelByNameCache.Purge() channelByNameCache.Purge()
} }
func NewSqlChannelStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) ChannelStore { func NewSqlChannelStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.ChannelStore {
s := &SqlChannelStore{ s := &SqlChannelStore{
SqlStore: sqlStore, SqlStore: sqlStore,
metrics: metrics, metrics: metrics,
@@ -94,11 +91,11 @@ func (s SqlChannelStore) CreateIndexesIfNotExists() {
s.CreateFullTextIndexIfNotExists("idx_channels_txt", "Channels", "Name, DisplayName") s.CreateFullTextIndexIfNotExists("idx_channels_txt", "Channels", "Name, DisplayName")
} }
func (s SqlChannelStore) Save(channel *model.Channel) StoreChannel { func (s SqlChannelStore) Save(channel *model.Channel) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
var result StoreResult var result store.StoreResult
if channel.Type == model.CHANNEL_DIRECT { if channel.Type == model.CHANNEL_DIRECT {
result.Err = model.NewAppError("SqlChannelStore.Save", "store.sql_channel.save.direct_channel.app_error", nil, "", http.StatusBadRequest) result.Err = model.NewAppError("SqlChannelStore.Save", "store.sql_channel.save.direct_channel.app_error", nil, "", http.StatusBadRequest)
} else { } else {
@@ -123,7 +120,7 @@ func (s SqlChannelStore) Save(channel *model.Channel) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) CreateDirectChannel(userId string, otherUserId string) StoreChannel { func (s SqlChannelStore) CreateDirectChannel(userId string, otherUserId string) store.StoreChannel {
channel := new(model.Channel) channel := new(model.Channel)
channel.DisplayName = "" channel.DisplayName = ""
@@ -146,11 +143,11 @@ func (s SqlChannelStore) CreateDirectChannel(userId string, otherUserId string)
return s.SaveDirectChannel(channel, cm1, cm2) return s.SaveDirectChannel(channel, cm1, cm2)
} }
func (s SqlChannelStore) SaveDirectChannel(directchannel *model.Channel, member1 *model.ChannelMember, member2 *model.ChannelMember) StoreChannel { func (s SqlChannelStore) SaveDirectChannel(directchannel *model.Channel, member1 *model.ChannelMember, member2 *model.ChannelMember) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
var result StoreResult var result store.StoreResult
if directchannel.Type != model.CHANNEL_DIRECT { if directchannel.Type != model.CHANNEL_DIRECT {
result.Err = model.NewAppError("SqlChannelStore.SaveDirectChannel", "store.sql_channel.save_direct_channel.not_direct.app_error", nil, "", http.StatusBadRequest) result.Err = model.NewAppError("SqlChannelStore.SaveDirectChannel", "store.sql_channel.save_direct_channel.not_direct.app_error", nil, "", http.StatusBadRequest)
@@ -202,8 +199,8 @@ func (s SqlChannelStore) SaveDirectChannel(directchannel *model.Channel, member1
return storeChannel return storeChannel
} }
func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel) StoreResult { func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if len(channel.Id) > 0 { if len(channel.Id) > 0 {
result.Err = model.NewAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.existing.app_error", nil, "id="+channel.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.existing.app_error", nil, "id="+channel.Id, http.StatusBadRequest)
@@ -232,7 +229,7 @@ func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *mo
if dupChannel.DeleteAt > 0 { if dupChannel.DeleteAt > 0 {
result.Err = model.NewAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.previously.app_error", nil, "id="+channel.Id+", "+err.Error(), http.StatusBadRequest) result.Err = model.NewAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.previously.app_error", nil, "id="+channel.Id+", "+err.Error(), http.StatusBadRequest)
} else { } else {
result.Err = model.NewAppError("SqlChannelStore.Save", CHANNEL_EXISTS_ERROR, nil, "id="+channel.Id+", "+err.Error(), http.StatusBadRequest) result.Err = model.NewAppError("SqlChannelStore.Save", store.CHANNEL_EXISTS_ERROR, nil, "id="+channel.Id+", "+err.Error(), http.StatusBadRequest)
result.Data = &dupChannel result.Data = &dupChannel
} }
} else { } else {
@@ -245,12 +242,12 @@ func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *mo
return result return result
} }
func (s SqlChannelStore) Update(channel *model.Channel) StoreChannel { func (s SqlChannelStore) Update(channel *model.Channel) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
channel.PreUpdate() channel.PreUpdate()
@@ -285,11 +282,11 @@ func (s SqlChannelStore) Update(channel *model.Channel) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) extraUpdated(channel *model.Channel) StoreChannel { func (s SqlChannelStore) extraUpdated(channel *model.Channel) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
channel.ExtraUpdated() channel.ExtraUpdated()
@@ -313,11 +310,11 @@ func (s SqlChannelStore) extraUpdated(channel *model.Channel) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetChannelUnread(channelId, userId string) StoreChannel { func (s SqlChannelStore) GetChannelUnread(channelId, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var unreadChannel model.ChannelUnread var unreadChannel model.ChannelUnread
err := s.GetReplica().SelectOne(&unreadChannel, err := s.GetReplica().SelectOne(&unreadChannel,
@@ -356,15 +353,15 @@ func (us SqlChannelStore) InvalidateChannelByName(teamId, name string) {
channelByNameCache.Remove(teamId + name) channelByNameCache.Remove(teamId + name)
} }
func (s SqlChannelStore) Get(id string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) Get(id string, allowFromCache bool) store.StoreChannel {
return s.get(id, false, allowFromCache) return s.get(id, false, allowFromCache)
} }
func (s SqlChannelStore) GetPinnedPosts(channelId string) StoreChannel { func (s SqlChannelStore) GetPinnedPosts(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
pl := model.NewPostList() pl := model.NewPostList()
var posts []*model.Post var posts []*model.Post
@@ -386,15 +383,15 @@ func (s SqlChannelStore) GetPinnedPosts(channelId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetFromMaster(id string) StoreChannel { func (s SqlChannelStore) GetFromMaster(id string) store.StoreChannel {
return s.get(id, true, false) return s.get(id, true, false)
} }
func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) StoreChannel { func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var db *gorp.DbMap var db *gorp.DbMap
if master { if master {
@@ -439,19 +436,19 @@ func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) StoreC
return storeChannel return storeChannel
} }
func (s SqlChannelStore) Delete(channelId string, time int64) StoreChannel { func (s SqlChannelStore) Delete(channelId string, time int64) store.StoreChannel {
return s.SetDeleteAt(channelId, time, time) return s.SetDeleteAt(channelId, time, time)
} }
func (s SqlChannelStore) Restore(channelId string, time int64) StoreChannel { func (s SqlChannelStore) Restore(channelId string, time int64) store.StoreChannel {
return s.SetDeleteAt(channelId, 0, time) return s.SetDeleteAt(channelId, 0, time)
} }
func (s SqlChannelStore) SetDeleteAt(channelId string, deleteAt int64, updateAt int64) StoreChannel { func (s SqlChannelStore) SetDeleteAt(channelId string, deleteAt int64, updateAt int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("Update Channels SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :ChannelId", map[string]interface{}{"DeleteAt": deleteAt, "UpdateAt": updateAt, "ChannelId": channelId}) _, err := s.GetMaster().Exec("Update Channels SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :ChannelId", map[string]interface{}{"DeleteAt": deleteAt, "UpdateAt": updateAt, "ChannelId": channelId})
if err != nil { if err != nil {
@@ -465,11 +462,11 @@ func (s SqlChannelStore) SetDeleteAt(channelId string, deleteAt int64, updateAt
return storeChannel return storeChannel
} }
func (s SqlChannelStore) PermanentDeleteByTeam(teamId string) StoreChannel { func (s SqlChannelStore) PermanentDeleteByTeam(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM Channels WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId}); err != nil { if _, err := s.GetMaster().Exec("DELETE FROM Channels WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId}); err != nil {
result.Err = model.NewAppError("SqlChannelStore.PermanentDeleteByTeam", "store.sql_channel.permanent_delete_by_team.app_error", nil, "teamId="+teamId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlChannelStore.PermanentDeleteByTeam", "store.sql_channel.permanent_delete_by_team.app_error", nil, "teamId="+teamId+", "+err.Error(), http.StatusInternalServerError)
@@ -482,11 +479,11 @@ func (s SqlChannelStore) PermanentDeleteByTeam(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) PermanentDelete(channelId string) StoreChannel { func (s SqlChannelStore) PermanentDelete(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM Channels WHERE Id = :ChannelId", map[string]interface{}{"ChannelId": channelId}); err != nil { if _, err := s.GetMaster().Exec("DELETE FROM Channels WHERE Id = :ChannelId", map[string]interface{}{"ChannelId": channelId}); err != nil {
result.Err = model.NewAppError("SqlChannelStore.PermanentDelete", "store.sql_channel.permanent_delete.app_error", nil, "channel_id="+channelId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlChannelStore.PermanentDelete", "store.sql_channel.permanent_delete.app_error", nil, "channel_id="+channelId+", "+err.Error(), http.StatusInternalServerError)
@@ -499,11 +496,11 @@ func (s SqlChannelStore) PermanentDelete(channelId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) PermanentDeleteMembersByChannel(channelId string) StoreChannel { func (s SqlChannelStore) PermanentDeleteMembersByChannel(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM ChannelMembers WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId}) _, err := s.GetMaster().Exec("DELETE FROM ChannelMembers WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId})
if err != nil { if err != nil {
@@ -522,11 +519,11 @@ type channelWithMember struct {
model.ChannelMember model.ChannelMember
} }
func (s SqlChannelStore) GetChannels(teamId string, userId string) StoreChannel { func (s SqlChannelStore) GetChannels(teamId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
data := &model.ChannelList{} data := &model.ChannelList{}
_, err := s.GetReplica().Select(data, "SELECT Channels.* FROM Channels, ChannelMembers WHERE Id = ChannelId AND UserId = :UserId AND DeleteAt = 0 AND (TeamId = :TeamId OR TeamId = '') ORDER BY DisplayName", map[string]interface{}{"TeamId": teamId, "UserId": userId}) _, err := s.GetReplica().Select(data, "SELECT Channels.* FROM Channels, ChannelMembers WHERE Id = ChannelId AND UserId = :UserId AND DeleteAt = 0 AND (TeamId = :TeamId OR TeamId = '') ORDER BY DisplayName", map[string]interface{}{"TeamId": teamId, "UserId": userId})
@@ -548,11 +545,11 @@ func (s SqlChannelStore) GetChannels(teamId string, userId string) StoreChannel
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetMoreChannels(teamId string, userId string, offset int, limit int) StoreChannel { func (s SqlChannelStore) GetMoreChannels(teamId string, userId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
data := &model.ChannelList{} data := &model.ChannelList{}
_, err := s.GetReplica().Select(data, _, err := s.GetReplica().Select(data,
@@ -592,11 +589,11 @@ func (s SqlChannelStore) GetMoreChannels(teamId string, userId string, offset in
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetPublicChannelsForTeam(teamId string, offset int, limit int) StoreChannel { func (s SqlChannelStore) GetPublicChannelsForTeam(teamId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
data := &model.ChannelList{} data := &model.ChannelList{}
_, err := s.GetReplica().Select(data, _, err := s.GetReplica().Select(data,
@@ -626,11 +623,11 @@ func (s SqlChannelStore) GetPublicChannelsForTeam(teamId string, offset int, lim
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) StoreChannel { func (s SqlChannelStore) GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
props := make(map[string]interface{}) props := make(map[string]interface{})
props["teamId"] = teamId props["teamId"] = teamId
@@ -682,11 +679,11 @@ type channelIdWithCountAndUpdateAt struct {
UpdateAt int64 UpdateAt int64
} }
func (s SqlChannelStore) GetChannelCounts(teamId string, userId string) StoreChannel { func (s SqlChannelStore) GetChannelCounts(teamId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []channelIdWithCountAndUpdateAt var data []channelIdWithCountAndUpdateAt
_, err := s.GetReplica().Select(&data, "SELECT Id, TotalMsgCount, UpdateAt FROM Channels WHERE Id IN (SELECT ChannelId FROM ChannelMembers WHERE UserId = :UserId) AND (TeamId = :TeamId OR TeamId = '') AND DeleteAt = 0 ORDER BY DisplayName", map[string]interface{}{"TeamId": teamId, "UserId": userId}) _, err := s.GetReplica().Select(&data, "SELECT Id, TotalMsgCount, UpdateAt FROM Channels WHERE Id IN (SELECT ChannelId FROM ChannelMembers WHERE UserId = :UserId) AND (TeamId = :TeamId OR TeamId = '') AND DeleteAt = 0 ORDER BY DisplayName", map[string]interface{}{"TeamId": teamId, "UserId": userId})
@@ -711,11 +708,11 @@ func (s SqlChannelStore) GetChannelCounts(teamId string, userId string) StoreCha
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetTeamChannels(teamId string) StoreChannel { func (s SqlChannelStore) GetTeamChannels(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
data := &model.ChannelList{} data := &model.ChannelList{}
_, err := s.GetReplica().Select(data, "SELECT * FROM Channels WHERE TeamId = :TeamId And Type != 'D' ORDER BY DisplayName", map[string]interface{}{"TeamId": teamId}) _, err := s.GetReplica().Select(data, "SELECT * FROM Channels WHERE TeamId = :TeamId And Type != 'D' ORDER BY DisplayName", map[string]interface{}{"TeamId": teamId})
@@ -737,16 +734,16 @@ func (s SqlChannelStore) GetTeamChannels(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetByName(teamId string, name string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) GetByName(teamId string, name string, allowFromCache bool) store.StoreChannel {
return s.getByName(teamId, name, false, allowFromCache) return s.getByName(teamId, name, false, allowFromCache)
} }
func (s SqlChannelStore) GetByNameIncludeDeleted(teamId string, name string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) GetByNameIncludeDeleted(teamId string, name string, allowFromCache bool) store.StoreChannel {
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) StoreChannel { func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bool, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
var query string var query string
if includeDeleted { if includeDeleted {
@@ -756,7 +753,7 @@ func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bo
} }
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
channel := model.Channel{} channel := model.Channel{}
@@ -777,7 +774,7 @@ func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bo
} }
if err := s.GetReplica().SelectOne(&channel, query, map[string]interface{}{"TeamId": teamId, "Name": name}); err != nil { if err := s.GetReplica().SelectOne(&channel, query, map[string]interface{}{"TeamId": teamId, "Name": name}); err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
result.Err = model.NewAppError("SqlChannelStore.GetByName", MISSING_CHANNEL_ERROR, nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusNotFound) result.Err = model.NewAppError("SqlChannelStore.GetByName", store.MISSING_CHANNEL_ERROR, nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusNotFound)
} else { } else {
result.Err = model.NewAppError("SqlChannelStore.GetByName", "store.sql_channel.get_by_name.existing.app_error", nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlChannelStore.GetByName", "store.sql_channel.get_by_name.existing.app_error", nil, "teamId="+teamId+", "+"name="+name+", "+err.Error(), http.StatusInternalServerError)
} }
@@ -793,11 +790,11 @@ func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bo
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetDeletedByName(teamId string, name string) StoreChannel { func (s SqlChannelStore) GetDeletedByName(teamId string, name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
channel := model.Channel{} channel := model.Channel{}
@@ -818,11 +815,11 @@ func (s SqlChannelStore) GetDeletedByName(teamId string, name string) StoreChann
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetDeleted(teamId string, offset int, limit int) StoreChannel { func (s SqlChannelStore) GetDeleted(teamId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
channels := &model.ChannelList{} channels := &model.ChannelList{}
@@ -843,11 +840,11 @@ func (s SqlChannelStore) GetDeleted(teamId string, offset int, limit int) StoreC
return storeChannel return storeChannel
} }
func (s SqlChannelStore) SaveMember(member *model.ChannelMember) StoreChannel { func (s SqlChannelStore) SaveMember(member *model.ChannelMember) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
var result StoreResult var result store.StoreResult
// Grab the channel we are saving this member to // Grab the channel we are saving this member to
if cr := <-s.GetFromMaster(member.ChannelId); cr.Err != nil { if cr := <-s.GetFromMaster(member.ChannelId); cr.Err != nil {
result.Err = cr.Err result.Err = cr.Err
@@ -881,8 +878,8 @@ func (s SqlChannelStore) SaveMember(member *model.ChannelMember) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) saveMemberT(transaction *gorp.Transaction, member *model.ChannelMember, channel *model.Channel) StoreResult { func (s SqlChannelStore) saveMemberT(transaction *gorp.Transaction, member *model.ChannelMember, channel *model.Channel) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
member.PreSave() member.PreSave()
if result.Err = member.IsValid(); result.Err != nil { if result.Err = member.IsValid(); result.Err != nil {
@@ -902,11 +899,11 @@ func (s SqlChannelStore) saveMemberT(transaction *gorp.Transaction, member *mode
return result return result
} }
func (s SqlChannelStore) UpdateMember(member *model.ChannelMember) StoreChannel { func (s SqlChannelStore) UpdateMember(member *model.ChannelMember) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
member.PreUpdate() member.PreUpdate()
@@ -929,11 +926,11 @@ func (s SqlChannelStore) UpdateMember(member *model.ChannelMember) StoreChannel
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetMembers(channelId string, offset, limit int) StoreChannel { func (s SqlChannelStore) GetMembers(channelId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var members model.ChannelMembers var members model.ChannelMembers
_, err := s.GetReplica().Select(&members, "SELECT * FROM ChannelMembers WHERE ChannelId = :ChannelId LIMIT :Limit OFFSET :Offset", map[string]interface{}{"ChannelId": channelId, "Limit": limit, "Offset": offset}) _, err := s.GetReplica().Select(&members, "SELECT * FROM ChannelMembers WHERE ChannelId = :ChannelId LIMIT :Limit OFFSET :Offset", map[string]interface{}{"ChannelId": channelId, "Limit": limit, "Offset": offset})
@@ -950,17 +947,17 @@ func (s SqlChannelStore) GetMembers(channelId string, offset, limit int) StoreCh
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetMember(channelId string, userId string) StoreChannel { func (s SqlChannelStore) GetMember(channelId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var member model.ChannelMember var member model.ChannelMember
if err := s.GetReplica().SelectOne(&member, "SELECT * FROM ChannelMembers WHERE ChannelId = :ChannelId AND UserId = :UserId", map[string]interface{}{"ChannelId": channelId, "UserId": userId}); err != nil { if err := s.GetReplica().SelectOne(&member, "SELECT * FROM ChannelMembers WHERE ChannelId = :ChannelId AND UserId = :UserId", map[string]interface{}{"ChannelId": channelId, "UserId": userId}); err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
result.Err = model.NewAppError("SqlChannelStore.GetMember", MISSING_CHANNEL_MEMBER_ERROR, nil, "channel_id="+channelId+"user_id="+userId+","+err.Error(), http.StatusNotFound) result.Err = model.NewAppError("SqlChannelStore.GetMember", store.MISSING_CHANNEL_MEMBER_ERROR, nil, "channel_id="+channelId+"user_id="+userId+","+err.Error(), http.StatusNotFound)
} else { } else {
result.Err = model.NewAppError("SqlChannelStore.GetMember", "store.sql_channel.get_member.app_error", nil, "channel_id="+channelId+"user_id="+userId+","+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlChannelStore.GetMember", "store.sql_channel.get_member.app_error", nil, "channel_id="+channelId+"user_id="+userId+","+err.Error(), http.StatusInternalServerError)
} }
@@ -1009,11 +1006,11 @@ func (us SqlChannelStore) IsUserInChannelUseCache(userId string, channelId strin
} }
} }
func (s SqlChannelStore) GetMemberForPost(postId string, userId string) StoreChannel { func (s SqlChannelStore) GetMemberForPost(postId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
member := &model.ChannelMember{} member := &model.ChannelMember{}
if err := s.GetReplica().SelectOne( if err := s.GetReplica().SelectOne(
@@ -1044,11 +1041,11 @@ type allChannelMember struct {
Roles string Roles string
} }
func (s SqlChannelStore) GetAllChannelMembersForUser(userId string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) GetAllChannelMembersForUser(userId string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok { if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok {
@@ -1105,11 +1102,11 @@ type allChannelMemberNotifyProps struct {
NotifyProps model.StringMap NotifyProps model.StringMap
} }
func (s SqlChannelStore) GetAllChannelMembersNotifyPropsForChannel(channelId string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) GetAllChannelMembersNotifyPropsForChannel(channelId string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := allChannelMembersNotifyPropsForChannelCache.Get(channelId); ok { if cacheItem, ok := allChannelMembersNotifyPropsForChannelCache.Get(channelId); ok {
@@ -1181,11 +1178,11 @@ func (s SqlChannelStore) GetMemberCountFromCache(channelId string) int64 {
} }
} }
func (s SqlChannelStore) GetMemberCount(channelId string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) GetMemberCount(channelId string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok { if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok {
@@ -1234,11 +1231,11 @@ func (s SqlChannelStore) GetMemberCount(channelId string, allowFromCache bool) S
return storeChannel return storeChannel
} }
func (s SqlChannelStore) RemoveMember(channelId string, userId string) StoreChannel { func (s SqlChannelStore) RemoveMember(channelId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
// Grab the channel we are saving this member to // Grab the channel we are saving this member to
if cr := <-s.Get(channelId, true); cr.Err != nil { if cr := <-s.Get(channelId, true); cr.Err != nil {
@@ -1264,11 +1261,11 @@ func (s SqlChannelStore) RemoveMember(channelId string, userId string) StoreChan
return storeChannel return storeChannel
} }
func (s SqlChannelStore) PermanentDeleteMembersByUser(userId string) StoreChannel { func (s SqlChannelStore) PermanentDeleteMembersByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM ChannelMembers WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}); err != nil { if _, err := s.GetMaster().Exec("DELETE FROM ChannelMembers WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlChannelStore.RemoveMember", "store.sql_channel.permanent_delete_members_by_user.app_error", nil, "user_id="+userId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlChannelStore.RemoveMember", "store.sql_channel.permanent_delete_members_by_user.app_error", nil, "user_id="+userId+", "+err.Error(), http.StatusInternalServerError)
@@ -1281,11 +1278,11 @@ func (s SqlChannelStore) PermanentDeleteMembersByUser(userId string) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlChannelStore) UpdateLastViewedAt(channelIds []string, userId string) StoreChannel { func (s SqlChannelStore) UpdateLastViewedAt(channelIds []string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var query string var query string
props := make(map[string]interface{}) props := make(map[string]interface{})
@@ -1342,11 +1339,11 @@ func (s SqlChannelStore) UpdateLastViewedAt(channelIds []string, userId string)
return storeChannel return storeChannel
} }
func (s SqlChannelStore) IncrementMentionCount(channelId string, userId string) StoreChannel { func (s SqlChannelStore) IncrementMentionCount(channelId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec( _, err := s.GetMaster().Exec(
`UPDATE `UPDATE
@@ -1369,11 +1366,11 @@ func (s SqlChannelStore) IncrementMentionCount(channelId string, userId string)
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetAll(teamId string) StoreChannel { func (s SqlChannelStore) GetAll(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.Channel var data []*model.Channel
_, err := s.GetReplica().Select(&data, "SELECT * FROM Channels WHERE TeamId = :TeamId AND Type != 'D' ORDER BY Name", map[string]interface{}{"TeamId": teamId}) _, err := s.GetReplica().Select(&data, "SELECT * FROM Channels WHERE TeamId = :TeamId AND Type != 'D' ORDER BY Name", map[string]interface{}{"TeamId": teamId})
@@ -1391,11 +1388,11 @@ func (s SqlChannelStore) GetAll(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetForPost(postId string) StoreChannel { func (s SqlChannelStore) GetForPost(postId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
channel := &model.Channel{} channel := &model.Channel{}
if err := s.GetReplica().SelectOne( if err := s.GetReplica().SelectOne(
@@ -1420,11 +1417,11 @@ func (s SqlChannelStore) GetForPost(postId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) StoreChannel { func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType" query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType"
@@ -1446,11 +1443,11 @@ func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) S
return storeChannel return storeChannel
} }
func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType string) StoreChannel { func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType AND DeleteAt > 0" query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType AND DeleteAt > 0"
@@ -1472,11 +1469,11 @@ func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType st
return storeChannel return storeChannel
} }
func (s SqlChannelStore) ExtraUpdateByUser(userId string, time int64) StoreChannel { func (s SqlChannelStore) ExtraUpdateByUser(userId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec( _, err := s.GetMaster().Exec(
`UPDATE Channels SET ExtraUpdateAt = :Time `UPDATE Channels SET ExtraUpdateAt = :Time
@@ -1494,11 +1491,11 @@ func (s SqlChannelStore) ExtraUpdateByUser(userId string, time int64) StoreChann
return storeChannel return storeChannel
} }
func (s SqlChannelStore) GetMembersForUser(teamId string, userId string) StoreChannel { func (s SqlChannelStore) GetMembersForUser(teamId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
members := &model.ChannelMembers{} members := &model.ChannelMembers{}
_, err := s.GetReplica().Select(members, ` _, err := s.GetReplica().Select(members, `
@@ -1524,8 +1521,8 @@ func (s SqlChannelStore) GetMembersForUser(teamId string, userId string) StoreCh
return storeChannel return storeChannel
} }
func (s SqlChannelStore) SearchInTeam(teamId string, term string) StoreChannel { func (s SqlChannelStore) SearchInTeam(teamId string, term string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := ` searchQuery := `
@@ -1548,8 +1545,8 @@ func (s SqlChannelStore) SearchInTeam(teamId string, term string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlChannelStore) SearchMore(userId string, teamId string, term string) StoreChannel { func (s SqlChannelStore) SearchMore(userId string, teamId string, term string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := ` searchQuery := `
@@ -1582,8 +1579,8 @@ func (s SqlChannelStore) SearchMore(userId string, teamId string, term string) S
return storeChannel return storeChannel
} }
func (s SqlChannelStore) performSearch(searchQuery string, term string, parameters map[string]interface{}) StoreResult { func (s SqlChannelStore) performSearch(searchQuery string, term string, parameters map[string]interface{}) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
// these chars have special meaning and can be treated as spaces // these chars have special meaning and can be treated as spaces
for _, c := range specialUserSearchChar { for _, c := range specialUserSearchChar {
@@ -1631,11 +1628,11 @@ func (s SqlChannelStore) performSearch(searchQuery string, term string, paramete
return result return result
} }
func (s SqlChannelStore) GetMembersByIds(channelId string, userIds []string) StoreChannel { func (s SqlChannelStore) GetMembersByIds(channelId string, userIds []string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var members model.ChannelMembers var members model.ChannelMembers
props := make(map[string]interface{}) props := make(map[string]interface{})

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@@ -1,19 +1,20 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type sqlClusterDiscoveryStore struct { type sqlClusterDiscoveryStore struct {
SqlStore SqlStore
} }
func NewSqlClusterDiscoveryStore(sqlStore SqlStore) ClusterDiscoveryStore { func NewSqlClusterDiscoveryStore(sqlStore SqlStore) store.ClusterDiscoveryStore {
s := &sqlClusterDiscoveryStore{sqlStore} s := &sqlClusterDiscoveryStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -27,12 +28,12 @@ func NewSqlClusterDiscoveryStore(sqlStore SqlStore) ClusterDiscoveryStore {
return s return s
} }
func (s sqlClusterDiscoveryStore) Save(ClusterDiscovery *model.ClusterDiscovery) StoreChannel { func (s sqlClusterDiscoveryStore) Save(ClusterDiscovery *model.ClusterDiscovery) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
ClusterDiscovery.PreSave() ClusterDiscovery.PreSave()
if result.Err = ClusterDiscovery.IsValid(); result.Err != nil { if result.Err = ClusterDiscovery.IsValid(); result.Err != nil {
@@ -52,11 +53,11 @@ func (s sqlClusterDiscoveryStore) Save(ClusterDiscovery *model.ClusterDiscovery)
return storeChannel return storeChannel
} }
func (s sqlClusterDiscoveryStore) Delete(ClusterDiscovery *model.ClusterDiscovery) StoreChannel { func (s sqlClusterDiscoveryStore) Delete(ClusterDiscovery *model.ClusterDiscovery) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
result.Data = false result.Data = false
if count, err := s.GetMaster().SelectInt( if count, err := s.GetMaster().SelectInt(
@@ -89,11 +90,11 @@ func (s sqlClusterDiscoveryStore) Delete(ClusterDiscovery *model.ClusterDiscover
return storeChannel return storeChannel
} }
func (s sqlClusterDiscoveryStore) Exists(ClusterDiscovery *model.ClusterDiscovery) StoreChannel { func (s sqlClusterDiscoveryStore) Exists(ClusterDiscovery *model.ClusterDiscovery) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
result.Data = false result.Data = false
if count, err := s.GetMaster().SelectInt( if count, err := s.GetMaster().SelectInt(
@@ -127,12 +128,12 @@ func (s sqlClusterDiscoveryStore) Exists(ClusterDiscovery *model.ClusterDiscover
return storeChannel return storeChannel
} }
func (s sqlClusterDiscoveryStore) GetAll(ClusterDiscoveryType, clusterName string) StoreChannel { func (s sqlClusterDiscoveryStore) GetAll(ClusterDiscoveryType, clusterName string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
lastPingAt := model.GetMillis() - model.CDS_OFFLINE_AFTER_MILLIS lastPingAt := model.GetMillis() - model.CDS_OFFLINE_AFTER_MILLIS
@@ -167,11 +168,11 @@ func (s sqlClusterDiscoveryStore) GetAll(ClusterDiscoveryType, clusterName strin
return storeChannel return storeChannel
} }
func (s sqlClusterDiscoveryStore) SetLastPingAt(ClusterDiscovery *model.ClusterDiscovery) StoreChannel { func (s sqlClusterDiscoveryStore) SetLastPingAt(ClusterDiscovery *model.ClusterDiscovery) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec( if _, err := s.GetMaster().Exec(
` `
@@ -200,12 +201,12 @@ func (s sqlClusterDiscoveryStore) SetLastPingAt(ClusterDiscovery *model.ClusterD
return storeChannel return storeChannel
} }
func (s sqlClusterDiscoveryStore) Cleanup() StoreChannel { func (s sqlClusterDiscoveryStore) Cleanup() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec( if _, err := s.GetMaster().Exec(
` `

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
@@ -9,10 +9,11 @@ import (
"time" "time"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestSqlClusterDiscoveryStore(t *testing.T) { func TestSqlClusterDiscoveryStore(t *testing.T) {
Setup() ss := Setup()
discovery := &model.ClusterDiscovery{ discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name", ClusterName: "cluster_name",
@@ -20,17 +21,17 @@ func TestSqlClusterDiscoveryStore(t *testing.T) {
Type: "test_test", Type: "test_test",
} }
if result := <-store.ClusterDiscovery().Save(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.ClusterDiscovery().Cleanup(); result.Err != nil { if result := <-ss.ClusterDiscovery().Cleanup(); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestSqlClusterDiscoveryStoreDelete(t *testing.T) { func TestSqlClusterDiscoveryStoreDelete(t *testing.T) {
Setup() ss := Setup()
discovery := &model.ClusterDiscovery{ discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name", ClusterName: "cluster_name",
@@ -38,17 +39,17 @@ func TestSqlClusterDiscoveryStoreDelete(t *testing.T) {
Type: "test_test", Type: "test_test",
} }
if result := <-store.ClusterDiscovery().Save(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.ClusterDiscovery().Delete(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Delete(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestSqlClusterDiscoveryStoreLastPing(t *testing.T) { func TestSqlClusterDiscoveryStoreLastPing(t *testing.T) {
Setup() ss := Setup()
discovery := &model.ClusterDiscovery{ discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name_lastPing", ClusterName: "cluster_name_lastPing",
@@ -56,11 +57,11 @@ func TestSqlClusterDiscoveryStoreLastPing(t *testing.T) {
Type: "test_test_lastPing" + model.NewId(), Type: "test_test_lastPing" + model.NewId(),
} }
if result := <-store.ClusterDiscovery().Save(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
@@ -68,11 +69,11 @@ func TestSqlClusterDiscoveryStoreLastPing(t *testing.T) {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
if result := <-store.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.ClusterDiscovery().GetAll(discovery.Type, "cluster_name_lastPing"); result.Err != nil { if result := <-ss.ClusterDiscovery().GetAll(discovery.Type, "cluster_name_lastPing"); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
list := result.Data.([]*model.ClusterDiscovery) list := result.Data.([]*model.ClusterDiscovery)
@@ -93,13 +94,13 @@ func TestSqlClusterDiscoveryStoreLastPing(t *testing.T) {
Type: "test_test_missing", Type: "test_test_missing",
} }
if result := <-store.ClusterDiscovery().SetLastPingAt(discovery2); result.Err != nil { if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestSqlClusterDiscoveryStoreExists(t *testing.T) { func TestSqlClusterDiscoveryStoreExists(t *testing.T) {
Setup() ss := Setup()
discovery := &model.ClusterDiscovery{ discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name_Exists", ClusterName: "cluster_name_Exists",
@@ -107,11 +108,11 @@ func TestSqlClusterDiscoveryStoreExists(t *testing.T) {
Type: "test_test_Exists" + model.NewId(), Type: "test_test_Exists" + model.NewId(),
} }
if result := <-store.ClusterDiscovery().Save(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.ClusterDiscovery().Exists(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Exists(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
val := result.Data.(bool) val := result.Data.(bool)
@@ -122,7 +123,7 @@ func TestSqlClusterDiscoveryStoreExists(t *testing.T) {
discovery.ClusterName = "cluster_name_Exists2" discovery.ClusterName = "cluster_name_Exists2"
if result := <-store.ClusterDiscovery().Exists(discovery); result.Err != nil { if result := <-ss.ClusterDiscovery().Exists(discovery); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
val := result.Data.(bool) val := result.Data.(bool)
@@ -133,7 +134,7 @@ func TestSqlClusterDiscoveryStoreExists(t *testing.T) {
} }
func TestSqlClusterDiscoveryGetStore(t *testing.T) { func TestSqlClusterDiscoveryGetStore(t *testing.T) {
Setup() ss := Setup()
testType1 := model.NewId() testType1 := model.NewId()
@@ -142,14 +143,14 @@ func TestSqlClusterDiscoveryGetStore(t *testing.T) {
Hostname: "hostname1", Hostname: "hostname1",
Type: testType1, Type: testType1,
} }
Must(store.ClusterDiscovery().Save(discovery1)) store.Must(ss.ClusterDiscovery().Save(discovery1))
discovery2 := &model.ClusterDiscovery{ discovery2 := &model.ClusterDiscovery{
ClusterName: "cluster_name", ClusterName: "cluster_name",
Hostname: "hostname2", Hostname: "hostname2",
Type: testType1, Type: testType1,
} }
Must(store.ClusterDiscovery().Save(discovery2)) store.Must(ss.ClusterDiscovery().Save(discovery2))
discovery3 := &model.ClusterDiscovery{ discovery3 := &model.ClusterDiscovery{
ClusterName: "cluster_name", ClusterName: "cluster_name",
@@ -158,7 +159,7 @@ func TestSqlClusterDiscoveryGetStore(t *testing.T) {
CreateAt: 1, CreateAt: 1,
LastPingAt: 1, LastPingAt: 1,
} }
Must(store.ClusterDiscovery().Save(discovery3)) store.Must(ss.ClusterDiscovery().Save(discovery3))
testType2 := model.NewId() testType2 := model.NewId()
@@ -167,9 +168,9 @@ func TestSqlClusterDiscoveryGetStore(t *testing.T) {
Hostname: "hostname1", Hostname: "hostname1",
Type: testType2, Type: testType2,
} }
Must(store.ClusterDiscovery().Save(discovery4)) store.Must(ss.ClusterDiscovery().Save(discovery4))
if result := <-store.ClusterDiscovery().GetAll(testType1, "cluster_name"); result.Err != nil { if result := <-ss.ClusterDiscovery().GetAll(testType1, "cluster_name"); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
list := result.Data.([]*model.ClusterDiscovery) list := result.Data.([]*model.ClusterDiscovery)
@@ -179,7 +180,7 @@ func TestSqlClusterDiscoveryGetStore(t *testing.T) {
} }
} }
if result := <-store.ClusterDiscovery().GetAll(testType2, "cluster_name"); result.Err != nil { if result := <-ss.ClusterDiscovery().GetAll(testType2, "cluster_name"); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
list := result.Data.([]*model.ClusterDiscovery) list := result.Data.([]*model.ClusterDiscovery)
@@ -189,7 +190,7 @@ func TestSqlClusterDiscoveryGetStore(t *testing.T) {
} }
} }
if result := <-store.ClusterDiscovery().GetAll(model.NewId(), "cluster_name"); result.Err != nil { if result := <-ss.ClusterDiscovery().GetAll(model.NewId(), "cluster_name"); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
list := result.Data.([]*model.ClusterDiscovery) list := result.Data.([]*model.ClusterDiscovery)

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

@@ -1,19 +1,20 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlCommandStore struct { type SqlCommandStore struct {
SqlStore SqlStore
} }
func NewSqlCommandStore(sqlStore SqlStore) CommandStore { func NewSqlCommandStore(sqlStore SqlStore) store.CommandStore {
s := &SqlCommandStore{sqlStore} s := &SqlCommandStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -43,11 +44,11 @@ func (s SqlCommandStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_command_delete_at", "Commands", "DeleteAt") s.CreateIndexIfNotExists("idx_command_delete_at", "Commands", "DeleteAt")
} }
func (s SqlCommandStore) Save(command *model.Command) StoreChannel { func (s SqlCommandStore) Save(command *model.Command) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(command.Id) > 0 { if len(command.Id) > 0 {
result.Err = model.NewAppError("SqlCommandStore.Save", "store.sql_command.save.saving_overwrite.app_error", nil, "id="+command.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlCommandStore.Save", "store.sql_command.save.saving_overwrite.app_error", nil, "id="+command.Id, http.StatusBadRequest)
@@ -76,11 +77,11 @@ func (s SqlCommandStore) Save(command *model.Command) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) Get(id string) StoreChannel { func (s SqlCommandStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var command model.Command var command model.Command
@@ -97,11 +98,11 @@ func (s SqlCommandStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) GetByTeam(teamId string) StoreChannel { func (s SqlCommandStore) GetByTeam(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var commands []*model.Command var commands []*model.Command
@@ -118,11 +119,11 @@ func (s SqlCommandStore) GetByTeam(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) Delete(commandId string, time int64) StoreChannel { func (s SqlCommandStore) Delete(commandId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("Update Commands SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": commandId}) _, err := s.GetMaster().Exec("Update Commands SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": commandId})
if err != nil { if err != nil {
@@ -136,11 +137,11 @@ func (s SqlCommandStore) Delete(commandId string, time int64) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) PermanentDeleteByTeam(teamId string) StoreChannel { func (s SqlCommandStore) PermanentDeleteByTeam(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM Commands WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId}) _, err := s.GetMaster().Exec("DELETE FROM Commands WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId})
if err != nil { if err != nil {
@@ -154,11 +155,11 @@ func (s SqlCommandStore) PermanentDeleteByTeam(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) PermanentDeleteByUser(userId string) StoreChannel { func (s SqlCommandStore) PermanentDeleteByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM Commands WHERE CreatorId = :UserId", map[string]interface{}{"UserId": userId}) _, err := s.GetMaster().Exec("DELETE FROM Commands WHERE CreatorId = :UserId", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {
@@ -172,11 +173,11 @@ func (s SqlCommandStore) PermanentDeleteByUser(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) Update(cmd *model.Command) StoreChannel { func (s SqlCommandStore) Update(cmd *model.Command) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
cmd.UpdateAt = model.GetMillis() cmd.UpdateAt = model.GetMillis()
@@ -193,11 +194,11 @@ func (s SqlCommandStore) Update(cmd *model.Command) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandStore) AnalyticsCommandCount(teamId string) StoreChannel { func (s SqlCommandStore) AnalyticsCommandCount(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT `SELECT

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

@@ -1,7 +1,7 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
@@ -10,7 +10,7 @@ import (
) )
func TestCommandStoreSave(t *testing.T) { func TestCommandStoreSave(t *testing.T) {
Setup() ss := Setup()
o1 := model.Command{} o1 := model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -19,17 +19,17 @@ func TestCommandStoreSave(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
if err := (<-store.Command().Save(&o1)).Err; err != nil { if err := (<-ss.Command().Save(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err) t.Fatal("couldn't save item", err)
} }
if err := (<-store.Command().Save(&o1)).Err; err == nil { if err := (<-ss.Command().Save(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save") t.Fatal("shouldn't be able to update from save")
} }
} }
func TestCommandStoreGet(t *testing.T) { func TestCommandStoreGet(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -38,9 +38,9 @@ func TestCommandStoreGet(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-store.Command().Get(o1.Id); r1.Err != nil { if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt { if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
@@ -48,13 +48,13 @@ func TestCommandStoreGet(t *testing.T) {
} }
} }
if err := (<-store.Command().Get("123")).Err; err == nil { if err := (<-ss.Command().Get("123")).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestCommandStoreGetByTeam(t *testing.T) { func TestCommandStoreGetByTeam(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -63,9 +63,9 @@ func TestCommandStoreGetByTeam(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-store.Command().GetByTeam(o1.TeamId); r1.Err != nil { if r1 := <-ss.Command().GetByTeam(o1.TeamId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.([]*model.Command)[0].CreateAt != o1.CreateAt { if r1.Data.([]*model.Command)[0].CreateAt != o1.CreateAt {
@@ -73,7 +73,7 @@ func TestCommandStoreGetByTeam(t *testing.T) {
} }
} }
if result := <-store.Command().GetByTeam("123"); result.Err != nil { if result := <-ss.Command().GetByTeam("123"); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if len(result.Data.([]*model.Command)) != 0 { if len(result.Data.([]*model.Command)) != 0 {
@@ -83,7 +83,7 @@ func TestCommandStoreGetByTeam(t *testing.T) {
} }
func TestCommandStoreDelete(t *testing.T) { func TestCommandStoreDelete(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -92,9 +92,9 @@ func TestCommandStoreDelete(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-store.Command().Get(o1.Id); r1.Err != nil { if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt { if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
@@ -102,18 +102,18 @@ func TestCommandStoreDelete(t *testing.T) {
} }
} }
if r2 := <-store.Command().Delete(o1.Id, model.GetMillis()); r2.Err != nil { if r2 := <-ss.Command().Delete(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Command().Get(o1.Id)); r3.Err == nil { if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestCommandStoreDeleteByTeam(t *testing.T) { func TestCommandStoreDeleteByTeam(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -122,9 +122,9 @@ func TestCommandStoreDeleteByTeam(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-store.Command().Get(o1.Id); r1.Err != nil { if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt { if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
@@ -132,18 +132,18 @@ func TestCommandStoreDeleteByTeam(t *testing.T) {
} }
} }
if r2 := <-store.Command().PermanentDeleteByTeam(o1.TeamId); r2.Err != nil { if r2 := <-ss.Command().PermanentDeleteByTeam(o1.TeamId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Command().Get(o1.Id)); r3.Err == nil { if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestCommandStoreDeleteByUser(t *testing.T) { func TestCommandStoreDeleteByUser(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -152,9 +152,9 @@ func TestCommandStoreDeleteByUser(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-store.Command().Get(o1.Id); r1.Err != nil { if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt { if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
@@ -162,18 +162,18 @@ func TestCommandStoreDeleteByUser(t *testing.T) {
} }
} }
if r2 := <-store.Command().PermanentDeleteByUser(o1.CreatorId); r2.Err != nil { if r2 := <-ss.Command().PermanentDeleteByUser(o1.CreatorId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Command().Get(o1.Id)); r3.Err == nil { if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestCommandStoreUpdate(t *testing.T) { func TestCommandStoreUpdate(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -182,17 +182,17 @@ func TestCommandStoreUpdate(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
o1.Token = model.NewId() o1.Token = model.NewId()
if r2 := <-store.Command().Update(o1); r2.Err != nil { if r2 := <-ss.Command().Update(o1); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
} }
func TestCommandCount(t *testing.T) { func TestCommandCount(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Command{} o1 := &model.Command{}
o1.CreatorId = model.NewId() o1.CreatorId = model.NewId()
@@ -201,9 +201,9 @@ func TestCommandCount(t *testing.T) {
o1.URL = "http://nowhere.com/" o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger" o1.Trigger = "trigger"
o1 = (<-store.Command().Save(o1)).Data.(*model.Command) o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-store.Command().AnalyticsCommandCount(""); r1.Err != nil { if r1 := <-ss.Command().AnalyticsCommandCount(""); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(int64) == 0 { if r1.Data.(int64) == 0 {
@@ -211,7 +211,7 @@ func TestCommandCount(t *testing.T) {
} }
} }
if r2 := <-store.Command().AnalyticsCommandCount(o1.TeamId); r2.Err != nil { if r2 := <-ss.Command().AnalyticsCommandCount(o1.TeamId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} else { } else {
if r2.Data.(int64) != 1 { if r2.Data.(int64) != 1 {

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

@@ -1,7 +1,7 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -10,13 +10,14 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlCommandWebhookStore struct { type SqlCommandWebhookStore struct {
SqlStore SqlStore
} }
func NewSqlCommandWebhookStore(sqlStore SqlStore) CommandWebhookStore { func NewSqlCommandWebhookStore(sqlStore SqlStore) store.CommandWebhookStore {
s := &SqlCommandWebhookStore{sqlStore} s := &SqlCommandWebhookStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -36,11 +37,11 @@ func (s SqlCommandWebhookStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_command_webhook_create_at", "CommandWebhooks", "CreateAt") s.CreateIndexIfNotExists("idx_command_webhook_create_at", "CommandWebhooks", "CreateAt")
} }
func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) StoreChannel { func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(webhook.Id) > 0 { if len(webhook.Id) > 0 {
result.Err = model.NewAppError("SqlCommandWebhookStore.Save", "store.sql_command_webhooks.save.existing.app_error", nil, "id="+webhook.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlCommandWebhookStore.Save", "store.sql_command_webhooks.save.existing.app_error", nil, "id="+webhook.Id, http.StatusBadRequest)
@@ -69,11 +70,11 @@ func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) StoreChannel
return storeChannel return storeChannel
} }
func (s SqlCommandWebhookStore) Get(id string) StoreChannel { func (s SqlCommandWebhookStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhook model.CommandWebhook var webhook model.CommandWebhook
@@ -94,11 +95,11 @@ func (s SqlCommandWebhookStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlCommandWebhookStore) TryUse(id string, limit int) StoreChannel { func (s SqlCommandWebhookStore) TryUse(id string, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if sqlResult, err := s.GetMaster().Exec("UPDATE CommandWebhooks SET UseCount = UseCount + 1 WHERE Id = :Id AND UseCount < :UseLimit", map[string]interface{}{"Id": id, "UseLimit": limit}); err != nil { if sqlResult, err := s.GetMaster().Exec("UPDATE CommandWebhooks SET UseCount = UseCount + 1 WHERE Id = :Id AND UseCount < :UseLimit", map[string]interface{}{"Id": id, "UseLimit": limit}); err != nil {
result.Err = model.NewAppError("SqlCommandWebhookStore.TryUse", "store.sql_command_webhooks.try_use.app_error", nil, "id="+id+", err="+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlCommandWebhookStore.TryUse", "store.sql_command_webhooks.try_use.app_error", nil, "id="+id+", err="+err.Error(), http.StatusInternalServerError)

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

@@ -1,7 +1,7 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
@@ -12,9 +12,9 @@ import (
) )
func TestCommandWebhookStore(t *testing.T) { func TestCommandWebhookStore(t *testing.T) {
Setup() ss := Setup()
cws := store.CommandWebhook() cws := ss.CommandWebhook()
h1 := &model.CommandWebhook{} h1 := &model.CommandWebhook{}
h1.CommandId = model.NewId() h1.CommandId = model.NewId()

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

@@ -1,7 +1,7 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
@@ -9,13 +9,14 @@ import (
"strings" "strings"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlComplianceStore struct { type SqlComplianceStore struct {
SqlStore SqlStore
} }
func NewSqlComplianceStore(sqlStore SqlStore) ComplianceStore { func NewSqlComplianceStore(sqlStore SqlStore) store.ComplianceStore {
s := &SqlComplianceStore{sqlStore} s := &SqlComplianceStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -35,12 +36,12 @@ func NewSqlComplianceStore(sqlStore SqlStore) ComplianceStore {
func (s SqlComplianceStore) CreateIndexesIfNotExists() { func (s SqlComplianceStore) CreateIndexesIfNotExists() {
} }
func (s SqlComplianceStore) Save(compliance *model.Compliance) StoreChannel { func (s SqlComplianceStore) Save(compliance *model.Compliance) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
compliance.PreSave() compliance.PreSave()
if result.Err = compliance.IsValid(); result.Err != nil { if result.Err = compliance.IsValid(); result.Err != nil {
@@ -62,12 +63,12 @@ func (s SqlComplianceStore) Save(compliance *model.Compliance) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlComplianceStore) Update(compliance *model.Compliance) StoreChannel { func (us SqlComplianceStore) Update(compliance *model.Compliance) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if result.Err = compliance.IsValid(); result.Err != nil { if result.Err = compliance.IsValid(); result.Err != nil {
storeChannel <- result storeChannel <- result
@@ -88,12 +89,12 @@ func (us SqlComplianceStore) Update(compliance *model.Compliance) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlComplianceStore) GetAll(offset, limit int) StoreChannel { func (s SqlComplianceStore) GetAll(offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := "SELECT * FROM Compliances ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset" query := "SELECT * FROM Compliances ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset"
@@ -111,12 +112,12 @@ func (s SqlComplianceStore) GetAll(offset, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlComplianceStore) Get(id string) StoreChannel { func (us SqlComplianceStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if obj, err := us.GetReplica().Get(model.Compliance{}, id); err != nil { if obj, err := us.GetReplica().Get(model.Compliance{}, id); err != nil {
result.Err = model.NewAppError("SqlComplianceStore.Get", "store.sql_compliance.get.finding.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlComplianceStore.Get", "store.sql_compliance.get.finding.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -134,11 +135,11 @@ func (us SqlComplianceStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlComplianceStore) ComplianceExport(job *model.Compliance) StoreChannel { func (s SqlComplianceStore) ComplianceExport(job *model.Compliance) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
props := map[string]interface{}{"StartTime": job.StartAt, "EndTime": job.EndAt} props := map[string]interface{}{"StartTime": job.StartAt, "EndTime": job.EndAt}

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

@@ -1,27 +1,28 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"time" "time"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestSqlComplianceStore(t *testing.T) { func TestSqlComplianceStore(t *testing.T) {
Setup() ss := Setup()
compliance1 := &model.Compliance{Desc: "Audit for federal subpoena case #22443", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_FAILED, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC} compliance1 := &model.Compliance{Desc: "Audit for federal subpoena case #22443", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_FAILED, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC}
Must(store.Compliance().Save(compliance1)) store.Must(ss.Compliance().Save(compliance1))
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
compliance2 := &model.Compliance{Desc: "Audit for federal subpoena case #11458", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_RUNNING, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC} compliance2 := &model.Compliance{Desc: "Audit for federal subpoena case #11458", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_RUNNING, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC}
Must(store.Compliance().Save(compliance2)) store.Must(ss.Compliance().Save(compliance2))
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
c := store.Compliance().GetAll(0, 1000) c := ss.Compliance().GetAll(0, 1000)
result := <-c result := <-c
compliances := result.Data.(model.Compliances) compliances := result.Data.(model.Compliances)
@@ -30,9 +31,9 @@ func TestSqlComplianceStore(t *testing.T) {
} }
compliance2.Status = model.COMPLIANCE_STATUS_FAILED compliance2.Status = model.COMPLIANCE_STATUS_FAILED
Must(store.Compliance().Update(compliance2)) store.Must(ss.Compliance().Update(compliance2))
c = store.Compliance().GetAll(0, 1000) c = ss.Compliance().GetAll(0, 1000)
result = <-c result = <-c
compliances = result.Data.(model.Compliances) compliances = result.Data.(model.Compliances)
@@ -40,7 +41,7 @@ func TestSqlComplianceStore(t *testing.T) {
t.Fatal() t.Fatal()
} }
c = store.Compliance().GetAll(0, 1) c = ss.Compliance().GetAll(0, 1)
result = <-c result = <-c
compliances = result.Data.(model.Compliances) compliances = result.Data.(model.Compliances)
@@ -48,7 +49,7 @@ func TestSqlComplianceStore(t *testing.T) {
t.Fatal("should only have returned 1") t.Fatal("should only have returned 1")
} }
c = store.Compliance().GetAll(1, 1) c = ss.Compliance().GetAll(1, 1)
result = <-c result = <-c
compliances = result.Data.(model.Compliances) compliances = result.Data.(model.Compliances)
@@ -56,14 +57,14 @@ func TestSqlComplianceStore(t *testing.T) {
t.Fatal("should only have returned 1") t.Fatal("should only have returned 1")
} }
rc2 := (<-store.Compliance().Get(compliance2.Id)).Data.(*model.Compliance) rc2 := (<-ss.Compliance().Get(compliance2.Id)).Data.(*model.Compliance)
if rc2.Status != compliance2.Status { if rc2.Status != compliance2.Status {
t.Fatal() t.Fatal()
} }
} }
func TestComplianceExport(t *testing.T) { func TestComplianceExport(t *testing.T) {
Setup() ss := Setup()
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
@@ -72,59 +73,59 @@ func TestComplianceExport(t *testing.T) {
t1.Name = "zz" + model.NewId() + "b" t1.Name = "zz" + model.NewId() + "b"
t1.Email = model.NewId() + "@nowhere.com" t1.Email = model.NewId() + "@nowhere.com"
t1.Type = model.TEAM_OPEN t1.Type = model.TEAM_OPEN
t1 = Must(store.Team().Save(t1)).(*model.Team) t1 = store.Must(ss.Team().Save(t1)).(*model.Team)
u1 := &model.User{} u1 := &model.User{}
u1.Email = model.NewId() u1.Email = model.NewId()
u1.Username = model.NewId() u1.Username = model.NewId()
u1 = Must(store.User().Save(u1)).(*model.User) u1 = store.Must(ss.User().Save(u1)).(*model.User)
Must(store.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id})) store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id}))
u2 := &model.User{} u2 := &model.User{}
u2.Email = model.NewId() u2.Email = model.NewId()
u2.Username = model.NewId() u2.Username = model.NewId()
u2 = Must(store.User().Save(u2)).(*model.User) u2 = store.Must(ss.User().Save(u2)).(*model.User)
Must(store.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id})) store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id}))
c1 := &model.Channel{} c1 := &model.Channel{}
c1.TeamId = t1.Id c1.TeamId = t1.Id
c1.DisplayName = "Channel2" c1.DisplayName = "Channel2"
c1.Name = "zz" + model.NewId() + "b" c1.Name = "zz" + model.NewId() + "b"
c1.Type = model.CHANNEL_OPEN c1.Type = model.CHANNEL_OPEN
c1 = Must(store.Channel().Save(c1)).(*model.Channel) c1 = store.Must(ss.Channel().Save(c1)).(*model.Channel)
o1 := &model.Post{} o1 := &model.Post{}
o1.ChannelId = c1.Id o1.ChannelId = c1.Id
o1.UserId = u1.Id o1.UserId = u1.Id
o1.CreateAt = model.GetMillis() o1.CreateAt = model.GetMillis()
o1.Message = "zz" + model.NewId() + "b" o1.Message = "zz" + model.NewId() + "b"
o1 = Must(store.Post().Save(o1)).(*model.Post) o1 = store.Must(ss.Post().Save(o1)).(*model.Post)
o1a := &model.Post{} o1a := &model.Post{}
o1a.ChannelId = c1.Id o1a.ChannelId = c1.Id
o1a.UserId = u1.Id o1a.UserId = u1.Id
o1a.CreateAt = o1.CreateAt + 10 o1a.CreateAt = o1.CreateAt + 10
o1a.Message = "zz" + model.NewId() + "b" o1a.Message = "zz" + model.NewId() + "b"
o1a = Must(store.Post().Save(o1a)).(*model.Post) o1a = store.Must(ss.Post().Save(o1a)).(*model.Post)
o2 := &model.Post{} o2 := &model.Post{}
o2.ChannelId = c1.Id o2.ChannelId = c1.Id
o2.UserId = u1.Id o2.UserId = u1.Id
o2.CreateAt = o1.CreateAt + 20 o2.CreateAt = o1.CreateAt + 20
o2.Message = "zz" + model.NewId() + "b" o2.Message = "zz" + model.NewId() + "b"
o2 = Must(store.Post().Save(o2)).(*model.Post) o2 = store.Must(ss.Post().Save(o2)).(*model.Post)
o2a := &model.Post{} o2a := &model.Post{}
o2a.ChannelId = c1.Id o2a.ChannelId = c1.Id
o2a.UserId = u2.Id o2a.UserId = u2.Id
o2a.CreateAt = o1.CreateAt + 30 o2a.CreateAt = o1.CreateAt + 30
o2a.Message = "zz" + model.NewId() + "b" o2a.Message = "zz" + model.NewId() + "b"
o2a = Must(store.Post().Save(o2a)).(*model.Post) o2a = store.Must(ss.Post().Save(o2a)).(*model.Post)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1} cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1}
if r1 := <-store.Compliance().ComplianceExport(cr1); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr1); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)
@@ -143,7 +144,7 @@ func TestComplianceExport(t *testing.T) {
} }
cr2 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email} cr2 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email}
if r1 := <-store.Compliance().ComplianceExport(cr2); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr2); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)
@@ -158,7 +159,7 @@ func TestComplianceExport(t *testing.T) {
} }
cr3 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email} cr3 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email}
if r1 := <-store.Compliance().ComplianceExport(cr3); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr3); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)
@@ -177,7 +178,7 @@ func TestComplianceExport(t *testing.T) {
} }
cr4 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message} cr4 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message}
if r1 := <-store.Compliance().ComplianceExport(cr4); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr4); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)
@@ -192,7 +193,7 @@ func TestComplianceExport(t *testing.T) {
} }
cr5 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message + " " + o1.Message} cr5 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message + " " + o1.Message}
if r1 := <-store.Compliance().ComplianceExport(cr5); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr5); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)
@@ -207,7 +208,7 @@ func TestComplianceExport(t *testing.T) {
} }
cr6 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email, Keywords: o2a.Message + " " + o1.Message} cr6 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email, Keywords: o2a.Message + " " + o1.Message}
if r1 := <-store.Compliance().ComplianceExport(cr6); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr6); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)
@@ -227,7 +228,7 @@ func TestComplianceExport(t *testing.T) {
} }
func TestComplianceExportDirectMessages(t *testing.T) { func TestComplianceExportDirectMessages(t *testing.T) {
Setup() ss := Setup()
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
@@ -236,68 +237,68 @@ func TestComplianceExportDirectMessages(t *testing.T) {
t1.Name = "zz" + model.NewId() + "b" t1.Name = "zz" + model.NewId() + "b"
t1.Email = model.NewId() + "@nowhere.com" t1.Email = model.NewId() + "@nowhere.com"
t1.Type = model.TEAM_OPEN t1.Type = model.TEAM_OPEN
t1 = Must(store.Team().Save(t1)).(*model.Team) t1 = store.Must(ss.Team().Save(t1)).(*model.Team)
u1 := &model.User{} u1 := &model.User{}
u1.Email = model.NewId() u1.Email = model.NewId()
u1.Username = model.NewId() u1.Username = model.NewId()
u1 = Must(store.User().Save(u1)).(*model.User) u1 = store.Must(ss.User().Save(u1)).(*model.User)
Must(store.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id})) store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id}))
u2 := &model.User{} u2 := &model.User{}
u2.Email = model.NewId() u2.Email = model.NewId()
u2.Username = model.NewId() u2.Username = model.NewId()
u2 = Must(store.User().Save(u2)).(*model.User) u2 = store.Must(ss.User().Save(u2)).(*model.User)
Must(store.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id})) store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id}))
c1 := &model.Channel{} c1 := &model.Channel{}
c1.TeamId = t1.Id c1.TeamId = t1.Id
c1.DisplayName = "Channel2" c1.DisplayName = "Channel2"
c1.Name = "zz" + model.NewId() + "b" c1.Name = "zz" + model.NewId() + "b"
c1.Type = model.CHANNEL_OPEN c1.Type = model.CHANNEL_OPEN
c1 = Must(store.Channel().Save(c1)).(*model.Channel) c1 = store.Must(ss.Channel().Save(c1)).(*model.Channel)
cDM := Must(store.Channel().CreateDirectChannel(u1.Id, u2.Id)).(*model.Channel) cDM := store.Must(ss.Channel().CreateDirectChannel(u1.Id, u2.Id)).(*model.Channel)
o1 := &model.Post{} o1 := &model.Post{}
o1.ChannelId = c1.Id o1.ChannelId = c1.Id
o1.UserId = u1.Id o1.UserId = u1.Id
o1.CreateAt = model.GetMillis() o1.CreateAt = model.GetMillis()
o1.Message = "zz" + model.NewId() + "b" o1.Message = "zz" + model.NewId() + "b"
o1 = Must(store.Post().Save(o1)).(*model.Post) o1 = store.Must(ss.Post().Save(o1)).(*model.Post)
o1a := &model.Post{} o1a := &model.Post{}
o1a.ChannelId = c1.Id o1a.ChannelId = c1.Id
o1a.UserId = u1.Id o1a.UserId = u1.Id
o1a.CreateAt = o1.CreateAt + 10 o1a.CreateAt = o1.CreateAt + 10
o1a.Message = "zz" + model.NewId() + "b" o1a.Message = "zz" + model.NewId() + "b"
o1a = Must(store.Post().Save(o1a)).(*model.Post) o1a = store.Must(ss.Post().Save(o1a)).(*model.Post)
o2 := &model.Post{} o2 := &model.Post{}
o2.ChannelId = c1.Id o2.ChannelId = c1.Id
o2.UserId = u1.Id o2.UserId = u1.Id
o2.CreateAt = o1.CreateAt + 20 o2.CreateAt = o1.CreateAt + 20
o2.Message = "zz" + model.NewId() + "b" o2.Message = "zz" + model.NewId() + "b"
o2 = Must(store.Post().Save(o2)).(*model.Post) o2 = store.Must(ss.Post().Save(o2)).(*model.Post)
o2a := &model.Post{} o2a := &model.Post{}
o2a.ChannelId = c1.Id o2a.ChannelId = c1.Id
o2a.UserId = u2.Id o2a.UserId = u2.Id
o2a.CreateAt = o1.CreateAt + 30 o2a.CreateAt = o1.CreateAt + 30
o2a.Message = "zz" + model.NewId() + "b" o2a.Message = "zz" + model.NewId() + "b"
o2a = Must(store.Post().Save(o2a)).(*model.Post) o2a = store.Must(ss.Post().Save(o2a)).(*model.Post)
o3 := &model.Post{} o3 := &model.Post{}
o3.ChannelId = cDM.Id o3.ChannelId = cDM.Id
o3.UserId = u1.Id o3.UserId = u1.Id
o3.CreateAt = o1.CreateAt + 40 o3.CreateAt = o1.CreateAt + 40
o3.Message = "zz" + model.NewId() + "b" o3.Message = "zz" + model.NewId() + "b"
o3 = Must(store.Post().Save(o3)).(*model.Post) o3 = store.Must(ss.Post().Save(o3)).(*model.Post)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o3.CreateAt + 1, Emails: u1.Email} cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o3.CreateAt + 1, Emails: u1.Email}
if r1 := <-store.Compliance().ComplianceExport(cr1); r1.Err != nil { if r1 := <-ss.Compliance().ComplianceExport(cr1); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
cposts := r1.Data.([]*model.CompliancePost) cposts := r1.Data.([]*model.CompliancePost)

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

@@ -1,13 +1,14 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -23,7 +24,7 @@ type SqlEmojiStore struct {
metrics einterfaces.MetricsInterface metrics einterfaces.MetricsInterface
} }
func NewSqlEmojiStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) EmojiStore { func NewSqlEmojiStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.EmojiStore {
s := &SqlEmojiStore{ s := &SqlEmojiStore{
SqlStore: sqlStore, SqlStore: sqlStore,
metrics: metrics, metrics: metrics,
@@ -47,11 +48,11 @@ func (es SqlEmojiStore) CreateIndexesIfNotExists() {
es.CreateIndexIfNotExists("idx_emoji_delete_at", "Emoji", "DeleteAt") es.CreateIndexIfNotExists("idx_emoji_delete_at", "Emoji", "DeleteAt")
} }
func (es SqlEmojiStore) Save(emoji *model.Emoji) StoreChannel { func (es SqlEmojiStore) Save(emoji *model.Emoji) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
emoji.PreSave() emoji.PreSave()
if result.Err = emoji.IsValid(); result.Err != nil { if result.Err = emoji.IsValid(); result.Err != nil {
@@ -73,11 +74,11 @@ func (es SqlEmojiStore) Save(emoji *model.Emoji) StoreChannel {
return storeChannel return storeChannel
} }
func (es SqlEmojiStore) Get(id string, allowFromCache bool) StoreChannel { func (es SqlEmojiStore) Get(id string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := emojiCache.Get(id); ok { if cacheItem, ok := emojiCache.Get(id); ok {
@@ -125,11 +126,11 @@ func (es SqlEmojiStore) Get(id string, allowFromCache bool) StoreChannel {
return storeChannel return storeChannel
} }
func (es SqlEmojiStore) GetByName(name string) StoreChannel { func (es SqlEmojiStore) GetByName(name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var emoji *model.Emoji var emoji *model.Emoji
@@ -153,11 +154,11 @@ func (es SqlEmojiStore) GetByName(name string) StoreChannel {
return storeChannel return storeChannel
} }
func (es SqlEmojiStore) GetList(offset, limit int) StoreChannel { func (es SqlEmojiStore) GetList(offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var emoji []*model.Emoji var emoji []*model.Emoji
@@ -181,11 +182,11 @@ func (es SqlEmojiStore) GetList(offset, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (es SqlEmojiStore) Delete(id string, time int64) StoreChannel { func (es SqlEmojiStore) Delete(id string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if sqlResult, err := es.GetMaster().Exec( if sqlResult, err := es.GetMaster().Exec(
`Update `Update

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

@@ -1,24 +1,25 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"time" "time"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestEmojiSaveDelete(t *testing.T) { func TestEmojiSaveDelete(t *testing.T) {
Setup() ss := Setup()
emoji1 := &model.Emoji{ emoji1 := &model.Emoji{
CreatorId: model.NewId(), CreatorId: model.NewId(),
Name: model.NewId(), Name: model.NewId(),
} }
if result := <-store.Emoji().Save(emoji1); result.Err != nil { if result := <-ss.Emoji().Save(emoji1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
@@ -30,25 +31,25 @@ func TestEmojiSaveDelete(t *testing.T) {
CreatorId: model.NewId(), CreatorId: model.NewId(),
Name: emoji1.Name, Name: emoji1.Name,
} }
if result := <-store.Emoji().Save(&emoji2); result.Err == nil { if result := <-ss.Emoji().Save(&emoji2); result.Err == nil {
t.Fatal("shouldn't be able to save emoji with duplicate name") t.Fatal("shouldn't be able to save emoji with duplicate name")
} }
if result := <-store.Emoji().Delete(emoji1.Id, time.Now().Unix()); result.Err != nil { if result := <-ss.Emoji().Delete(emoji1.Id, time.Now().Unix()); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.Emoji().Save(&emoji2); result.Err != nil { if result := <-ss.Emoji().Save(&emoji2); result.Err != nil {
t.Fatal("should be able to save emoji with duplicate name now that original has been deleted", result.Err) t.Fatal("should be able to save emoji with duplicate name now that original has been deleted", result.Err)
} }
if result := <-store.Emoji().Delete(emoji2.Id, time.Now().Unix()+1); result.Err != nil { if result := <-ss.Emoji().Delete(emoji2.Id, time.Now().Unix()+1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestEmojiGet(t *testing.T) { func TestEmojiGet(t *testing.T) {
Setup() ss := Setup()
emojis := []model.Emoji{ emojis := []model.Emoji{
{ {
@@ -66,35 +67,35 @@ func TestEmojiGet(t *testing.T) {
} }
for i, emoji := range emojis { for i, emoji := range emojis {
emojis[i] = *Must(store.Emoji().Save(&emoji)).(*model.Emoji) emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
} }
defer func() { defer func() {
for _, emoji := range emojis { for _, emoji := range emojis {
Must(store.Emoji().Delete(emoji.Id, time.Now().Unix())) store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
} }
}() }()
for _, emoji := range emojis { for _, emoji := range emojis {
if result := <-store.Emoji().Get(emoji.Id, false); result.Err != nil { if result := <-ss.Emoji().Get(emoji.Id, false); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err) t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
} }
} }
for _, emoji := range emojis { for _, emoji := range emojis {
if result := <-store.Emoji().Get(emoji.Id, true); result.Err != nil { if result := <-ss.Emoji().Get(emoji.Id, true); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err) t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
} }
} }
for _, emoji := range emojis { for _, emoji := range emojis {
if result := <-store.Emoji().Get(emoji.Id, true); result.Err != nil { if result := <-ss.Emoji().Get(emoji.Id, true); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err) t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
} }
} }
} }
func TestEmojiGetByName(t *testing.T) { func TestEmojiGetByName(t *testing.T) {
Setup() ss := Setup()
emojis := []model.Emoji{ emojis := []model.Emoji{
{ {
@@ -112,23 +113,23 @@ func TestEmojiGetByName(t *testing.T) {
} }
for i, emoji := range emojis { for i, emoji := range emojis {
emojis[i] = *Must(store.Emoji().Save(&emoji)).(*model.Emoji) emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
} }
defer func() { defer func() {
for _, emoji := range emojis { for _, emoji := range emojis {
Must(store.Emoji().Delete(emoji.Id, time.Now().Unix())) store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
} }
}() }()
for _, emoji := range emojis { for _, emoji := range emojis {
if result := <-store.Emoji().GetByName(emoji.Name); result.Err != nil { if result := <-ss.Emoji().GetByName(emoji.Name); result.Err != nil {
t.Fatalf("failed to get emoji with name %v: %v", emoji.Name, result.Err) t.Fatalf("failed to get emoji with name %v: %v", emoji.Name, result.Err)
} }
} }
} }
func TestEmojiGetList(t *testing.T) { func TestEmojiGetList(t *testing.T) {
Setup() ss := Setup()
emojis := []model.Emoji{ emojis := []model.Emoji{
{ {
@@ -146,15 +147,15 @@ func TestEmojiGetList(t *testing.T) {
} }
for i, emoji := range emojis { for i, emoji := range emojis {
emojis[i] = *Must(store.Emoji().Save(&emoji)).(*model.Emoji) emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
} }
defer func() { defer func() {
for _, emoji := range emojis { for _, emoji := range emojis {
Must(store.Emoji().Delete(emoji.Id, time.Now().Unix())) store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
} }
}() }()
if result := <-store.Emoji().GetList(0, 100); result.Err != nil { if result := <-ss.Emoji().GetList(0, 100); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
for _, emoji := range emojis { for _, emoji := range emojis {

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

@@ -1,6 +1,6 @@
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -8,6 +8,7 @@ import (
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -27,7 +28,7 @@ func ClearFileCaches() {
fileInfoCache.Purge() fileInfoCache.Purge()
} }
func NewSqlFileInfoStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) FileInfoStore { func NewSqlFileInfoStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.FileInfoStore {
s := &SqlFileInfoStore{ s := &SqlFileInfoStore{
SqlStore: sqlStore, SqlStore: sqlStore,
metrics: metrics, metrics: metrics,
@@ -56,11 +57,11 @@ func (fs SqlFileInfoStore) CreateIndexesIfNotExists() {
fs.CreateIndexIfNotExists("idx_fileinfo_postid_at", "FileInfo", "PostId") fs.CreateIndexIfNotExists("idx_fileinfo_postid_at", "FileInfo", "PostId")
} }
func (fs SqlFileInfoStore) Save(info *model.FileInfo) StoreChannel { func (fs SqlFileInfoStore) Save(info *model.FileInfo) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
info.PreSave() info.PreSave()
if result.Err = info.IsValid(); result.Err != nil { if result.Err = info.IsValid(); result.Err != nil {
@@ -82,11 +83,11 @@ func (fs SqlFileInfoStore) Save(info *model.FileInfo) StoreChannel {
return storeChannel return storeChannel
} }
func (fs SqlFileInfoStore) Get(id string) StoreChannel { func (fs SqlFileInfoStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
info := &model.FileInfo{} info := &model.FileInfo{}
@@ -114,11 +115,11 @@ func (fs SqlFileInfoStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (fs SqlFileInfoStore) GetByPath(path string) StoreChannel { func (fs SqlFileInfoStore) GetByPath(path string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
info := &model.FileInfo{} info := &model.FileInfo{}
@@ -147,11 +148,11 @@ func (fs SqlFileInfoStore) InvalidateFileInfosForPostCache(postId string) {
fileInfoCache.Remove(postId) fileInfoCache.Remove(postId)
} }
func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowFromCache bool) StoreChannel { func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := fileInfoCache.Get(postId); ok { if cacheItem, ok := fileInfoCache.Get(postId); ok {
@@ -209,11 +210,11 @@ func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowF
return storeChannel return storeChannel
} }
func (fs SqlFileInfoStore) AttachToPost(fileId, postId string) StoreChannel { func (fs SqlFileInfoStore) AttachToPost(fileId, postId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := fs.GetMaster().Exec( if _, err := fs.GetMaster().Exec(
`UPDATE `UPDATE
@@ -234,11 +235,11 @@ func (fs SqlFileInfoStore) AttachToPost(fileId, postId string) StoreChannel {
return storeChannel return storeChannel
} }
func (fs SqlFileInfoStore) DeleteForPost(postId string) StoreChannel { func (fs SqlFileInfoStore) DeleteForPost(postId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := fs.GetMaster().Exec( if _, err := fs.GetMaster().Exec(
`UPDATE `UPDATE
@@ -260,11 +261,11 @@ func (fs SqlFileInfoStore) DeleteForPost(postId string) StoreChannel {
return storeChannel return storeChannel
} }
func (fs SqlFileInfoStore) PermanentDelete(fileId string) StoreChannel { func (fs SqlFileInfoStore) PermanentDelete(fileId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := fs.GetMaster().Exec( if _, err := fs.GetMaster().Exec(
`DELETE FROM `DELETE FROM
@@ -282,11 +283,11 @@ func (fs SqlFileInfoStore) PermanentDelete(fileId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlFileInfoStore) PermanentDeleteBatch(endTime int64, limit int64) StoreChannel { func (s SqlFileInfoStore) PermanentDeleteBatch(endTime int64, limit int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var query string var query string
if *utils.Cfg.SqlSettings.DriverName == "postgres" { if *utils.Cfg.SqlSettings.DriverName == "postgres" {

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

@@ -1,24 +1,25 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"fmt" "fmt"
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestFileInfoSaveGet(t *testing.T) { func TestFileInfoSaveGet(t *testing.T) {
Setup() ss := Setup()
info := &model.FileInfo{ info := &model.FileInfo{
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
} }
if result := <-store.FileInfo().Save(info); result.Err != nil { if result := <-ss.FileInfo().Save(info); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 { } else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 {
t.Fatal("should've assigned an id to FileInfo") t.Fatal("should've assigned an id to FileInfo")
@@ -26,10 +27,10 @@ func TestFileInfoSaveGet(t *testing.T) {
info = returned info = returned
} }
defer func() { defer func() {
<-store.FileInfo().PermanentDelete(info.Id) <-ss.FileInfo().PermanentDelete(info.Id)
}() }()
if result := <-store.FileInfo().Get(info.Id); result.Err != nil { if result := <-ss.FileInfo().Get(info.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id { } else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id {
t.Log(info) t.Log(info)
@@ -37,29 +38,29 @@ func TestFileInfoSaveGet(t *testing.T) {
t.Fatal("should've returned correct FileInfo") t.Fatal("should've returned correct FileInfo")
} }
info2 := Must(store.FileInfo().Save(&model.FileInfo{ info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
DeleteAt: 123, DeleteAt: 123,
})).(*model.FileInfo) })).(*model.FileInfo)
if result := <-store.FileInfo().Get(info2.Id); result.Err == nil { if result := <-ss.FileInfo().Get(info2.Id); result.Err == nil {
t.Fatal("shouldn't have gotten deleted file") t.Fatal("shouldn't have gotten deleted file")
} }
defer func() { defer func() {
<-store.FileInfo().PermanentDelete(info2.Id) <-ss.FileInfo().PermanentDelete(info2.Id)
}() }()
} }
func TestFileInfoSaveGetByPath(t *testing.T) { func TestFileInfoSaveGetByPath(t *testing.T) {
Setup() ss := Setup()
info := &model.FileInfo{ info := &model.FileInfo{
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: fmt.Sprintf("%v/file.txt", model.NewId()), Path: fmt.Sprintf("%v/file.txt", model.NewId()),
} }
if result := <-store.FileInfo().Save(info); result.Err != nil { if result := <-ss.FileInfo().Save(info); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 { } else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 {
t.Fatal("should've assigned an id to FileInfo") t.Fatal("should've assigned an id to FileInfo")
@@ -67,10 +68,10 @@ func TestFileInfoSaveGetByPath(t *testing.T) {
info = returned info = returned
} }
defer func() { defer func() {
<-store.FileInfo().PermanentDelete(info.Id) <-ss.FileInfo().PermanentDelete(info.Id)
}() }()
if result := <-store.FileInfo().GetByPath(info.Path); result.Err != nil { if result := <-ss.FileInfo().GetByPath(info.Path); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id { } else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id {
t.Log(info) t.Log(info)
@@ -78,22 +79,22 @@ func TestFileInfoSaveGetByPath(t *testing.T) {
t.Fatal("should've returned correct FileInfo") t.Fatal("should've returned correct FileInfo")
} }
info2 := Must(store.FileInfo().Save(&model.FileInfo{ info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
DeleteAt: 123, DeleteAt: 123,
})).(*model.FileInfo) })).(*model.FileInfo)
if result := <-store.FileInfo().GetByPath(info2.Id); result.Err == nil { if result := <-ss.FileInfo().GetByPath(info2.Id); result.Err == nil {
t.Fatal("shouldn't have gotten deleted file") t.Fatal("shouldn't have gotten deleted file")
} }
defer func() { defer func() {
<-store.FileInfo().PermanentDelete(info2.Id) <-ss.FileInfo().PermanentDelete(info2.Id)
}() }()
} }
func TestFileInfoGetForPost(t *testing.T) { func TestFileInfoGetForPost(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
postId := model.NewId() postId := model.NewId()
@@ -123,25 +124,25 @@ func TestFileInfoGetForPost(t *testing.T) {
} }
for i, info := range infos { for i, info := range infos {
infos[i] = Must(store.FileInfo().Save(info)).(*model.FileInfo) infos[i] = store.Must(ss.FileInfo().Save(info)).(*model.FileInfo)
defer func(id string) { defer func(id string) {
<-store.FileInfo().PermanentDelete(id) <-ss.FileInfo().PermanentDelete(id)
}(infos[i].Id) }(infos[i].Id)
} }
if result := <-store.FileInfo().GetForPost(postId, true, false); result.Err != nil { if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 { } else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos") t.Fatal("should've returned exactly 2 file infos")
} }
if result := <-store.FileInfo().GetForPost(postId, false, false); result.Err != nil { if result := <-ss.FileInfo().GetForPost(postId, false, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 { } else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos") t.Fatal("should've returned exactly 2 file infos")
} }
if result := <-store.FileInfo().GetForPost(postId, true, true); result.Err != nil { if result := <-ss.FileInfo().GetForPost(postId, true, true); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 { } else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos") t.Fatal("should've returned exactly 2 file infos")
@@ -149,48 +150,48 @@ func TestFileInfoGetForPost(t *testing.T) {
} }
func TestFileInfoAttachToPost(t *testing.T) { func TestFileInfoAttachToPost(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
postId := model.NewId() postId := model.NewId()
info1 := Must(store.FileInfo().Save(&model.FileInfo{ info1 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: userId, CreatorId: userId,
Path: "file.txt", Path: "file.txt",
})).(*model.FileInfo) })).(*model.FileInfo)
defer func() { defer func() {
<-store.FileInfo().PermanentDelete(info1.Id) <-ss.FileInfo().PermanentDelete(info1.Id)
}() }()
if len(info1.PostId) != 0 { if len(info1.PostId) != 0 {
t.Fatal("file shouldn't have a PostId") t.Fatal("file shouldn't have a PostId")
} }
if result := <-store.FileInfo().AttachToPost(info1.Id, postId); result.Err != nil { if result := <-ss.FileInfo().AttachToPost(info1.Id, postId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
info1 = Must(store.FileInfo().Get(info1.Id)).(*model.FileInfo) info1 = store.Must(ss.FileInfo().Get(info1.Id)).(*model.FileInfo)
} }
if len(info1.PostId) == 0 { if len(info1.PostId) == 0 {
t.Fatal("file should now have a PostId") t.Fatal("file should now have a PostId")
} }
info2 := Must(store.FileInfo().Save(&model.FileInfo{ info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: userId, CreatorId: userId,
Path: "file.txt", Path: "file.txt",
})).(*model.FileInfo) })).(*model.FileInfo)
defer func() { defer func() {
<-store.FileInfo().PermanentDelete(info2.Id) <-ss.FileInfo().PermanentDelete(info2.Id)
}() }()
if result := <-store.FileInfo().AttachToPost(info2.Id, postId); result.Err != nil { if result := <-ss.FileInfo().AttachToPost(info2.Id, postId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
info2 = Must(store.FileInfo().Get(info2.Id)).(*model.FileInfo) info2 = store.Must(ss.FileInfo().Get(info2.Id)).(*model.FileInfo)
} }
if result := <-store.FileInfo().GetForPost(postId, true, false); result.Err != nil { if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if infos := result.Data.([]*model.FileInfo); len(infos) != 2 { } else if infos := result.Data.([]*model.FileInfo); len(infos) != 2 {
t.Fatal("should've returned exactly 2 file infos") t.Fatal("should've returned exactly 2 file infos")
@@ -198,7 +199,7 @@ func TestFileInfoAttachToPost(t *testing.T) {
} }
func TestFileInfoDeleteForPost(t *testing.T) { func TestFileInfoDeleteForPost(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
postId := model.NewId() postId := model.NewId()
@@ -228,70 +229,70 @@ func TestFileInfoDeleteForPost(t *testing.T) {
} }
for i, info := range infos { for i, info := range infos {
infos[i] = Must(store.FileInfo().Save(info)).(*model.FileInfo) infos[i] = store.Must(ss.FileInfo().Save(info)).(*model.FileInfo)
defer func(id string) { defer func(id string) {
<-store.FileInfo().PermanentDelete(id) <-ss.FileInfo().PermanentDelete(id)
}(infos[i].Id) }(infos[i].Id)
} }
if result := <-store.FileInfo().DeleteForPost(postId); result.Err != nil { if result := <-ss.FileInfo().DeleteForPost(postId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if infos := Must(store.FileInfo().GetForPost(postId, true, false)).([]*model.FileInfo); len(infos) != 0 { if infos := store.Must(ss.FileInfo().GetForPost(postId, true, false)).([]*model.FileInfo); len(infos) != 0 {
t.Fatal("shouldn't have returned any file infos") t.Fatal("shouldn't have returned any file infos")
} }
} }
func TestFileInfoPermanentDelete(t *testing.T) { func TestFileInfoPermanentDelete(t *testing.T) {
Setup() ss := Setup()
info := Must(store.FileInfo().Save(&model.FileInfo{ info := store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: model.NewId(), PostId: model.NewId(),
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
})).(*model.FileInfo) })).(*model.FileInfo)
if result := <-store.FileInfo().PermanentDelete(info.Id); result.Err != nil { if result := <-ss.FileInfo().PermanentDelete(info.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestFileInfoPermanentDeleteBatch(t *testing.T) { func TestFileInfoPermanentDeleteBatch(t *testing.T) {
Setup() ss := Setup()
postId := model.NewId() postId := model.NewId()
Must(store.FileInfo().Save(&model.FileInfo{ store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId, PostId: postId,
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
CreateAt: 1000, CreateAt: 1000,
})) }))
Must(store.FileInfo().Save(&model.FileInfo{ store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId, PostId: postId,
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
CreateAt: 1200, CreateAt: 1200,
})) }))
Must(store.FileInfo().Save(&model.FileInfo{ store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId, PostId: postId,
CreatorId: model.NewId(), CreatorId: model.NewId(),
Path: "file.txt", Path: "file.txt",
CreateAt: 2000, CreateAt: 2000,
})) }))
if result := <-store.FileInfo().GetForPost(postId, true, false); result.Err != nil { if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if len(result.Data.([]*model.FileInfo)) != 3 { } else if len(result.Data.([]*model.FileInfo)) != 3 {
t.Fatal("Expected 3 fileInfos") t.Fatal("Expected 3 fileInfos")
} }
Must(store.FileInfo().PermanentDeleteBatch(1500, 1000)) store.Must(ss.FileInfo().PermanentDeleteBatch(1500, 1000))
if result := <-store.FileInfo().GetForPost(postId, true, false); result.Err != nil { if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if len(result.Data.([]*model.FileInfo)) != 1 { } else if len(result.Data.([]*model.FileInfo)) != 1 {
t.Fatal("Expected 3 fileInfos") t.Fatal("Expected 3 fileInfos")

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -9,13 +9,14 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlJobStore struct { type SqlJobStore struct {
SqlStore SqlStore
} }
func NewSqlJobStore(sqlStore SqlStore) JobStore { func NewSqlJobStore(sqlStore SqlStore) store.JobStore {
s := &SqlJobStore{sqlStore} s := &SqlJobStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -33,11 +34,11 @@ func (jss SqlJobStore) CreateIndexesIfNotExists() {
jss.CreateIndexIfNotExists("idx_jobs_type", "Jobs", "Type") jss.CreateIndexIfNotExists("idx_jobs_type", "Jobs", "Type")
} }
func (jss SqlJobStore) Save(job *model.Job) StoreChannel { func (jss SqlJobStore) Save(job *model.Job) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if err := jss.GetMaster().Insert(job); err != nil { if err := jss.GetMaster().Insert(job); err != nil {
result.Err = model.NewAppError("SqlJobStore.Save", "store.sql_job.save.app_error", nil, "id="+job.Id+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlJobStore.Save", "store.sql_job.save.app_error", nil, "id="+job.Id+", "+err.Error(), http.StatusInternalServerError)
} else { } else {
@@ -51,11 +52,11 @@ func (jss SqlJobStore) Save(job *model.Job) StoreChannel {
return storeChannel return storeChannel
} }
func (jss SqlJobStore) UpdateOptimistically(job *model.Job, currentStatus string) StoreChannel { func (jss SqlJobStore) UpdateOptimistically(job *model.Job, currentStatus string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if sqlResult, err := jss.GetMaster().Exec( if sqlResult, err := jss.GetMaster().Exec(
`UPDATE `UPDATE
@@ -99,11 +100,11 @@ func (jss SqlJobStore) UpdateOptimistically(job *model.Job, currentStatus string
return storeChannel return storeChannel
} }
func (jss SqlJobStore) UpdateStatus(id string, status string) StoreChannel { func (jss SqlJobStore) UpdateStatus(id string, status string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
job := &model.Job{ job := &model.Job{
Id: id, Id: id,
@@ -128,11 +129,11 @@ func (jss SqlJobStore) UpdateStatus(id string, status string) StoreChannel {
return storeChannel return storeChannel
} }
func (jss SqlJobStore) UpdateStatusOptimistically(id string, currentStatus string, newStatus string) StoreChannel { func (jss SqlJobStore) UpdateStatusOptimistically(id string, currentStatus string, newStatus string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var startAtClause string var startAtClause string
if newStatus == model.JOB_STATUS_IN_PROGRESS { if newStatus == model.JOB_STATUS_IN_PROGRESS {
@@ -171,11 +172,11 @@ func (jss SqlJobStore) UpdateStatusOptimistically(id string, currentStatus strin
return storeChannel return storeChannel
} }
func (jss SqlJobStore) Get(id string) StoreChannel { func (jss SqlJobStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var status *model.Job var status *model.Job
@@ -202,11 +203,11 @@ func (jss SqlJobStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (jss SqlJobStore) GetAllPage(offset int, limit int) StoreChannel { func (jss SqlJobStore) GetAllPage(offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Job var statuses []*model.Job
@@ -233,11 +234,11 @@ func (jss SqlJobStore) GetAllPage(offset int, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (jss SqlJobStore) GetAllByType(jobType string) StoreChannel { func (jss SqlJobStore) GetAllByType(jobType string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Job var statuses []*model.Job
@@ -262,11 +263,11 @@ func (jss SqlJobStore) GetAllByType(jobType string) StoreChannel {
return storeChannel return storeChannel
} }
func (jss SqlJobStore) GetAllByTypePage(jobType string, offset int, limit int) StoreChannel { func (jss SqlJobStore) GetAllByTypePage(jobType string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Job var statuses []*model.Job
@@ -295,11 +296,11 @@ func (jss SqlJobStore) GetAllByTypePage(jobType string, offset int, limit int) S
return storeChannel return storeChannel
} }
func (jss SqlJobStore) GetAllByStatus(status string) StoreChannel { func (jss SqlJobStore) GetAllByStatus(status string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Job var statuses []*model.Job
@@ -324,11 +325,11 @@ func (jss SqlJobStore) GetAllByStatus(status string) StoreChannel {
return storeChannel return storeChannel
} }
func (jss SqlJobStore) Delete(id string) StoreChannel { func (jss SqlJobStore) Delete(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := jss.GetMaster().Exec( if _, err := jss.GetMaster().Exec(
`DELETE FROM `DELETE FROM

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

@@ -1,7 +1,7 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
@@ -9,10 +9,11 @@ import (
"time" "time"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestJobSaveGet(t *testing.T) { func TestJobSaveGet(t *testing.T) {
Setup() ss := Setup()
job := &model.Job{ job := &model.Job{
Id: model.NewId(), Id: model.NewId(),
@@ -25,15 +26,15 @@ func TestJobSaveGet(t *testing.T) {
}, },
} }
if result := <-store.Job().Save(job); result.Err != nil { if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
defer func() { defer func() {
<-store.Job().Delete(job.Id) <-ss.Job().Delete(job.Id)
}() }()
if result := <-store.Job().Get(job.Id); result.Err != nil { if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.(*model.Job); received.Id != job.Id { } else if received := result.Data.(*model.Job); received.Id != job.Id {
t.Fatal("received incorrect job after save") t.Fatal("received incorrect job after save")
@@ -43,7 +44,7 @@ func TestJobSaveGet(t *testing.T) {
} }
func TestJobGetAllByType(t *testing.T) { func TestJobGetAllByType(t *testing.T) {
Setup() ss := Setup()
jobType := model.NewId() jobType := model.NewId()
@@ -63,11 +64,11 @@ func TestJobGetAllByType(t *testing.T) {
} }
for _, job := range jobs { for _, job := range jobs {
Must(store.Job().Save(job)) store.Must(ss.Job().Save(job))
defer store.Job().Delete(job.Id) defer ss.Job().Delete(job.Id)
} }
if result := <-store.Job().GetAllByType(jobType); result.Err != nil { if result := <-ss.Job().GetAllByType(jobType); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 { } else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs") t.Fatal("received wrong number of jobs")
@@ -79,7 +80,7 @@ func TestJobGetAllByType(t *testing.T) {
} }
func TestJobGetAllByTypePage(t *testing.T) { func TestJobGetAllByTypePage(t *testing.T) {
Setup() ss := Setup()
jobType := model.NewId() jobType := model.NewId()
@@ -107,11 +108,11 @@ func TestJobGetAllByTypePage(t *testing.T) {
} }
for _, job := range jobs { for _, job := range jobs {
Must(store.Job().Save(job)) store.Must(ss.Job().Save(job))
defer store.Job().Delete(job.Id) defer ss.Job().Delete(job.Id)
} }
if result := <-store.Job().GetAllByTypePage(jobType, 0, 2); result.Err != nil { if result := <-ss.Job().GetAllByTypePage(jobType, 0, 2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 { } else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs") t.Fatal("received wrong number of jobs")
@@ -121,7 +122,7 @@ func TestJobGetAllByTypePage(t *testing.T) {
t.Fatal("should've received second newest job second") t.Fatal("should've received second newest job second")
} }
if result := <-store.Job().GetAllByTypePage(jobType, 2, 2); result.Err != nil { if result := <-ss.Job().GetAllByTypePage(jobType, 2, 2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 1 { } else if received := result.Data.([]*model.Job); len(received) != 1 {
t.Fatal("received wrong number of jobs") t.Fatal("received wrong number of jobs")
@@ -131,7 +132,7 @@ func TestJobGetAllByTypePage(t *testing.T) {
} }
func TestJobGetAllPage(t *testing.T) { func TestJobGetAllPage(t *testing.T) {
Setup() ss := Setup()
jobType := model.NewId() jobType := model.NewId()
createAtTime := model.GetMillis() createAtTime := model.GetMillis()
@@ -155,11 +156,11 @@ func TestJobGetAllPage(t *testing.T) {
} }
for _, job := range jobs { for _, job := range jobs {
Must(store.Job().Save(job)) store.Must(ss.Job().Save(job))
defer store.Job().Delete(job.Id) defer ss.Job().Delete(job.Id)
} }
if result := <-store.Job().GetAllPage(0, 2); result.Err != nil { if result := <-ss.Job().GetAllPage(0, 2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 { } else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs") t.Fatal("received wrong number of jobs")
@@ -169,7 +170,7 @@ func TestJobGetAllPage(t *testing.T) {
t.Fatal("should've received second newest job second") t.Fatal("should've received second newest job second")
} }
if result := <-store.Job().GetAllPage(2, 2); result.Err != nil { if result := <-ss.Job().GetAllPage(2, 2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) < 1 { } else if received := result.Data.([]*model.Job); len(received) < 1 {
t.Fatal("received wrong number of jobs") t.Fatal("received wrong number of jobs")
@@ -179,6 +180,8 @@ func TestJobGetAllPage(t *testing.T) {
} }
func TestJobGetAllByStatus(t *testing.T) { func TestJobGetAllByStatus(t *testing.T) {
ss := Setup()
jobType := model.NewId() jobType := model.NewId()
status := model.NewId() status := model.NewId()
@@ -213,11 +216,11 @@ func TestJobGetAllByStatus(t *testing.T) {
} }
for _, job := range jobs { for _, job := range jobs {
Must(store.Job().Save(job)) store.Must(ss.Job().Save(job))
defer store.Job().Delete(job.Id) defer ss.Job().Delete(job.Id)
} }
if result := <-store.Job().GetAllByStatus(status); result.Err != nil { if result := <-ss.Job().GetAllByStatus(status); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 3 { } else if received := result.Data.([]*model.Job); len(received) != 3 {
t.Fatal("received wrong number of jobs") t.Fatal("received wrong number of jobs")
@@ -229,6 +232,8 @@ func TestJobGetAllByStatus(t *testing.T) {
} }
func TestJobUpdateOptimistically(t *testing.T) { func TestJobUpdateOptimistically(t *testing.T) {
ss := Setup()
job := &model.Job{ job := &model.Job{
Id: model.NewId(), Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION, Type: model.JOB_TYPE_DATA_RETENTION,
@@ -236,10 +241,10 @@ func TestJobUpdateOptimistically(t *testing.T) {
Status: model.JOB_STATUS_PENDING, Status: model.JOB_STATUS_PENDING,
} }
if result := <-store.Job().Save(job); result.Err != nil { if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
defer store.Job().Delete(job.Id) defer ss.Job().Delete(job.Id)
job.LastActivityAt = model.GetMillis() job.LastActivityAt = model.GetMillis()
job.Status = model.JOB_STATUS_IN_PROGRESS job.Status = model.JOB_STATUS_IN_PROGRESS
@@ -248,7 +253,7 @@ func TestJobUpdateOptimistically(t *testing.T) {
"Foo": "Bar", "Foo": "Bar",
} }
if result := <-store.Job().UpdateOptimistically(job, model.JOB_STATUS_SUCCESS); result.Err != nil { if result := <-ss.Job().UpdateOptimistically(job, model.JOB_STATUS_SUCCESS); result.Err != nil {
if result.Data.(bool) { if result.Data.(bool) {
t.Fatal("should have failed due to incorrect old status") t.Fatal("should have failed due to incorrect old status")
} }
@@ -256,7 +261,7 @@ func TestJobUpdateOptimistically(t *testing.T) {
time.Sleep(2 * time.Millisecond) time.Sleep(2 * time.Millisecond)
if result := <-store.Job().UpdateOptimistically(job, model.JOB_STATUS_PENDING); result.Err != nil { if result := <-ss.Job().UpdateOptimistically(job, model.JOB_STATUS_PENDING); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if !result.Data.(bool) { if !result.Data.(bool) {
@@ -265,7 +270,7 @@ func TestJobUpdateOptimistically(t *testing.T) {
var updatedJob *model.Job var updatedJob *model.Job
if result := <-store.Job().Get(job.Id); result.Err != nil { if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
updatedJob = result.Data.(*model.Job) updatedJob = result.Data.(*model.Job)
@@ -279,6 +284,8 @@ func TestJobUpdateOptimistically(t *testing.T) {
} }
func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) { func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
ss := Setup()
job := &model.Job{ job := &model.Job{
Id: model.NewId(), Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION, Type: model.JOB_TYPE_DATA_RETENTION,
@@ -287,17 +294,17 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
} }
var lastUpdateAt int64 var lastUpdateAt int64
if result := <-store.Job().Save(job); result.Err != nil { if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
lastUpdateAt = result.Data.(*model.Job).LastActivityAt lastUpdateAt = result.Data.(*model.Job).LastActivityAt
} }
defer store.Job().Delete(job.Id) defer ss.Job().Delete(job.Id)
time.Sleep(2 * time.Millisecond) time.Sleep(2 * time.Millisecond)
if result := <-store.Job().UpdateStatus(job.Id, model.JOB_STATUS_PENDING); result.Err != nil { if result := <-ss.Job().UpdateStatus(job.Id, model.JOB_STATUS_PENDING); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
received := result.Data.(*model.Job) received := result.Data.(*model.Job)
@@ -312,7 +319,7 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
time.Sleep(2 * time.Millisecond) time.Sleep(2 * time.Millisecond)
if result := <-store.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil { if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if result.Data.(bool) { if result.Data.(bool) {
@@ -320,7 +327,7 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
} }
} }
if result := <-store.Job().Get(job.Id); result.Err != nil { if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
received := result.Data.(*model.Job) received := result.Data.(*model.Job)
@@ -334,7 +341,7 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
time.Sleep(2 * time.Millisecond) time.Sleep(2 * time.Millisecond)
if result := <-store.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS); result.Err != nil { if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if !result.Data.(bool) { if !result.Data.(bool) {
@@ -343,7 +350,7 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
} }
var startAtSet int64 var startAtSet int64
if result := <-store.Job().Get(job.Id); result.Err != nil { if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
received := result.Data.(*model.Job) received := result.Data.(*model.Job)
@@ -362,7 +369,7 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
time.Sleep(2 * time.Millisecond) time.Sleep(2 * time.Millisecond)
if result := <-store.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil { if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if !result.Data.(bool) { if !result.Data.(bool) {
@@ -370,7 +377,7 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
} }
} }
if result := <-store.Job().Get(job.Id); result.Err != nil { if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
received := result.Data.(*model.Job) received := result.Data.(*model.Job)
@@ -388,13 +395,13 @@ func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
} }
func TestJobDelete(t *testing.T) { func TestJobDelete(t *testing.T) {
Setup() ss := Setup()
job := Must(store.Job().Save(&model.Job{ job := store.Must(ss.Job().Save(&model.Job{
Id: model.NewId(), Id: model.NewId(),
})).(*model.Job) })).(*model.Job)
if result := <-store.Job().Delete(job.Id); result.Err != nil { if result := <-ss.Job().Delete(job.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }

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

@@ -1,19 +1,20 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlLicenseStore struct { type SqlLicenseStore struct {
SqlStore SqlStore
} }
func NewSqlLicenseStore(sqlStore SqlStore) LicenseStore { func NewSqlLicenseStore(sqlStore SqlStore) store.LicenseStore {
ls := &SqlLicenseStore{sqlStore} ls := &SqlLicenseStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -28,12 +29,12 @@ func NewSqlLicenseStore(sqlStore SqlStore) LicenseStore {
func (ls SqlLicenseStore) CreateIndexesIfNotExists() { func (ls SqlLicenseStore) CreateIndexesIfNotExists() {
} }
func (ls SqlLicenseStore) Save(license *model.LicenseRecord) StoreChannel { func (ls SqlLicenseStore) Save(license *model.LicenseRecord) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
license.PreSave() license.PreSave()
if result.Err = license.IsValid(); result.Err != nil { if result.Err = license.IsValid(); result.Err != nil {
@@ -58,12 +59,12 @@ func (ls SqlLicenseStore) Save(license *model.LicenseRecord) StoreChannel {
return storeChannel return storeChannel
} }
func (ls SqlLicenseStore) Get(id string) StoreChannel { func (ls SqlLicenseStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if obj, err := ls.GetReplica().Get(model.LicenseRecord{}, id); err != nil { if obj, err := ls.GetReplica().Get(model.LicenseRecord{}, id); err != nil {
result.Err = model.NewAppError("SqlLicenseStore.Get", "store.sql_license.get.app_error", nil, "license_id="+id+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlLicenseStore.Get", "store.sql_license.get.app_error", nil, "license_id="+id+", "+err.Error(), http.StatusInternalServerError)

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

@@ -1,46 +1,47 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestLicenseStoreSave(t *testing.T) { func TestLicenseStoreSave(t *testing.T) {
Setup() ss := Setup()
l1 := model.LicenseRecord{} l1 := model.LicenseRecord{}
l1.Id = model.NewId() l1.Id = model.NewId()
l1.Bytes = "junk" l1.Bytes = "junk"
if err := (<-store.License().Save(&l1)).Err; err != nil { if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("couldn't save license record", err) t.Fatal("couldn't save license record", err)
} }
if err := (<-store.License().Save(&l1)).Err; err != nil { if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("shouldn't fail on trying to save existing license record", err) t.Fatal("shouldn't fail on trying to save existing license record", err)
} }
l1.Id = "" l1.Id = ""
if err := (<-store.License().Save(&l1)).Err; err == nil { if err := (<-ss.License().Save(&l1)).Err; err == nil {
t.Fatal("should fail on invalid license", err) t.Fatal("should fail on invalid license", err)
} }
} }
func TestLicenseStoreGet(t *testing.T) { func TestLicenseStoreGet(t *testing.T) {
Setup() ss := Setup()
l1 := model.LicenseRecord{} l1 := model.LicenseRecord{}
l1.Id = model.NewId() l1.Id = model.NewId()
l1.Bytes = "junk" l1.Bytes = "junk"
Must(store.License().Save(&l1)) store.Must(ss.License().Save(&l1))
if r := <-store.License().Get(l1.Id); r.Err != nil { if r := <-ss.License().Get(l1.Id); r.Err != nil {
t.Fatal("couldn't get license", r.Err) t.Fatal("couldn't get license", r.Err)
} else { } else {
if r.Data.(*model.LicenseRecord).Bytes != l1.Bytes { if r.Data.(*model.LicenseRecord).Bytes != l1.Bytes {
@@ -48,7 +49,7 @@ func TestLicenseStoreGet(t *testing.T) {
} }
} }
if err := (<-store.License().Get("missing")).Err; err == nil { if err := (<-ss.License().Get("missing")).Err; err == nil {
t.Fatal("should fail on get license", err) t.Fatal("should fail on get license", err)
} }
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
@@ -9,6 +9,7 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -16,7 +17,7 @@ type SqlOAuthStore struct {
SqlStore SqlStore
} }
func NewSqlOAuthStore(sqlStore SqlStore) OAuthStore { func NewSqlOAuthStore(sqlStore SqlStore) store.OAuthStore {
as := &SqlOAuthStore{sqlStore} as := &SqlOAuthStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -59,12 +60,12 @@ func (as SqlOAuthStore) CreateIndexesIfNotExists() {
as.CreateIndexIfNotExists("idx_oauthauthdata_client_id", "OAuthAuthData", "Code") as.CreateIndexIfNotExists("idx_oauthauthdata_client_id", "OAuthAuthData", "Code")
} }
func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) StoreChannel { func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(app.Id) > 0 { if len(app.Id) > 0 {
result.Err = model.NewAppError("SqlOAuthStore.SaveApp", "store.sql_oauth.save_app.existing.app_error", nil, "app_id="+app.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlOAuthStore.SaveApp", "store.sql_oauth.save_app.existing.app_error", nil, "app_id="+app.Id, http.StatusBadRequest)
@@ -93,12 +94,12 @@ func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) StoreChannel { func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
app.PreUpdate() app.PreUpdate()
@@ -133,12 +134,12 @@ func (as SqlOAuthStore) UpdateApp(app *model.OAuthApp) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetApp(id string) StoreChannel { func (as SqlOAuthStore) GetApp(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if obj, err := as.GetReplica().Get(model.OAuthApp{}, id); err != nil { if obj, err := as.GetReplica().Get(model.OAuthApp{}, id); err != nil {
result.Err = model.NewAppError("SqlOAuthStore.GetApp", "store.sql_oauth.get_app.finding.app_error", nil, "app_id="+id+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlOAuthStore.GetApp", "store.sql_oauth.get_app.finding.app_error", nil, "app_id="+id+", "+err.Error(), http.StatusInternalServerError)
@@ -156,12 +157,12 @@ func (as SqlOAuthStore) GetApp(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) StoreChannel { func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var apps []*model.OAuthApp var apps []*model.OAuthApp
@@ -178,12 +179,12 @@ func (as SqlOAuthStore) GetAppByUser(userId string, offset, limit int) StoreChan
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetApps(offset, limit int) StoreChannel { func (as SqlOAuthStore) GetApps(offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var apps []*model.OAuthApp var apps []*model.OAuthApp
@@ -200,11 +201,11 @@ func (as SqlOAuthStore) GetApps(offset, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) StoreChannel { func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var apps []*model.OAuthApp var apps []*model.OAuthApp
@@ -223,11 +224,11 @@ func (as SqlOAuthStore) GetAuthorizedApps(userId string, offset, limit int) Stor
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) DeleteApp(id string) StoreChannel { func (as SqlOAuthStore) DeleteApp(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
// wrap in a transaction so that if one fails, everything fails // wrap in a transaction so that if one fails, everything fails
transaction, err := as.GetMaster().Begin() transaction, err := as.GetMaster().Begin()
@@ -257,12 +258,12 @@ func (as SqlOAuthStore) DeleteApp(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) StoreChannel { func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if result.Err = accessData.IsValid(); result.Err != nil { if result.Err = accessData.IsValid(); result.Err != nil {
storeChannel <- result storeChannel <- result
@@ -283,12 +284,12 @@ func (as SqlOAuthStore) SaveAccessData(accessData *model.AccessData) StoreChanne
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetAccessData(token string) StoreChannel { func (as SqlOAuthStore) GetAccessData(token string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
accessData := model.AccessData{} accessData := model.AccessData{}
@@ -306,12 +307,12 @@ func (as SqlOAuthStore) GetAccessData(token string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) StoreChannel { func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var accessData []*model.AccessData var accessData []*model.AccessData
@@ -331,12 +332,12 @@ func (as SqlOAuthStore) GetAccessDataByUserForApp(userId, clientId string) Store
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) StoreChannel { func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
accessData := model.AccessData{} accessData := model.AccessData{}
@@ -354,12 +355,12 @@ func (as SqlOAuthStore) GetAccessDataByRefreshToken(token string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) StoreChannel { func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
accessData := model.AccessData{} accessData := model.AccessData{}
@@ -382,11 +383,11 @@ func (as SqlOAuthStore) GetPreviousAccessData(userId, clientId string) StoreChan
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) StoreChannel { func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if result.Err = accessData.IsValid(); result.Err != nil { if result.Err = accessData.IsValid(); result.Err != nil {
storeChannel <- result storeChannel <- result
@@ -409,11 +410,11 @@ func (as SqlOAuthStore) UpdateAccessData(accessData *model.AccessData) StoreChan
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) RemoveAccessData(token string) StoreChannel { func (as SqlOAuthStore) RemoveAccessData(token string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil { if _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
result.Err = model.NewAppError("SqlOAuthStore.RemoveAccessData", "store.sql_oauth.remove_access_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlOAuthStore.RemoveAccessData", "store.sql_oauth.remove_access_data.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
@@ -426,12 +427,12 @@ func (as SqlOAuthStore) RemoveAccessData(token string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) StoreChannel { func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
authData.PreSave() authData.PreSave()
if result.Err = authData.IsValid(); result.Err != nil { if result.Err = authData.IsValid(); result.Err != nil {
@@ -453,12 +454,12 @@ func (as SqlOAuthStore) SaveAuthData(authData *model.AuthData) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) GetAuthData(code string) StoreChannel { func (as SqlOAuthStore) GetAuthData(code string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if obj, err := as.GetReplica().Get(model.AuthData{}, code); err != nil { if obj, err := as.GetReplica().Get(model.AuthData{}, code); err != nil {
result.Err = model.NewAppError("SqlOAuthStore.GetAuthData", "store.sql_oauth.get_auth_data.finding.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlOAuthStore.GetAuthData", "store.sql_oauth.get_auth_data.finding.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -476,11 +477,11 @@ func (as SqlOAuthStore) GetAuthData(code string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) RemoveAuthData(code string) StoreChannel { func (as SqlOAuthStore) RemoveAuthData(code string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := as.GetMaster().Exec("DELETE FROM OAuthAuthData WHERE Code = :Code", map[string]interface{}{"Code": code}) _, err := as.GetMaster().Exec("DELETE FROM OAuthAuthData WHERE Code = :Code", map[string]interface{}{"Code": code})
if err != nil { if err != nil {
@@ -494,11 +495,11 @@ func (as SqlOAuthStore) RemoveAuthData(code string) StoreChannel {
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) StoreChannel { func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}) _, err := as.GetMaster().Exec("DELETE FROM OAuthAccessData WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {
@@ -512,8 +513,8 @@ func (as SqlOAuthStore) PermanentDeleteAuthDataByUser(userId string) StoreChanne
return storeChannel return storeChannel
} }
func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string) StoreResult { func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if _, err := transaction.Exec("DELETE FROM OAuthApps WHERE Id = :Id", map[string]interface{}{"Id": clientId}); err != nil { if _, err := transaction.Exec("DELETE FROM OAuthApps WHERE Id = :Id", map[string]interface{}{"Id": clientId}); err != nil {
result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
@@ -523,8 +524,8 @@ func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string
return as.deleteOAuthAppSessions(transaction, clientId) return as.deleteOAuthAppSessions(transaction, clientId)
} }
func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) StoreResult { func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
query := "" query := ""
if *utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES { if *utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
@@ -541,8 +542,8 @@ func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, cl
return as.deleteOAuthTokens(transaction, clientId) return as.deleteOAuthTokens(transaction, clientId)
} }
func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) StoreResult { func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil { if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil {
result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error(), http.StatusInternalServerError)
@@ -552,8 +553,8 @@ func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientI
return as.deleteAppExtras(transaction, clientId) return as.deleteAppExtras(transaction, clientId)
} }
func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) StoreResult { func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if _, err := transaction.Exec( if _, err := transaction.Exec(
`DELETE FROM `DELETE FROM

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

@@ -1,16 +1,17 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestOAuthStoreSaveApp(t *testing.T) { func TestOAuthStoreSaveApp(t *testing.T) {
Setup() ss := Setup()
a1 := model.OAuthApp{} a1 := model.OAuthApp{}
a1.CreatorId = model.NewId() a1.CreatorId = model.NewId()
@@ -19,45 +20,45 @@ func TestOAuthStoreSaveApp(t *testing.T) {
// Try to save an app that already has an Id // Try to save an app that already has an Id
a1.Id = model.NewId() a1.Id = model.NewId()
if err := (<-store.OAuth().SaveApp(&a1)).Err; err == nil { if err := (<-ss.OAuth().SaveApp(&a1)).Err; err == nil {
t.Fatal("Should have failed, cannot add an OAuth app cannot be save with an Id, it has to be updated") t.Fatal("Should have failed, cannot add an OAuth app cannot be save with an Id, it has to be updated")
} }
// Try to save an Invalid App // Try to save an Invalid App
a1.Id = "" a1.Id = ""
if err := (<-store.OAuth().SaveApp(&a1)).Err; err == nil { if err := (<-ss.OAuth().SaveApp(&a1)).Err; err == nil {
t.Fatal("Should have failed, app should be invalid cause it doesn' have a name set") t.Fatal("Should have failed, app should be invalid cause it doesn' have a name set")
} }
// Save the app // Save the app
a1.Id = "" a1.Id = ""
a1.Name = "TestApp" + model.NewId() a1.Name = "TestApp" + model.NewId()
if err := (<-store.OAuth().SaveApp(&a1)).Err; err != nil { if err := (<-ss.OAuth().SaveApp(&a1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestOAuthStoreGetApp(t *testing.T) { func TestOAuthStoreGetApp(t *testing.T) {
Setup() ss := Setup()
a1 := model.OAuthApp{} a1 := model.OAuthApp{}
a1.CreatorId = model.NewId() a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId() a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"} a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com" a1.Homepage = "https://nowhere.com"
Must(store.OAuth().SaveApp(&a1)) store.Must(ss.OAuth().SaveApp(&a1))
// Lets try to get and app that does not exists // Lets try to get and app that does not exists
if err := (<-store.OAuth().GetApp("fake0123456789abcderfgret1")).Err; err == nil { if err := (<-ss.OAuth().GetApp("fake0123456789abcderfgret1")).Err; err == nil {
t.Fatal("Should have failed. App does not exists") t.Fatal("Should have failed. App does not exists")
} }
if err := (<-store.OAuth().GetApp(a1.Id)).Err; err != nil { if err := (<-ss.OAuth().GetApp(a1.Id)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Lets try and get the app from a user that hasn't created any apps // Lets try and get the app from a user that hasn't created any apps
if result := (<-store.OAuth().GetAppByUser("fake0123456789abcderfgret1", 0, 1000)); result.Err == nil { if result := (<-ss.OAuth().GetAppByUser("fake0123456789abcderfgret1", 0, 1000)); result.Err == nil {
if len(result.Data.([]*model.OAuthApp)) > 0 { if len(result.Data.([]*model.OAuthApp)) > 0 {
t.Fatal("Should have failed. Fake user hasn't created any apps") t.Fatal("Should have failed. Fake user hasn't created any apps")
} }
@@ -65,24 +66,24 @@ func TestOAuthStoreGetApp(t *testing.T) {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if err := (<-store.OAuth().GetAppByUser(a1.CreatorId, 0, 1000)).Err; err != nil { if err := (<-ss.OAuth().GetAppByUser(a1.CreatorId, 0, 1000)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := (<-store.OAuth().GetApps(0, 1000)).Err; err != nil { if err := (<-ss.OAuth().GetApps(0, 1000)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestOAuthStoreUpdateApp(t *testing.T) { func TestOAuthStoreUpdateApp(t *testing.T) {
Setup() ss := Setup()
a1 := model.OAuthApp{} a1 := model.OAuthApp{}
a1.CreatorId = model.NewId() a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId() a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"} a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com" a1.Homepage = "https://nowhere.com"
Must(store.OAuth().SaveApp(&a1)) store.Must(ss.OAuth().SaveApp(&a1))
// temporarily save the created app id // temporarily save the created app id
id := a1.Id id := a1.Id
@@ -93,19 +94,19 @@ func TestOAuthStoreUpdateApp(t *testing.T) {
// Lets update the app by removing the name // Lets update the app by removing the name
a1.Name = "" a1.Name = ""
if result := <-store.OAuth().UpdateApp(&a1); result.Err == nil { if result := <-ss.OAuth().UpdateApp(&a1); result.Err == nil {
t.Fatal("Should have failed. App name is not set") t.Fatal("Should have failed. App name is not set")
} }
// Lets not find the app that we are trying to update // Lets not find the app that we are trying to update
a1.Id = "fake0123456789abcderfgret1" a1.Id = "fake0123456789abcderfgret1"
a1.Name = "NewName" a1.Name = "NewName"
if result := <-store.OAuth().UpdateApp(&a1); result.Err == nil { if result := <-ss.OAuth().UpdateApp(&a1); result.Err == nil {
t.Fatal("Should have failed. Not able to find the app") t.Fatal("Should have failed. Not able to find the app")
} }
a1.Id = id a1.Id = id
if result := <-store.OAuth().UpdateApp(&a1); result.Err != nil { if result := <-ss.OAuth().UpdateApp(&a1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
ua1 := (result.Data.([2]*model.OAuthApp)[0]) ua1 := (result.Data.([2]*model.OAuthApp)[0])
@@ -122,14 +123,14 @@ func TestOAuthStoreUpdateApp(t *testing.T) {
} }
func TestOAuthStoreSaveAccessData(t *testing.T) { func TestOAuthStoreSaveAccessData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AccessData{} a1 := model.AccessData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
a1.UserId = model.NewId() a1.UserId = model.NewId()
// Lets try and save an incomplete access data // Lets try and save an incomplete access data
if err := (<-store.OAuth().SaveAccessData(&a1)).Err; err == nil { if err := (<-ss.OAuth().SaveAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed. Access data needs the token") t.Fatal("Should have failed. Access data needs the token")
} }
@@ -137,13 +138,13 @@ func TestOAuthStoreSaveAccessData(t *testing.T) {
a1.RefreshToken = model.NewId() a1.RefreshToken = model.NewId()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
if err := (<-store.OAuth().SaveAccessData(&a1)).Err; err != nil { if err := (<-ss.OAuth().SaveAccessData(&a1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestOAuthUpdateAccessData(t *testing.T) { func TestOAuthUpdateAccessData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AccessData{} a1 := model.AccessData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
@@ -152,25 +153,25 @@ func TestOAuthUpdateAccessData(t *testing.T) {
a1.RefreshToken = model.NewId() a1.RefreshToken = model.NewId()
a1.ExpiresAt = model.GetMillis() a1.ExpiresAt = model.GetMillis()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAccessData(&a1)) store.Must(ss.OAuth().SaveAccessData(&a1))
//Try to update to invalid Refresh Token //Try to update to invalid Refresh Token
refreshToken := a1.RefreshToken refreshToken := a1.RefreshToken
a1.RefreshToken = model.NewId() + "123" a1.RefreshToken = model.NewId() + "123"
if err := (<-store.OAuth().UpdateAccessData(&a1)).Err; err == nil { if err := (<-ss.OAuth().UpdateAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed with invalid token") t.Fatal("Should have failed with invalid token")
} }
//Try to update to invalid RedirectUri //Try to update to invalid RedirectUri
a1.RefreshToken = model.NewId() a1.RefreshToken = model.NewId()
a1.RedirectUri = "" a1.RedirectUri = ""
if err := (<-store.OAuth().UpdateAccessData(&a1)).Err; err == nil { if err := (<-ss.OAuth().UpdateAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed with invalid Redirect URI") t.Fatal("Should have failed with invalid Redirect URI")
} }
// Should update fine // Should update fine
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
if result := <-store.OAuth().UpdateAccessData(&a1); result.Err != nil { if result := <-ss.OAuth().UpdateAccessData(&a1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
ra1 := result.Data.(*model.AccessData) ra1 := result.Data.(*model.AccessData)
@@ -181,7 +182,7 @@ func TestOAuthUpdateAccessData(t *testing.T) {
} }
func TestOAuthStoreGetAccessData(t *testing.T) { func TestOAuthStoreGetAccessData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AccessData{} a1 := model.AccessData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
@@ -190,13 +191,13 @@ func TestOAuthStoreGetAccessData(t *testing.T) {
a1.RefreshToken = model.NewId() a1.RefreshToken = model.NewId()
a1.ExpiresAt = model.GetMillis() a1.ExpiresAt = model.GetMillis()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAccessData(&a1)) store.Must(ss.OAuth().SaveAccessData(&a1))
if err := (<-store.OAuth().GetAccessData("invalidToken")).Err; err == nil { if err := (<-ss.OAuth().GetAccessData("invalidToken")).Err; err == nil {
t.Fatal("Should have failed. There is no data with an invalid token") t.Fatal("Should have failed. There is no data with an invalid token")
} }
if result := <-store.OAuth().GetAccessData(a1.Token); result.Err != nil { if result := <-ss.OAuth().GetAccessData(a1.Token); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
ra1 := result.Data.(*model.AccessData) ra1 := result.Data.(*model.AccessData)
@@ -205,21 +206,21 @@ func TestOAuthStoreGetAccessData(t *testing.T) {
} }
} }
if err := (<-store.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)).Err; err != nil { if err := (<-ss.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := (<-store.OAuth().GetPreviousAccessData("user", "junk")).Err; err != nil { if err := (<-ss.OAuth().GetPreviousAccessData("user", "junk")).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Try to get the Access data using an invalid refresh token // Try to get the Access data using an invalid refresh token
if err := (<-store.OAuth().GetAccessDataByRefreshToken(a1.Token)).Err; err == nil { if err := (<-ss.OAuth().GetAccessDataByRefreshToken(a1.Token)).Err; err == nil {
t.Fatal("Should have failed. There is no data with an invalid token") t.Fatal("Should have failed. There is no data with an invalid token")
} }
// Get the Access Data using the refresh token // Get the Access Data using the refresh token
if result := <-store.OAuth().GetAccessDataByRefreshToken(a1.RefreshToken); result.Err != nil { if result := <-ss.OAuth().GetAccessDataByRefreshToken(a1.RefreshToken); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
ra1 := result.Data.(*model.AccessData) ra1 := result.Data.(*model.AccessData)
@@ -230,7 +231,7 @@ func TestOAuthStoreGetAccessData(t *testing.T) {
} }
func TestOAuthStoreRemoveAccessData(t *testing.T) { func TestOAuthStoreRemoveAccessData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AccessData{} a1 := model.AccessData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
@@ -238,13 +239,13 @@ func TestOAuthStoreRemoveAccessData(t *testing.T) {
a1.Token = model.NewId() a1.Token = model.NewId()
a1.RefreshToken = model.NewId() a1.RefreshToken = model.NewId()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAccessData(&a1)) store.Must(ss.OAuth().SaveAccessData(&a1))
if err := (<-store.OAuth().RemoveAccessData(a1.Token)).Err; err != nil { if err := (<-ss.OAuth().RemoveAccessData(a1.Token)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result := (<-store.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)); result.Err != nil { if result := (<-ss.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)); result.Err != nil {
} else { } else {
if result.Data != nil { if result.Data != nil {
t.Fatal("did not delete access token") t.Fatal("did not delete access token")
@@ -253,79 +254,79 @@ func TestOAuthStoreRemoveAccessData(t *testing.T) {
} }
func TestOAuthStoreSaveAuthData(t *testing.T) { func TestOAuthStoreSaveAuthData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AuthData{} a1 := model.AuthData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
a1.UserId = model.NewId() a1.UserId = model.NewId()
a1.Code = model.NewId() a1.Code = model.NewId()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
if err := (<-store.OAuth().SaveAuthData(&a1)).Err; err != nil { if err := (<-ss.OAuth().SaveAuthData(&a1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestOAuthStoreGetAuthData(t *testing.T) { func TestOAuthStoreGetAuthData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AuthData{} a1 := model.AuthData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
a1.UserId = model.NewId() a1.UserId = model.NewId()
a1.Code = model.NewId() a1.Code = model.NewId()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAuthData(&a1)) store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-store.OAuth().GetAuthData(a1.Code)).Err; err != nil { if err := (<-ss.OAuth().GetAuthData(a1.Code)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestOAuthStoreRemoveAuthData(t *testing.T) { func TestOAuthStoreRemoveAuthData(t *testing.T) {
Setup() ss := Setup()
a1 := model.AuthData{} a1 := model.AuthData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
a1.UserId = model.NewId() a1.UserId = model.NewId()
a1.Code = model.NewId() a1.Code = model.NewId()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAuthData(&a1)) store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-store.OAuth().RemoveAuthData(a1.Code)).Err; err != nil { if err := (<-ss.OAuth().RemoveAuthData(a1.Code)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := (<-store.OAuth().GetAuthData(a1.Code)).Err; err == nil { if err := (<-ss.OAuth().GetAuthData(a1.Code)).Err; err == nil {
t.Fatal("should have errored - auth code removed") t.Fatal("should have errored - auth code removed")
} }
} }
func TestOAuthStoreRemoveAuthDataByUser(t *testing.T) { func TestOAuthStoreRemoveAuthDataByUser(t *testing.T) {
Setup() ss := Setup()
a1 := model.AuthData{} a1 := model.AuthData{}
a1.ClientId = model.NewId() a1.ClientId = model.NewId()
a1.UserId = model.NewId() a1.UserId = model.NewId()
a1.Code = model.NewId() a1.Code = model.NewId()
a1.RedirectUri = "http://example.com" a1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAuthData(&a1)) store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-store.OAuth().PermanentDeleteAuthDataByUser(a1.UserId)).Err; err != nil { if err := (<-ss.OAuth().PermanentDeleteAuthDataByUser(a1.UserId)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestOAuthGetAuthorizedApps(t *testing.T) { func TestOAuthGetAuthorizedApps(t *testing.T) {
Setup() ss := Setup()
a1 := model.OAuthApp{} a1 := model.OAuthApp{}
a1.CreatorId = model.NewId() a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId() a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"} a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com" a1.Homepage = "https://nowhere.com"
Must(store.OAuth().SaveApp(&a1)) store.Must(ss.OAuth().SaveApp(&a1))
// Lets try and get an Authorized app for a user who hasn't authorized it // Lets try and get an Authorized app for a user who hasn't authorized it
if result := <-store.OAuth().GetAuthorizedApps("fake0123456789abcderfgret1", 0, 1000); result.Err == nil { if result := <-ss.OAuth().GetAuthorizedApps("fake0123456789abcderfgret1", 0, 1000); result.Err == nil {
if len(result.Data.([]*model.OAuthApp)) > 0 { if len(result.Data.([]*model.OAuthApp)) > 0 {
t.Fatal("Should have failed. Fake user hasn't authorized the app") t.Fatal("Should have failed. Fake user hasn't authorized the app")
} }
@@ -339,9 +340,9 @@ func TestOAuthGetAuthorizedApps(t *testing.T) {
p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP
p.Name = a1.Id p.Name = a1.Id
p.Value = "true" p.Value = "true"
Must(store.Preference().Save(&model.Preferences{p})) store.Must(ss.Preference().Save(&model.Preferences{p}))
if result := <-store.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil { if result := <-ss.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
apps := result.Data.([]*model.OAuthApp) apps := result.Data.([]*model.OAuthApp)
@@ -352,14 +353,14 @@ func TestOAuthGetAuthorizedApps(t *testing.T) {
} }
func TestOAuthGetAccessDataByUserForApp(t *testing.T) { func TestOAuthGetAccessDataByUserForApp(t *testing.T) {
Setup() ss := Setup()
a1 := model.OAuthApp{} a1 := model.OAuthApp{}
a1.CreatorId = model.NewId() a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId() a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"} a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com" a1.Homepage = "https://nowhere.com"
Must(store.OAuth().SaveApp(&a1)) store.Must(ss.OAuth().SaveApp(&a1))
// allow the app // allow the app
p := model.Preference{} p := model.Preference{}
@@ -367,9 +368,9 @@ func TestOAuthGetAccessDataByUserForApp(t *testing.T) {
p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP
p.Name = a1.Id p.Name = a1.Id
p.Value = "true" p.Value = "true"
Must(store.Preference().Save(&model.Preferences{p})) store.Must(ss.Preference().Save(&model.Preferences{p}))
if result := <-store.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil { if result := <-ss.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
apps := result.Data.([]*model.OAuthApp) apps := result.Data.([]*model.OAuthApp)
@@ -386,11 +387,11 @@ func TestOAuthGetAccessDataByUserForApp(t *testing.T) {
ad1.RefreshToken = model.NewId() ad1.RefreshToken = model.NewId()
ad1.RedirectUri = "http://example.com" ad1.RedirectUri = "http://example.com"
if err := (<-store.OAuth().SaveAccessData(&ad1)).Err; err != nil { if err := (<-ss.OAuth().SaveAccessData(&ad1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result := <-store.OAuth().GetAccessDataByUserForApp(a1.CreatorId, a1.Id); result.Err != nil { if result := <-ss.OAuth().GetAccessDataByUserForApp(a1.CreatorId, a1.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
accessData := result.Data.([]*model.AccessData) accessData := result.Data.([]*model.AccessData)
@@ -401,17 +402,17 @@ func TestOAuthGetAccessDataByUserForApp(t *testing.T) {
} }
func TestOAuthStoreDeleteApp(t *testing.T) { func TestOAuthStoreDeleteApp(t *testing.T) {
Setup() ss := Setup()
a1 := model.OAuthApp{} a1 := model.OAuthApp{}
a1.CreatorId = model.NewId() a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId() a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"} a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com" a1.Homepage = "https://nowhere.com"
Must(store.OAuth().SaveApp(&a1)) store.Must(ss.OAuth().SaveApp(&a1))
// delete a non-existent app // delete a non-existent app
if err := (<-store.OAuth().DeleteApp("fakeclientId")).Err; err != nil { if err := (<-ss.OAuth().DeleteApp("fakeclientId")).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -420,7 +421,7 @@ func TestOAuthStoreDeleteApp(t *testing.T) {
s1.Token = model.NewId() s1.Token = model.NewId()
s1.IsOAuth = true s1.IsOAuth = true
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
ad1 := model.AccessData{} ad1 := model.AccessData{}
ad1.ClientId = a1.Id ad1.ClientId = a1.Id
@@ -429,17 +430,17 @@ func TestOAuthStoreDeleteApp(t *testing.T) {
ad1.RefreshToken = model.NewId() ad1.RefreshToken = model.NewId()
ad1.RedirectUri = "http://example.com" ad1.RedirectUri = "http://example.com"
Must(store.OAuth().SaveAccessData(&ad1)) store.Must(ss.OAuth().SaveAccessData(&ad1))
if err := (<-store.OAuth().DeleteApp(a1.Id)).Err; err != nil { if err := (<-ss.OAuth().DeleteApp(a1.Id)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := (<-store.Session().Get(s1.Token)).Err; err == nil { if err := (<-ss.Session().Get(s1.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted") t.Fatal("should error - session should be deleted")
} }
if err := (<-store.OAuth().GetAccessData(s1.Token)).Err; err == nil { if err := (<-ss.OAuth().GetAccessData(s1.Token)).Err; err == nil {
t.Fatal("should error - access data should be deleted") t.Fatal("should error - access data should be deleted")
} }
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"fmt" "fmt"
@@ -13,6 +13,7 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -37,7 +38,7 @@ func ClearPostCaches() {
lastPostsCache.Purge() lastPostsCache.Purge()
} }
func NewSqlPostStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) PostStore { func NewSqlPostStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.PostStore {
s := &SqlPostStore{ s := &SqlPostStore{
SqlStore: sqlStore, SqlStore: sqlStore,
metrics: metrics, metrics: metrics,
@@ -75,11 +76,11 @@ func (s SqlPostStore) CreateIndexesIfNotExists() {
s.CreateFullTextIndexIfNotExists("idx_posts_hashtags_txt", "Posts", "Hashtags") s.CreateFullTextIndexIfNotExists("idx_posts_hashtags_txt", "Posts", "Hashtags")
} }
func (s SqlPostStore) Save(post *model.Post) StoreChannel { func (s SqlPostStore) Save(post *model.Post) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(post.Id) > 0 { if len(post.Id) > 0 {
result.Err = model.NewAppError("SqlPostStore.Save", "store.sql_post.save.existing.app_error", nil, "id="+post.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlPostStore.Save", "store.sql_post.save.existing.app_error", nil, "id="+post.Id, http.StatusBadRequest)
@@ -122,11 +123,11 @@ func (s SqlPostStore) Save(post *model.Post) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) Update(newPost *model.Post, oldPost *model.Post) StoreChannel { func (s SqlPostStore) Update(newPost *model.Post, oldPost *model.Post) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
newPost.UpdateAt = model.GetMillis() newPost.UpdateAt = model.GetMillis()
newPost.PreCommit() newPost.PreCommit()
@@ -166,11 +167,11 @@ func (s SqlPostStore) Update(newPost *model.Post, oldPost *model.Post) StoreChan
return storeChannel return storeChannel
} }
func (s SqlPostStore) Overwrite(post *model.Post) StoreChannel { func (s SqlPostStore) Overwrite(post *model.Post) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
post.UpdateAt = model.GetMillis() post.UpdateAt = model.GetMillis()
@@ -193,10 +194,10 @@ func (s SqlPostStore) Overwrite(post *model.Post) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetFlaggedPosts(userId string, offset int, limit int) StoreChannel { func (s SqlPostStore) GetFlaggedPosts(userId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
pl := model.NewPostList() pl := model.NewPostList()
var posts []*model.Post var posts []*model.Post
@@ -218,10 +219,10 @@ func (s SqlPostStore) GetFlaggedPosts(userId string, offset int, limit int) Stor
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetFlaggedPostsForTeam(userId, teamId string, offset int, limit int) StoreChannel { func (s SqlPostStore) GetFlaggedPostsForTeam(userId, teamId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
pl := model.NewPostList() pl := model.NewPostList()
var posts []*model.Post var posts []*model.Post
@@ -270,10 +271,10 @@ func (s SqlPostStore) GetFlaggedPostsForTeam(userId, teamId string, offset int,
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offset int, limit int) StoreChannel { func (s SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
pl := model.NewPostList() pl := model.NewPostList()
var posts []*model.Post var posts []*model.Post
@@ -306,11 +307,11 @@ func (s SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offset
return storeChannel return storeChannel
} }
func (s SqlPostStore) Get(id string) StoreChannel { func (s SqlPostStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
pl := model.NewPostList() pl := model.NewPostList()
if len(id) == 0 { if len(id) == 0 {
@@ -367,11 +368,11 @@ func (s SqlPostStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetSingle(id string) StoreChannel { func (s SqlPostStore) GetSingle(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var post model.Post var post model.Post
err := s.GetReplica().SelectOne(&post, "SELECT * FROM Posts WHERE Id = :Id AND DeleteAt = 0", map[string]interface{}{"Id": id}) err := s.GetReplica().SelectOne(&post, "SELECT * FROM Posts WHERE Id = :Id AND DeleteAt = 0", map[string]interface{}{"Id": id})
@@ -398,11 +399,11 @@ func (s SqlPostStore) InvalidateLastPostTimeCache(channelId string) {
lastPostsCache.Remove(channelId) lastPostsCache.Remove(channelId)
} }
func (s SqlPostStore) GetEtag(channelId string, allowFromCache bool) StoreChannel { func (s SqlPostStore) GetEtag(channelId string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := lastPostTimeCache.Get(channelId); ok { if cacheItem, ok := lastPostTimeCache.Get(channelId); ok {
@@ -441,11 +442,11 @@ func (s SqlPostStore) GetEtag(channelId string, allowFromCache bool) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlPostStore) Delete(postId string, time int64) StoreChannel { func (s SqlPostStore) Delete(postId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("Update Posts SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id OR RootId = :RootId", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": postId, "RootId": postId}) _, err := s.GetMaster().Exec("Update Posts SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id OR RootId = :RootId", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": postId, "RootId": postId})
if err != nil { if err != nil {
@@ -459,11 +460,11 @@ func (s SqlPostStore) Delete(postId string, time int64) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) permanentDelete(postId string) StoreChannel { func (s SqlPostStore) permanentDelete(postId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM Posts WHERE Id = :Id OR RootId = :RootId", map[string]interface{}{"Id": postId, "RootId": postId}) _, err := s.GetMaster().Exec("DELETE FROM Posts WHERE Id = :Id OR RootId = :RootId", map[string]interface{}{"Id": postId, "RootId": postId})
if err != nil { if err != nil {
@@ -477,11 +478,11 @@ func (s SqlPostStore) permanentDelete(postId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) permanentDeleteAllCommentByUser(userId string) StoreChannel { func (s SqlPostStore) permanentDeleteAllCommentByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM Posts WHERE UserId = :UserId AND RootId != ''", map[string]interface{}{"UserId": userId}) _, err := s.GetMaster().Exec("DELETE FROM Posts WHERE UserId = :UserId AND RootId != ''", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {
@@ -495,11 +496,11 @@ func (s SqlPostStore) permanentDeleteAllCommentByUser(userId string) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlPostStore) PermanentDeleteByUser(userId string) StoreChannel { func (s SqlPostStore) PermanentDeleteByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
// First attempt to delete all the comments for a user // First attempt to delete all the comments for a user
if r := <-s.permanentDeleteAllCommentByUser(userId); r.Err != nil { if r := <-s.permanentDeleteAllCommentByUser(userId); r.Err != nil {
@@ -552,11 +553,11 @@ func (s SqlPostStore) PermanentDeleteByUser(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) PermanentDeleteByChannel(channelId string) StoreChannel { func (s SqlPostStore) PermanentDeleteByChannel(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM Posts WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId}); err != nil { if _, err := s.GetMaster().Exec("DELETE FROM Posts WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId}); err != nil {
result.Err = model.NewAppError("SqlPostStore.PermanentDeleteByChannel", "store.sql_post.permanent_delete_by_channel.app_error", nil, "channel_id="+channelId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlPostStore.PermanentDeleteByChannel", "store.sql_post.permanent_delete_by_channel.app_error", nil, "channel_id="+channelId+", "+err.Error(), http.StatusInternalServerError)
@@ -569,11 +570,11 @@ func (s SqlPostStore) PermanentDeleteByChannel(channelId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFromCache bool) StoreChannel { func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if limit > 1000 { if limit > 1000 {
result.Err = model.NewAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+channelId, http.StatusBadRequest) result.Err = model.NewAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+channelId, http.StatusBadRequest)
@@ -641,11 +642,11 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache bool) StoreChannel { func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
// If the last post in the channel's time is less than or equal to the time we are getting posts since, // If the last post in the channel's time is less than or equal to the time we are getting posts since,
@@ -729,19 +730,19 @@ func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetPostsBefore(channelId string, postId string, numPosts int, offset int) StoreChannel { func (s SqlPostStore) GetPostsBefore(channelId string, postId string, numPosts int, offset int) store.StoreChannel {
return s.getPostsAround(channelId, postId, numPosts, offset, true) return s.getPostsAround(channelId, postId, numPosts, offset, true)
} }
func (s SqlPostStore) GetPostsAfter(channelId string, postId string, numPosts int, offset int) StoreChannel { func (s SqlPostStore) GetPostsAfter(channelId string, postId string, numPosts int, offset int) store.StoreChannel {
return s.getPostsAround(channelId, postId, numPosts, offset, false) return s.getPostsAround(channelId, postId, numPosts, offset, false)
} }
func (s SqlPostStore) getPostsAround(channelId string, postId string, numPosts int, offset int, before bool) StoreChannel { func (s SqlPostStore) getPostsAround(channelId string, postId string, numPosts int, offset int, before bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var direction string var direction string
var sort string var sort string
@@ -827,11 +828,11 @@ func (s SqlPostStore) getPostsAround(channelId string, postId string, numPosts i
return storeChannel return storeChannel
} }
func (s SqlPostStore) getRootPosts(channelId string, offset int, limit int) StoreChannel { func (s SqlPostStore) getRootPosts(channelId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var posts []*model.Post 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}) _, 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})
@@ -848,11 +849,11 @@ func (s SqlPostStore) getRootPosts(channelId string, offset int, limit int) Stor
return storeChannel return storeChannel
} }
func (s SqlPostStore) getParentsPosts(channelId string, offset int, limit int) StoreChannel { func (s SqlPostStore) getParentsPosts(channelId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var posts []*model.Post var posts []*model.Post
_, err := s.GetReplica().Select(&posts, _, err := s.GetReplica().Select(&posts,
@@ -905,11 +906,11 @@ var specialSearchChar = []string{
":", ":",
} }
func (s SqlPostStore) Search(teamId string, userId string, params *model.SearchParams) StoreChannel { func (s SqlPostStore) Search(teamId string, userId string, params *model.SearchParams) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if !*utils.Cfg.ServiceSettings.EnablePostSearch { if !*utils.Cfg.ServiceSettings.EnablePostSearch {
list := model.NewPostList() list := model.NewPostList()
@@ -1100,11 +1101,11 @@ func (s SqlPostStore) Search(teamId string, userId string, params *model.SearchP
return storeChannel return storeChannel
} }
func (s SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) StoreChannel { func (s SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT DISTINCT `SELECT DISTINCT
@@ -1162,11 +1163,11 @@ func (s SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) StoreChan
return storeChannel return storeChannel
} }
func (s SqlPostStore) AnalyticsPostCountsByDay(teamId string) StoreChannel { func (s SqlPostStore) AnalyticsPostCountsByDay(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT `SELECT
@@ -1226,11 +1227,11 @@ func (s SqlPostStore) AnalyticsPostCountsByDay(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) AnalyticsPostCount(teamId string, mustHaveFile bool, mustHaveHashtag bool) StoreChannel { func (s SqlPostStore) AnalyticsPostCount(teamId string, mustHaveFile bool, mustHaveHashtag bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT `SELECT
@@ -1266,11 +1267,11 @@ func (s SqlPostStore) AnalyticsPostCount(teamId string, mustHaveFile bool, mustH
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetPostsCreatedAt(channelId string, time int64) StoreChannel { func (s SqlPostStore) GetPostsCreatedAt(channelId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := `SELECT * FROM Posts WHERE CreateAt = :CreateAt` query := `SELECT * FROM Posts WHERE CreateAt = :CreateAt`
@@ -1290,11 +1291,11 @@ func (s SqlPostStore) GetPostsCreatedAt(channelId string, time int64) StoreChann
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetPostsByIds(postIds []string) StoreChannel { func (s SqlPostStore) GetPostsByIds(postIds []string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
inClause := `'` + strings.Join(postIds, `', '`) + `'` inClause := `'` + strings.Join(postIds, `', '`) + `'`
@@ -1317,11 +1318,11 @@ func (s SqlPostStore) GetPostsByIds(postIds []string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPostStore) GetPostsBatchForIndexing(startTime int64, limit int) StoreChannel { func (s SqlPostStore) GetPostsBatchForIndexing(startTime int64, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var posts []*model.PostForIndexing var posts []*model.PostForIndexing
_, err1 := s.GetSearchReplica().Select(&posts, _, err1 := s.GetSearchReplica().Select(&posts,
@@ -1358,11 +1359,11 @@ func (s SqlPostStore) GetPostsBatchForIndexing(startTime int64, limit int) Store
return storeChannel return storeChannel
} }
func (s SqlPostStore) PermanentDeleteBatch(endTime int64, limit int64) StoreChannel { func (s SqlPostStore) PermanentDeleteBatch(endTime int64, limit int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var query string var query string
if *utils.Cfg.SqlSettings.DriverName == "postgres" { if *utils.Cfg.SqlSettings.DriverName == "postgres" {

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
@@ -10,6 +10,7 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -21,7 +22,7 @@ const (
FEATURE_TOGGLE_PREFIX = "feature_enabled_" FEATURE_TOGGLE_PREFIX = "feature_enabled_"
) )
func NewSqlPreferenceStore(sqlStore SqlStore) PreferenceStore { func NewSqlPreferenceStore(sqlStore SqlStore) store.PreferenceStore {
s := &SqlPreferenceStore{sqlStore} s := &SqlPreferenceStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -58,11 +59,11 @@ func (s SqlPreferenceStore) DeleteUnusedFeatures() {
s.GetMaster().Exec(sql, queryParams) s.GetMaster().Exec(sql, queryParams)
} }
func (s SqlPreferenceStore) Save(preferences *model.Preferences) StoreChannel { func (s SqlPreferenceStore) Save(preferences *model.Preferences) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
// wrap in a transaction so that if one fails, everything fails // wrap in a transaction so that if one fails, everything fails
transaction, err := s.GetMaster().Begin() transaction, err := s.GetMaster().Begin()
@@ -97,8 +98,8 @@ func (s SqlPreferenceStore) Save(preferences *model.Preferences) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *model.Preference) StoreResult { func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *model.Preference) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
preference.PreUpdate() preference.PreUpdate()
@@ -152,8 +153,8 @@ func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *mode
return result return result
} }
func (s SqlPreferenceStore) insert(transaction *gorp.Transaction, preference *model.Preference) StoreResult { func (s SqlPreferenceStore) insert(transaction *gorp.Transaction, preference *model.Preference) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if err := transaction.Insert(preference); err != nil { if err := transaction.Insert(preference); err != nil {
if IsUniqueConstraintError(err, []string{"UserId", "preferences_pkey"}) { if IsUniqueConstraintError(err, []string{"UserId", "preferences_pkey"}) {
@@ -168,8 +169,8 @@ func (s SqlPreferenceStore) insert(transaction *gorp.Transaction, preference *mo
return result return result
} }
func (s SqlPreferenceStore) update(transaction *gorp.Transaction, preference *model.Preference) StoreResult { func (s SqlPreferenceStore) update(transaction *gorp.Transaction, preference *model.Preference) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if _, err := transaction.Update(preference); err != nil { if _, err := transaction.Update(preference); err != nil {
result.Err = model.NewAppError("SqlPreferenceStore.update", "store.sql_preference.update.app_error", nil, result.Err = model.NewAppError("SqlPreferenceStore.update", "store.sql_preference.update.app_error", nil,
@@ -179,11 +180,11 @@ func (s SqlPreferenceStore) update(transaction *gorp.Transaction, preference *mo
return result return result
} }
func (s SqlPreferenceStore) Get(userId string, category string, name string) StoreChannel { func (s SqlPreferenceStore) Get(userId string, category string, name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var preference model.Preference var preference model.Preference
@@ -208,11 +209,11 @@ func (s SqlPreferenceStore) Get(userId string, category string, name string) Sto
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) GetCategory(userId string, category string) StoreChannel { func (s SqlPreferenceStore) GetCategory(userId string, category string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var preferences model.Preferences var preferences model.Preferences
@@ -236,11 +237,11 @@ func (s SqlPreferenceStore) GetCategory(userId string, category string) StoreCha
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) GetAll(userId string) StoreChannel { func (s SqlPreferenceStore) GetAll(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var preferences model.Preferences var preferences model.Preferences
@@ -263,11 +264,11 @@ func (s SqlPreferenceStore) GetAll(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) PermanentDeleteByUser(userId string) StoreChannel { func (s SqlPreferenceStore) PermanentDeleteByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec( if _, err := s.GetMaster().Exec(
`DELETE FROM Preferences WHERE UserId = :UserId`, map[string]interface{}{"UserId": userId}); err != nil { `DELETE FROM Preferences WHERE UserId = :UserId`, map[string]interface{}{"UserId": userId}); err != nil {
@@ -281,11 +282,11 @@ func (s SqlPreferenceStore) PermanentDeleteByUser(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) IsFeatureEnabled(feature, userId string) StoreChannel { func (s SqlPreferenceStore) IsFeatureEnabled(feature, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if value, err := s.GetReplica().SelectStr(`SELECT if value, err := s.GetReplica().SelectStr(`SELECT
value value
FROM FROM
@@ -306,11 +307,11 @@ func (s SqlPreferenceStore) IsFeatureEnabled(feature, userId string) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) Delete(userId, category, name string) StoreChannel { func (s SqlPreferenceStore) Delete(userId, category, name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec( if _, err := s.GetMaster().Exec(
`DELETE FROM `DELETE FROM
@@ -329,11 +330,11 @@ func (s SqlPreferenceStore) Delete(userId, category, name string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) DeleteCategory(userId string, category string) StoreChannel { func (s SqlPreferenceStore) DeleteCategory(userId string, category string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec( if _, err := s.GetMaster().Exec(
`DELETE FROM `DELETE FROM
@@ -351,11 +352,11 @@ func (s SqlPreferenceStore) DeleteCategory(userId string, category string) Store
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) DeleteCategoryAndName(category string, name string) StoreChannel { func (s SqlPreferenceStore) DeleteCategoryAndName(category string, name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec( if _, err := s.GetMaster().Exec(
`DELETE FROM `DELETE FROM
@@ -373,11 +374,11 @@ func (s SqlPreferenceStore) DeleteCategoryAndName(category string, name string)
return storeChannel return storeChannel
} }
func (s SqlPreferenceStore) CleanupFlagsBatch(limit int64) StoreChannel { func (s SqlPreferenceStore) CleanupFlagsBatch(limit int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`DELETE FROM `DELETE FROM

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
@@ -9,10 +9,11 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestPreferenceSave(t *testing.T) { func TestPreferenceSave(t *testing.T) {
Setup() ss := Setup()
id := model.NewId() id := model.NewId()
@@ -30,31 +31,31 @@ func TestPreferenceSave(t *testing.T) {
Value: "value1b", Value: "value1b",
}, },
} }
if count := Must(store.Preference().Save(&preferences)); count != 2 { if count := store.Must(ss.Preference().Save(&preferences)); count != 2 {
t.Fatal("got incorrect number of rows saved") t.Fatal("got incorrect number of rows saved")
} }
for _, preference := range preferences { for _, preference := range preferences {
if data := Must(store.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data { if data := store.Must(ss.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
t.Fatal("got incorrect preference after first Save") t.Fatal("got incorrect preference after first Save")
} }
} }
preferences[0].Value = "value2a" preferences[0].Value = "value2a"
preferences[1].Value = "value2b" preferences[1].Value = "value2b"
if count := Must(store.Preference().Save(&preferences)); count != 2 { if count := store.Must(ss.Preference().Save(&preferences)); count != 2 {
t.Fatal("got incorrect number of rows saved") t.Fatal("got incorrect number of rows saved")
} }
for _, preference := range preferences { for _, preference := range preferences {
if data := Must(store.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data { if data := store.Must(ss.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
t.Fatal("got incorrect preference after second Save") t.Fatal("got incorrect preference after second Save")
} }
} }
} }
func TestPreferenceGet(t *testing.T) { func TestPreferenceGet(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
@@ -83,22 +84,22 @@ func TestPreferenceGet(t *testing.T) {
}, },
} }
Must(store.Preference().Save(&preferences)) store.Must(ss.Preference().Save(&preferences))
if result := <-store.Preference().Get(userId, category, name); result.Err != nil { if result := <-ss.Preference().Get(userId, category, name); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(model.Preference); data != preferences[0] { } else if data := result.Data.(model.Preference); data != preferences[0] {
t.Fatal("got incorrect preference") t.Fatal("got incorrect preference")
} }
// make sure getting a missing preference fails // make sure getting a missing preference fails
if result := <-store.Preference().Get(model.NewId(), model.NewId(), model.NewId()); result.Err == nil { if result := <-ss.Preference().Get(model.NewId(), model.NewId(), model.NewId()); result.Err == nil {
t.Fatal("no error on getting a missing preference") t.Fatal("no error on getting a missing preference")
} }
} }
func TestPreferenceGetCategory(t *testing.T) { func TestPreferenceGetCategory(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
@@ -130,9 +131,9 @@ func TestPreferenceGetCategory(t *testing.T) {
}, },
} }
Must(store.Preference().Save(&preferences)) store.Must(ss.Preference().Save(&preferences))
if result := <-store.Preference().GetCategory(userId, category); result.Err != nil { if result := <-ss.Preference().GetCategory(userId, category); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 2 { } else if data := result.Data.(model.Preferences); len(data) != 2 {
t.Fatal("got the wrong number of preferences") t.Fatal("got the wrong number of preferences")
@@ -141,7 +142,7 @@ func TestPreferenceGetCategory(t *testing.T) {
} }
// make sure getting a missing preference category doesn't fail // make sure getting a missing preference category doesn't fail
if result := <-store.Preference().GetCategory(model.NewId(), model.NewId()); result.Err != nil { if result := <-ss.Preference().GetCategory(model.NewId(), model.NewId()); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 0 { } else if data := result.Data.(model.Preferences); len(data) != 0 {
t.Fatal("shouldn't have got any preferences") t.Fatal("shouldn't have got any preferences")
@@ -149,7 +150,7 @@ func TestPreferenceGetCategory(t *testing.T) {
} }
func TestPreferenceGetAll(t *testing.T) { func TestPreferenceGetAll(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
@@ -181,9 +182,9 @@ func TestPreferenceGetAll(t *testing.T) {
}, },
} }
Must(store.Preference().Save(&preferences)) store.Must(ss.Preference().Save(&preferences))
if result := <-store.Preference().GetAll(userId); result.Err != nil { if result := <-ss.Preference().GetAll(userId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 3 { } else if data := result.Data.(model.Preferences); len(data) != 3 {
t.Fatal("got the wrong number of preferences") t.Fatal("got the wrong number of preferences")
@@ -197,7 +198,7 @@ func TestPreferenceGetAll(t *testing.T) {
} }
func TestPreferenceDeleteByUser(t *testing.T) { func TestPreferenceDeleteByUser(t *testing.T) {
Setup() ss := Setup()
userId := model.NewId() userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
@@ -229,15 +230,15 @@ func TestPreferenceDeleteByUser(t *testing.T) {
}, },
} }
Must(store.Preference().Save(&preferences)) store.Must(ss.Preference().Save(&preferences))
if result := <-store.Preference().PermanentDeleteByUser(userId); result.Err != nil { if result := <-ss.Preference().PermanentDeleteByUser(userId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestIsFeatureEnabled(t *testing.T) { func TestIsFeatureEnabled(t *testing.T) {
Setup() ss := Setup()
feature1 := "testFeat1" feature1 := "testFeat1"
feature2 := "testFeat2" feature2 := "testFeat2"
@@ -279,29 +280,29 @@ func TestIsFeatureEnabled(t *testing.T) {
}, },
} }
Must(store.Preference().Save(&features)) store.Must(ss.Preference().Save(&features))
if result := <-store.Preference().IsFeatureEnabled(feature1, userId); result.Err != nil { if result := <-ss.Preference().IsFeatureEnabled(feature1, userId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(bool); data != true { } else if data := result.Data.(bool); data != true {
t.Fatalf("got incorrect setting for feature1, %v=%v", true, data) t.Fatalf("got incorrect setting for feature1, %v=%v", true, data)
} }
if result := <-store.Preference().IsFeatureEnabled(feature2, userId); result.Err != nil { if result := <-ss.Preference().IsFeatureEnabled(feature2, userId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false { } else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for feature2, %v=%v", false, data) t.Fatalf("got incorrect setting for feature2, %v=%v", false, data)
} }
// make sure we get false if something different than "true" or "false" has been saved to database // make sure we get false if something different than "true" or "false" has been saved to database
if result := <-store.Preference().IsFeatureEnabled(feature3, userId); result.Err != nil { if result := <-ss.Preference().IsFeatureEnabled(feature3, userId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false { } else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for feature3, %v=%v", false, data) t.Fatalf("got incorrect setting for feature3, %v=%v", false, data)
} }
// make sure false is returned if a non-existent feature is queried // make sure false is returned if a non-existent feature is queried
if result := <-store.Preference().IsFeatureEnabled("someOtherFeature", userId); result.Err != nil { if result := <-ss.Preference().IsFeatureEnabled("someOtherFeature", userId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false { } else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for non-existent feature 'someOtherFeature', %v=%v", false, data) t.Fatalf("got incorrect setting for non-existent feature 'someOtherFeature', %v=%v", false, data)
@@ -309,7 +310,7 @@ func TestIsFeatureEnabled(t *testing.T) {
} }
func TestDeleteUnusedFeatures(t *testing.T) { func TestDeleteUnusedFeatures(t *testing.T) {
Setup() ss := Setup()
userId1 := model.NewId() userId1 := model.NewId()
userId2 := model.NewId() userId2 := model.NewId()
@@ -344,12 +345,12 @@ func TestDeleteUnusedFeatures(t *testing.T) {
}, },
} }
Must(store.Preference().Save(&features)) store.Must(ss.Preference().Save(&features))
store.Preference().(*SqlPreferenceStore).DeleteUnusedFeatures() ss.Preference().(*SqlPreferenceStore).DeleteUnusedFeatures()
//make sure features with value "false" have actually been deleted from the database //make sure features with value "false" have actually been deleted from the database
if val, err := store.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*) if val, err := ss.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*)
FROM Preferences FROM Preferences
WHERE Category = :Category WHERE Category = :Category
AND Value = :Val AND Value = :Val
@@ -360,7 +361,7 @@ func TestDeleteUnusedFeatures(t *testing.T) {
} }
// //
// make sure features with value "true" remain saved // make sure features with value "true" remain saved
if val, err := store.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*) if val, err := ss.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*)
FROM Preferences FROM Preferences
WHERE Category = :Category WHERE Category = :Category
AND Value = :Val AND Value = :Val
@@ -372,7 +373,7 @@ func TestDeleteUnusedFeatures(t *testing.T) {
} }
func TestPreferenceDelete(t *testing.T) { func TestPreferenceDelete(t *testing.T) {
Setup() ss := Setup()
preference := model.Preference{ preference := model.Preference{
UserId: model.NewId(), UserId: model.NewId(),
@@ -381,23 +382,23 @@ func TestPreferenceDelete(t *testing.T) {
Value: "value1a", Value: "value1a",
} }
Must(store.Preference().Save(&model.Preferences{preference})) store.Must(ss.Preference().Save(&model.Preferences{preference}))
if prefs := Must(store.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 1 { if prefs := store.Must(ss.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference") t.Fatal("should've returned 1 preference")
} }
if result := <-store.Preference().Delete(preference.UserId, preference.Category, preference.Name); result.Err != nil { if result := <-ss.Preference().Delete(preference.UserId, preference.Category, preference.Name); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if prefs := Must(store.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 0 { if prefs := store.Must(ss.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences") t.Fatal("should've returned no preferences")
} }
} }
func TestPreferenceDeleteCategory(t *testing.T) { func TestPreferenceDeleteCategory(t *testing.T) {
Setup() ss := Setup()
category := model.NewId() category := model.NewId()
userId := model.NewId() userId := model.NewId()
@@ -416,23 +417,23 @@ func TestPreferenceDeleteCategory(t *testing.T) {
Value: "value1a", Value: "value1a",
} }
Must(store.Preference().Save(&model.Preferences{preference1, preference2})) store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
if prefs := Must(store.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 2 { if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 2 {
t.Fatal("should've returned 2 preferences") t.Fatal("should've returned 2 preferences")
} }
if result := <-store.Preference().DeleteCategory(userId, category); result.Err != nil { if result := <-ss.Preference().DeleteCategory(userId, category); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if prefs := Must(store.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 { if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences") t.Fatal("should've returned no preferences")
} }
} }
func TestPreferenceDeleteCategoryAndName(t *testing.T) { func TestPreferenceDeleteCategoryAndName(t *testing.T) {
Setup() ss := Setup()
category := model.NewId() category := model.NewId()
name := model.NewId() name := model.NewId()
@@ -453,31 +454,31 @@ func TestPreferenceDeleteCategoryAndName(t *testing.T) {
Value: "value1a", Value: "value1a",
} }
Must(store.Preference().Save(&model.Preferences{preference1, preference2})) store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
if prefs := Must(store.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 1 { if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference") t.Fatal("should've returned 1 preference")
} }
if prefs := Must(store.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 1 { if prefs := store.Must(ss.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference") t.Fatal("should've returned 1 preference")
} }
if result := <-store.Preference().DeleteCategoryAndName(category, name); result.Err != nil { if result := <-ss.Preference().DeleteCategoryAndName(category, name); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if prefs := Must(store.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 { if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences") t.Fatal("should've returned no preferences")
} }
if prefs := Must(store.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 0 { if prefs := store.Must(ss.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences") t.Fatal("should've returned no preferences")
} }
} }
func TestPreferenceCleanupFlagsBatch(t *testing.T) { func TestPreferenceCleanupFlagsBatch(t *testing.T) {
Setup() ss := Setup()
category := model.PREFERENCE_CATEGORY_FLAGGED_POST category := model.PREFERENCE_CATEGORY_FLAGGED_POST
userId := model.NewId() userId := model.NewId()
@@ -487,7 +488,7 @@ func TestPreferenceCleanupFlagsBatch(t *testing.T) {
o1.UserId = userId o1.UserId = userId
o1.Message = "zz" + model.NewId() + "AAAAAAAAAAA" o1.Message = "zz" + model.NewId() + "AAAAAAAAAAA"
o1.CreateAt = 1000 o1.CreateAt = 1000
o1 = (<-store.Post().Save(o1)).Data.(*model.Post) o1 = (<-ss.Post().Save(o1)).Data.(*model.Post)
preference1 := model.Preference{ preference1 := model.Preference{
UserId: userId, UserId: userId,
@@ -503,14 +504,14 @@ func TestPreferenceCleanupFlagsBatch(t *testing.T) {
Value: "true", Value: "true",
} }
Must(store.Preference().Save(&model.Preferences{preference1, preference2})) store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
result := <-store.Preference().CleanupFlagsBatch(10000) result := <-ss.Preference().CleanupFlagsBatch(10000)
assert.Nil(t, result.Err) assert.Nil(t, result.Err)
result = <-store.Preference().Get(userId, category, preference1.Name) result = <-ss.Preference().Get(userId, category, preference1.Name)
assert.Nil(t, result.Err) assert.Nil(t, result.Err)
result = <-store.Preference().Get(userId, category, preference2.Name) result = <-ss.Preference().Get(userId, category, preference2.Name)
assert.NotNil(t, result.Err) assert.NotNil(t, result.Err)
} }

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

@@ -1,18 +1,19 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestReactionSave(t *testing.T) { func TestReactionSave(t *testing.T) {
Setup() ss := Setup()
post := Must(store.Post().Save(&model.Post{ post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(), ChannelId: model.NewId(),
UserId: model.NewId(), UserId: model.NewId(),
})).(*model.Post) })).(*model.Post)
@@ -23,7 +24,7 @@ func TestReactionSave(t *testing.T) {
PostId: post.Id, PostId: post.Id,
EmojiName: model.NewId(), EmojiName: model.NewId(),
} }
if result := <-store.Reaction().Save(reaction1); result.Err != nil { if result := <-ss.Reaction().Save(reaction1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if saved := result.Data.(*model.Reaction); saved.UserId != reaction1.UserId || } else if saved := result.Data.(*model.Reaction); saved.UserId != reaction1.UserId ||
saved.PostId != reaction1.PostId || saved.EmojiName != reaction1.EmojiName { saved.PostId != reaction1.PostId || saved.EmojiName != reaction1.EmojiName {
@@ -31,7 +32,7 @@ func TestReactionSave(t *testing.T) {
} }
var secondUpdateAt int64 var secondUpdateAt int64
if postList := Must(store.Post().Get(reaction1.PostId)).(*model.PostList); !postList.Posts[post.Id].HasReactions { if postList := store.Must(ss.Post().Get(reaction1.PostId)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = true on post") t.Fatal("should've set HasReactions = true on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt { } else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("should've marked post as updated when HasReactions changed") t.Fatal("should've marked post as updated when HasReactions changed")
@@ -39,7 +40,7 @@ func TestReactionSave(t *testing.T) {
secondUpdateAt = postList.Posts[post.Id].UpdateAt secondUpdateAt = postList.Posts[post.Id].UpdateAt
} }
if result := <-store.Reaction().Save(reaction1); result.Err != nil { if result := <-ss.Reaction().Save(reaction1); result.Err != nil {
t.Log(result.Err) t.Log(result.Err)
t.Fatal("should've allowed saving a duplicate reaction") t.Fatal("should've allowed saving a duplicate reaction")
} }
@@ -50,11 +51,11 @@ func TestReactionSave(t *testing.T) {
PostId: reaction1.PostId, PostId: reaction1.PostId,
EmojiName: reaction1.EmojiName, EmojiName: reaction1.EmojiName,
} }
if result := <-store.Reaction().Save(reaction2); result.Err != nil { if result := <-ss.Reaction().Save(reaction2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if postList := Must(store.Post().Get(reaction2.PostId)).(*model.PostList); postList.Posts[post.Id].UpdateAt != secondUpdateAt { if postList := store.Must(ss.Post().Get(reaction2.PostId)).(*model.PostList); postList.Posts[post.Id].UpdateAt != secondUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions hasn't changed") t.Fatal("shouldn't mark as updated when HasReactions hasn't changed")
} }
@@ -64,7 +65,7 @@ func TestReactionSave(t *testing.T) {
PostId: model.NewId(), PostId: model.NewId(),
EmojiName: reaction1.EmojiName, EmojiName: reaction1.EmojiName,
} }
if result := <-store.Reaction().Save(reaction3); result.Err != nil { if result := <-ss.Reaction().Save(reaction3); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
@@ -74,7 +75,7 @@ func TestReactionSave(t *testing.T) {
PostId: reaction1.PostId, PostId: reaction1.PostId,
EmojiName: model.NewId(), EmojiName: model.NewId(),
} }
if result := <-store.Reaction().Save(reaction4); result.Err != nil { if result := <-ss.Reaction().Save(reaction4); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
@@ -83,15 +84,15 @@ func TestReactionSave(t *testing.T) {
UserId: reaction1.UserId, UserId: reaction1.UserId,
PostId: reaction1.PostId, PostId: reaction1.PostId,
} }
if result := <-store.Reaction().Save(reaction5); result.Err == nil { if result := <-ss.Reaction().Save(reaction5); result.Err == nil {
t.Fatal("should've failed for invalid reaction") t.Fatal("should've failed for invalid reaction")
} }
} }
func TestReactionDelete(t *testing.T) { func TestReactionDelete(t *testing.T) {
Setup() ss := Setup()
post := Must(store.Post().Save(&model.Post{ post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(), ChannelId: model.NewId(),
UserId: model.NewId(), UserId: model.NewId(),
})).(*model.Post) })).(*model.Post)
@@ -102,20 +103,20 @@ func TestReactionDelete(t *testing.T) {
EmojiName: model.NewId(), EmojiName: model.NewId(),
} }
Must(store.Reaction().Save(reaction)) store.Must(ss.Reaction().Save(reaction))
firstUpdateAt := Must(store.Post().Get(reaction.PostId)).(*model.PostList).Posts[post.Id].UpdateAt firstUpdateAt := store.Must(ss.Post().Get(reaction.PostId)).(*model.PostList).Posts[post.Id].UpdateAt
if result := <-store.Reaction().Delete(reaction); result.Err != nil { if result := <-ss.Reaction().Delete(reaction); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.Reaction().GetForPost(post.Id, false); result.Err != nil { if result := <-ss.Reaction().GetForPost(post.Id, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if len(result.Data.([]*model.Reaction)) != 0 { } else if len(result.Data.([]*model.Reaction)) != 0 {
t.Fatal("should've deleted reaction") t.Fatal("should've deleted reaction")
} }
if postList := Must(store.Post().Get(post.Id)).(*model.PostList); postList.Posts[post.Id].HasReactions { if postList := store.Must(ss.Post().Get(post.Id)).(*model.PostList); postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = false on post") t.Fatal("should've set HasReactions = false on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt { } else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions has changed after deleting reactions") t.Fatal("shouldn't mark as updated when HasReactions has changed after deleting reactions")
@@ -123,7 +124,7 @@ func TestReactionDelete(t *testing.T) {
} }
func TestReactionGetForPost(t *testing.T) { func TestReactionGetForPost(t *testing.T) {
Setup() ss := Setup()
postId := model.NewId() postId := model.NewId()
@@ -153,10 +154,10 @@ func TestReactionGetForPost(t *testing.T) {
} }
for _, reaction := range reactions { for _, reaction := range reactions {
Must(store.Reaction().Save(reaction)) store.Must(ss.Reaction().Save(reaction))
} }
if result := <-store.Reaction().GetForPost(postId, false); result.Err != nil { if result := <-ss.Reaction().GetForPost(postId, false); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 { } else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions") t.Fatal("should've returned 3 reactions")
@@ -181,7 +182,7 @@ func TestReactionGetForPost(t *testing.T) {
} }
// Should return cached item // Should return cached item
if result := <-store.Reaction().GetForPost(postId, true); result.Err != nil { if result := <-ss.Reaction().GetForPost(postId, true); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 { } else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions") t.Fatal("should've returned 3 reactions")
@@ -207,19 +208,19 @@ func TestReactionGetForPost(t *testing.T) {
} }
func TestReactionDeleteAllWithEmojiName(t *testing.T) { func TestReactionDeleteAllWithEmojiName(t *testing.T) {
Setup() ss := Setup()
emojiToDelete := model.NewId() emojiToDelete := model.NewId()
post := Must(store.Post().Save(&model.Post{ post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(), ChannelId: model.NewId(),
UserId: model.NewId(), UserId: model.NewId(),
})).(*model.Post) })).(*model.Post)
post2 := Must(store.Post().Save(&model.Post{ post2 := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(), ChannelId: model.NewId(),
UserId: model.NewId(), UserId: model.NewId(),
})).(*model.Post) })).(*model.Post)
post3 := Must(store.Post().Save(&model.Post{ post3 := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(), ChannelId: model.NewId(),
UserId: model.NewId(), UserId: model.NewId(),
})).(*model.Post) })).(*model.Post)
@@ -255,15 +256,15 @@ func TestReactionDeleteAllWithEmojiName(t *testing.T) {
} }
for _, reaction := range reactions { for _, reaction := range reactions {
Must(store.Reaction().Save(reaction)) store.Must(ss.Reaction().Save(reaction))
} }
if result := <-store.Reaction().DeleteAllWithEmojiName(emojiToDelete); result.Err != nil { if result := <-ss.Reaction().DeleteAllWithEmojiName(emojiToDelete); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
// check that the reactions were deleted // check that the reactions were deleted
if returned := Must(store.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 { if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name") t.Fatal("should've only removed reactions with emoji name")
} else { } else {
for _, reaction := range returned { for _, reaction := range returned {
@@ -273,32 +274,32 @@ func TestReactionDeleteAllWithEmojiName(t *testing.T) {
} }
} }
if returned := Must(store.Reaction().GetForPost(post2.Id, false)).([]*model.Reaction); len(returned) != 1 { if returned := store.Must(ss.Reaction().GetForPost(post2.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name") t.Fatal("should've only removed reactions with emoji name")
} }
if returned := Must(store.Reaction().GetForPost(post3.Id, false)).([]*model.Reaction); len(returned) != 0 { if returned := store.Must(ss.Reaction().GetForPost(post3.Id, false)).([]*model.Reaction); len(returned) != 0 {
t.Fatal("should've only removed reactions with emoji name") t.Fatal("should've only removed reactions with emoji name")
} }
// check that the posts are updated // check that the posts are updated
if postList := Must(store.Post().Get(post.Id)).(*model.PostList); !postList.Posts[post.Id].HasReactions { if postList := store.Must(ss.Post().Get(post.Id)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("post should still have reactions") t.Fatal("post should still have reactions")
} }
if postList := Must(store.Post().Get(post2.Id)).(*model.PostList); !postList.Posts[post2.Id].HasReactions { if postList := store.Must(ss.Post().Get(post2.Id)).(*model.PostList); !postList.Posts[post2.Id].HasReactions {
t.Fatal("post should still have reactions") t.Fatal("post should still have reactions")
} }
if postList := Must(store.Post().Get(post3.Id)).(*model.PostList); postList.Posts[post3.Id].HasReactions { if postList := store.Must(ss.Post().Get(post3.Id)).(*model.PostList); postList.Posts[post3.Id].HasReactions {
t.Fatal("post shouldn't have reactions any more") t.Fatal("post shouldn't have reactions any more")
} }
} }
func TestReactionStorePermanentDeleteBatch(t *testing.T) { func TestReactionStorePermanentDeleteBatch(t *testing.T) {
Setup() ss := Setup()
post := Must(store.Post().Save(&model.Post{ post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(), ChannelId: model.NewId(),
UserId: model.NewId(), UserId: model.NewId(),
})).(*model.Post) })).(*model.Post)
@@ -333,19 +334,19 @@ func TestReactionStorePermanentDeleteBatch(t *testing.T) {
// Need to hang on to a reaction to delete later in order to clear the cache, as "allowFromCache" isn't honoured any more. // Need to hang on to a reaction to delete later in order to clear the cache, as "allowFromCache" isn't honoured any more.
var lastReaction *model.Reaction var lastReaction *model.Reaction
for _, reaction := range reactions { for _, reaction := range reactions {
lastReaction = Must(store.Reaction().Save(reaction)).(*model.Reaction) lastReaction = store.Must(ss.Reaction().Save(reaction)).(*model.Reaction)
} }
if returned := Must(store.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 4 { if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 4 {
t.Fatal("expected 4 reactions") t.Fatal("expected 4 reactions")
} }
Must(store.Reaction().PermanentDeleteBatch(1800, 1000)) store.Must(ss.Reaction().PermanentDeleteBatch(1800, 1000))
// This is to force a clear of the cache. // This is to force a clear of the cache.
Must(store.Reaction().Delete(lastReaction)) store.Must(ss.Reaction().Delete(lastReaction))
if returned := Must(store.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 { if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatalf("expected 1 reaction. Got: %v", len(returned)) t.Fatalf("expected 1 reaction. Got: %v", len(returned))
} }
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
@@ -9,6 +9,7 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -16,7 +17,7 @@ type SqlSessionStore struct {
SqlStore SqlStore
} }
func NewSqlSessionStore(sqlStore SqlStore) SessionStore { func NewSqlSessionStore(sqlStore SqlStore) store.SessionStore {
us := &SqlSessionStore{sqlStore} us := &SqlSessionStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -40,12 +41,12 @@ func (me SqlSessionStore) CreateIndexesIfNotExists() {
me.CreateIndexIfNotExists("idx_sessions_last_activity_at", "Sessions", "LastActivityAt") me.CreateIndexIfNotExists("idx_sessions_last_activity_at", "Sessions", "LastActivityAt")
} }
func (me SqlSessionStore) Save(session *model.Session) StoreChannel { func (me SqlSessionStore) Save(session *model.Session) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(session.Id) > 0 { if len(session.Id) > 0 {
result.Err = model.NewAppError("SqlSessionStore.Save", "store.sql_session.save.existing.app_error", nil, "id="+session.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlSessionStore.Save", "store.sql_session.save.existing.app_error", nil, "id="+session.Id, http.StatusBadRequest)
@@ -89,12 +90,12 @@ func (me SqlSessionStore) Save(session *model.Session) StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) Get(sessionIdOrToken string) StoreChannel { func (me SqlSessionStore) Get(sessionIdOrToken string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var sessions []*model.Session var sessions []*model.Session
@@ -128,8 +129,8 @@ func (me SqlSessionStore) Get(sessionIdOrToken string) StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) GetSessions(userId string) StoreChannel { func (me SqlSessionStore) GetSessions(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
@@ -137,7 +138,7 @@ func (me SqlSessionStore) GetSessions(userId string) StoreChannel {
l4g.Error(utils.T("store.sql_session.get_sessions.error"), cur.Err) l4g.Error(utils.T("store.sql_session.get_sessions.error"), cur.Err)
} }
result := StoreResult{} result := store.StoreResult{}
var sessions []*model.Session var sessions []*model.Session
tcs := me.Team().GetTeamsForUser(userId) tcs := me.Team().GetTeamsForUser(userId)
@@ -171,12 +172,12 @@ func (me SqlSessionStore) GetSessions(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) GetSessionsWithActiveDeviceIds(userId string) StoreChannel { func (me SqlSessionStore) GetSessionsWithActiveDeviceIds(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var sessions []*model.Session var sessions []*model.Session
if _, err := me.GetReplica().Select(&sessions, "SELECT * FROM Sessions WHERE UserId = :UserId AND ExpiresAt != 0 AND :ExpiresAt <= ExpiresAt AND DeviceId != ''", map[string]interface{}{"UserId": userId, "ExpiresAt": model.GetMillis()}); err != nil { if _, err := me.GetReplica().Select(&sessions, "SELECT * FROM Sessions WHERE UserId = :UserId AND ExpiresAt != 0 AND :ExpiresAt <= ExpiresAt AND DeviceId != ''", map[string]interface{}{"UserId": userId, "ExpiresAt": model.GetMillis()}); err != nil {
@@ -193,11 +194,11 @@ func (me SqlSessionStore) GetSessionsWithActiveDeviceIds(userId string) StoreCha
return storeChannel return storeChannel
} }
func (me SqlSessionStore) Remove(sessionIdOrToken string) StoreChannel { func (me SqlSessionStore) Remove(sessionIdOrToken string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE Id = :Id Or Token = :Token", map[string]interface{}{"Id": sessionIdOrToken, "Token": sessionIdOrToken}) _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE Id = :Id Or Token = :Token", map[string]interface{}{"Id": sessionIdOrToken, "Token": sessionIdOrToken})
if err != nil { if err != nil {
@@ -211,11 +212,11 @@ func (me SqlSessionStore) Remove(sessionIdOrToken string) StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) RemoveAllSessions() StoreChannel { func (me SqlSessionStore) RemoveAllSessions() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := me.GetMaster().Exec("DELETE FROM Sessions") _, err := me.GetMaster().Exec("DELETE FROM Sessions")
if err != nil { if err != nil {
@@ -229,11 +230,11 @@ func (me SqlSessionStore) RemoveAllSessions() StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) PermanentDeleteSessionsByUser(userId string) StoreChannel { func (me SqlSessionStore) PermanentDeleteSessionsByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}) _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {
@@ -247,11 +248,11 @@ func (me SqlSessionStore) PermanentDeleteSessionsByUser(userId string) StoreChan
return storeChannel return storeChannel
} }
func (me SqlSessionStore) CleanUpExpiredSessions(userId string) StoreChannel { func (me SqlSessionStore) CleanUpExpiredSessions(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE UserId = :UserId AND ExpiresAt != 0 AND :ExpiresAt > ExpiresAt", map[string]interface{}{"UserId": userId, "ExpiresAt": model.GetMillis()}); err != nil { if _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE UserId = :UserId AND ExpiresAt != 0 AND :ExpiresAt > ExpiresAt", map[string]interface{}{"UserId": userId, "ExpiresAt": model.GetMillis()}); err != nil {
result.Err = model.NewAppError("SqlSessionStore.CleanUpExpiredSessions", "store.sql_session.cleanup_expired_sessions.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlSessionStore.CleanUpExpiredSessions", "store.sql_session.cleanup_expired_sessions.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -266,11 +267,11 @@ func (me SqlSessionStore) CleanUpExpiredSessions(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) UpdateLastActivityAt(sessionId string, time int64) StoreChannel { func (me SqlSessionStore) UpdateLastActivityAt(sessionId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := me.GetMaster().Exec("UPDATE Sessions SET LastActivityAt = :LastActivityAt WHERE Id = :Id", map[string]interface{}{"LastActivityAt": time, "Id": sessionId}); err != nil { if _, err := me.GetMaster().Exec("UPDATE Sessions SET LastActivityAt = :LastActivityAt WHERE Id = :Id", map[string]interface{}{"LastActivityAt": time, "Id": sessionId}); err != nil {
result.Err = model.NewAppError("SqlSessionStore.UpdateLastActivityAt", "store.sql_session.update_last_activity.app_error", nil, "sessionId="+sessionId, http.StatusInternalServerError) result.Err = model.NewAppError("SqlSessionStore.UpdateLastActivityAt", "store.sql_session.update_last_activity.app_error", nil, "sessionId="+sessionId, http.StatusInternalServerError)
@@ -285,11 +286,11 @@ func (me SqlSessionStore) UpdateLastActivityAt(sessionId string, time int64) Sto
return storeChannel return storeChannel
} }
func (me SqlSessionStore) UpdateRoles(userId, roles string) StoreChannel { func (me SqlSessionStore) UpdateRoles(userId, roles string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := me.GetMaster().Exec("UPDATE Sessions SET Roles = :Roles WHERE UserId = :UserId", map[string]interface{}{"Roles": roles, "UserId": userId}); err != nil { if _, err := me.GetMaster().Exec("UPDATE Sessions SET Roles = :Roles WHERE UserId = :UserId", map[string]interface{}{"Roles": roles, "UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlSessionStore.UpdateRoles", "store.sql_session.update_roles.app_error", nil, "userId="+userId, http.StatusInternalServerError) result.Err = model.NewAppError("SqlSessionStore.UpdateRoles", "store.sql_session.update_roles.app_error", nil, "userId="+userId, http.StatusInternalServerError)
} else { } else {
@@ -303,11 +304,11 @@ func (me SqlSessionStore) UpdateRoles(userId, roles string) StoreChannel {
return storeChannel return storeChannel
} }
func (me SqlSessionStore) UpdateDeviceId(id string, deviceId string, expiresAt int64) StoreChannel { func (me SqlSessionStore) UpdateDeviceId(id string, deviceId string, expiresAt int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := me.GetMaster().Exec("UPDATE Sessions SET DeviceId = :DeviceId, ExpiresAt = :ExpiresAt WHERE Id = :Id", map[string]interface{}{"DeviceId": deviceId, "Id": id, "ExpiresAt": expiresAt}); err != nil { if _, err := me.GetMaster().Exec("UPDATE Sessions SET DeviceId = :DeviceId, ExpiresAt = :ExpiresAt WHERE Id = :Id", map[string]interface{}{"DeviceId": deviceId, "Id": id, "ExpiresAt": expiresAt}); err != nil {
result.Err = model.NewAppError("SqlSessionStore.UpdateDeviceId", "store.sql_session.update_device_id.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlSessionStore.UpdateDeviceId", "store.sql_session.update_device_id.app_error", nil, err.Error(), http.StatusInternalServerError)
} else { } else {
@@ -321,11 +322,11 @@ func (me SqlSessionStore) UpdateDeviceId(id string, deviceId string, expiresAt i
return storeChannel return storeChannel
} }
func (me SqlSessionStore) AnalyticsSessionCount() StoreChannel { func (me SqlSessionStore) AnalyticsSessionCount() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT `SELECT

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

@@ -1,42 +1,43 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestSessionStoreSave(t *testing.T) { func TestSessionStoreSave(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
if err := (<-store.Session().Save(&s1)).Err; err != nil { if err := (<-ss.Session().Save(&s1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
func TestSessionGet(t *testing.T) { func TestSessionGet(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
s2 := model.Session{} s2 := model.Session{}
s2.UserId = s1.UserId s2.UserId = s1.UserId
Must(store.Session().Save(&s2)) store.Must(ss.Session().Save(&s2))
s3 := model.Session{} s3 := model.Session{}
s3.UserId = s1.UserId s3.UserId = s1.UserId
s3.ExpiresAt = 1 s3.ExpiresAt = 1
Must(store.Session().Save(&s3)) store.Must(ss.Session().Save(&s3))
if rs1 := (<-store.Session().Get(s1.Id)); rs1.Err != nil { if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} else { } else {
if rs1.Data.(*model.Session).Id != s1.Id { if rs1.Data.(*model.Session).Id != s1.Id {
@@ -44,7 +45,7 @@ func TestSessionGet(t *testing.T) {
} }
} }
if rs2 := (<-store.Session().GetSessions(s1.UserId)); rs2.Err != nil { if rs2 := (<-ss.Session().GetSessions(s1.UserId)); rs2.Err != nil {
t.Fatal(rs2.Err) t.Fatal(rs2.Err)
} else { } else {
if len(rs2.Data.([]*model.Session)) != 2 { if len(rs2.Data.([]*model.Session)) != 2 {
@@ -54,26 +55,26 @@ func TestSessionGet(t *testing.T) {
} }
func TestSessionGetWithDeviceId(t *testing.T) { func TestSessionGetWithDeviceId(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
s1.ExpiresAt = model.GetMillis() + 10000 s1.ExpiresAt = model.GetMillis() + 10000
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
s2 := model.Session{} s2 := model.Session{}
s2.UserId = s1.UserId s2.UserId = s1.UserId
s2.DeviceId = model.NewId() s2.DeviceId = model.NewId()
s2.ExpiresAt = model.GetMillis() + 10000 s2.ExpiresAt = model.GetMillis() + 10000
Must(store.Session().Save(&s2)) store.Must(ss.Session().Save(&s2))
s3 := model.Session{} s3 := model.Session{}
s3.UserId = s1.UserId s3.UserId = s1.UserId
s3.ExpiresAt = 1 s3.ExpiresAt = 1
s3.DeviceId = model.NewId() s3.DeviceId = model.NewId()
Must(store.Session().Save(&s3)) store.Must(ss.Session().Save(&s3))
if rs1 := (<-store.Session().GetSessionsWithActiveDeviceIds(s1.UserId)); rs1.Err != nil { if rs1 := (<-ss.Session().GetSessionsWithActiveDeviceIds(s1.UserId)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} else { } else {
if len(rs1.Data.([]*model.Session)) != 1 { if len(rs1.Data.([]*model.Session)) != 1 {
@@ -83,13 +84,13 @@ func TestSessionGetWithDeviceId(t *testing.T) {
} }
func TestSessionRemove(t *testing.T) { func TestSessionRemove(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if rs1 := (<-store.Session().Get(s1.Id)); rs1.Err != nil { if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} else { } else {
if rs1.Data.(*model.Session).Id != s1.Id { if rs1.Data.(*model.Session).Id != s1.Id {
@@ -97,21 +98,21 @@ func TestSessionRemove(t *testing.T) {
} }
} }
Must(store.Session().Remove(s1.Id)) store.Must(ss.Session().Remove(s1.Id))
if rs2 := (<-store.Session().Get(s1.Id)); rs2.Err == nil { if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed") t.Fatal("should have been removed")
} }
} }
func TestSessionRemoveAll(t *testing.T) { func TestSessionRemoveAll(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if rs1 := (<-store.Session().Get(s1.Id)); rs1.Err != nil { if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} else { } else {
if rs1.Data.(*model.Session).Id != s1.Id { if rs1.Data.(*model.Session).Id != s1.Id {
@@ -119,21 +120,21 @@ func TestSessionRemoveAll(t *testing.T) {
} }
} }
Must(store.Session().RemoveAllSessions()) store.Must(ss.Session().RemoveAllSessions())
if rs2 := (<-store.Session().Get(s1.Id)); rs2.Err == nil { if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed") t.Fatal("should have been removed")
} }
} }
func TestSessionRemoveByUser(t *testing.T) { func TestSessionRemoveByUser(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if rs1 := (<-store.Session().Get(s1.Id)); rs1.Err != nil { if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} else { } else {
if rs1.Data.(*model.Session).Id != s1.Id { if rs1.Data.(*model.Session).Id != s1.Id {
@@ -141,21 +142,21 @@ func TestSessionRemoveByUser(t *testing.T) {
} }
} }
Must(store.Session().PermanentDeleteSessionsByUser(s1.UserId)) store.Must(ss.Session().PermanentDeleteSessionsByUser(s1.UserId))
if rs2 := (<-store.Session().Get(s1.Id)); rs2.Err == nil { if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed") t.Fatal("should have been removed")
} }
} }
func TestSessionRemoveToken(t *testing.T) { func TestSessionRemoveToken(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if rs1 := (<-store.Session().Get(s1.Id)); rs1.Err != nil { if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} else { } else {
if rs1.Data.(*model.Session).Id != s1.Id { if rs1.Data.(*model.Session).Id != s1.Id {
@@ -163,13 +164,13 @@ func TestSessionRemoveToken(t *testing.T) {
} }
} }
Must(store.Session().Remove(s1.Token)) store.Must(ss.Session().Remove(s1.Token))
if rs2 := (<-store.Session().Get(s1.Id)); rs2.Err == nil { if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed") t.Fatal("should have been removed")
} }
if rs3 := (<-store.Session().GetSessions(s1.UserId)); rs3.Err != nil { if rs3 := (<-ss.Session().GetSessions(s1.UserId)); rs3.Err != nil {
t.Fatal(rs3.Err) t.Fatal(rs3.Err)
} else { } else {
if len(rs3.Data.([]*model.Session)) != 0 { if len(rs3.Data.([]*model.Session)) != 0 {
@@ -179,57 +180,57 @@ func TestSessionRemoveToken(t *testing.T) {
} }
func TestSessionUpdateDeviceId(t *testing.T) { func TestSessionUpdateDeviceId(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if rs1 := (<-store.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs1.Err != nil { if rs1 := (<-ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} }
s2 := model.Session{} s2 := model.Session{}
s2.UserId = model.NewId() s2.UserId = model.NewId()
Must(store.Session().Save(&s2)) store.Must(ss.Session().Save(&s2))
if rs2 := (<-store.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs2.Err != nil { if rs2 := (<-ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs2.Err != nil {
t.Fatal(rs2.Err) t.Fatal(rs2.Err)
} }
} }
func TestSessionUpdateDeviceId2(t *testing.T) { func TestSessionUpdateDeviceId2(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if rs1 := (<-store.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs1.Err != nil { if rs1 := (<-ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs1.Err != nil {
t.Fatal(rs1.Err) t.Fatal(rs1.Err)
} }
s2 := model.Session{} s2 := model.Session{}
s2.UserId = model.NewId() s2.UserId = model.NewId()
Must(store.Session().Save(&s2)) store.Must(ss.Session().Save(&s2))
if rs2 := (<-store.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs2.Err != nil { if rs2 := (<-ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs2.Err != nil {
t.Fatal(rs2.Err) t.Fatal(rs2.Err)
} }
} }
func TestSessionStoreUpdateLastActivityAt(t *testing.T) { func TestSessionStoreUpdateLastActivityAt(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if err := (<-store.Session().UpdateLastActivityAt(s1.Id, 1234567890)).Err; err != nil { if err := (<-ss.Session().UpdateLastActivityAt(s1.Id, 1234567890)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if r1 := <-store.Session().Get(s1.Id); r1.Err != nil { if r1 := <-ss.Session().Get(s1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Session).LastActivityAt != 1234567890 { if r1.Data.(*model.Session).LastActivityAt != 1234567890 {
@@ -240,14 +241,14 @@ func TestSessionStoreUpdateLastActivityAt(t *testing.T) {
} }
func TestSessionCount(t *testing.T) { func TestSessionCount(t *testing.T) {
Setup() ss := Setup()
s1 := model.Session{} s1 := model.Session{}
s1.UserId = model.NewId() s1.UserId = model.NewId()
s1.ExpiresAt = model.GetMillis() + 100000 s1.ExpiresAt = model.GetMillis() + 100000
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if r1 := <-store.Session().AnalyticsSessionCount(); r1.Err != nil { if r1 := <-ss.Session().AnalyticsSessionCount(); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(int64) == 0 { if r1.Data.(int64) == 0 {

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

@@ -1,7 +1,7 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -10,6 +10,7 @@ import (
"strings" "strings"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
const ( const (
@@ -20,7 +21,7 @@ type SqlStatusStore struct {
SqlStore SqlStore
} }
func NewSqlStatusStore(sqlStore SqlStore) StatusStore { func NewSqlStatusStore(sqlStore SqlStore) store.StatusStore {
s := &SqlStatusStore{sqlStore} s := &SqlStatusStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -38,11 +39,11 @@ func (s SqlStatusStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_status_status", "Status", "Status") s.CreateIndexIfNotExists("idx_status_status", "Status", "Status")
} }
func (s SqlStatusStore) SaveOrUpdate(status *model.Status) StoreChannel { func (s SqlStatusStore) SaveOrUpdate(status *model.Status) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if err := s.GetReplica().SelectOne(&model.Status{}, "SELECT * FROM Status WHERE UserId = :UserId", map[string]interface{}{"UserId": status.UserId}); err == nil { if err := s.GetReplica().SelectOne(&model.Status{}, "SELECT * FROM Status WHERE UserId = :UserId", map[string]interface{}{"UserId": status.UserId}); err == nil {
if _, err := s.GetMaster().Update(status); err != nil { if _, err := s.GetMaster().Update(status); err != nil {
@@ -63,11 +64,11 @@ func (s SqlStatusStore) SaveOrUpdate(status *model.Status) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) Get(userId string) StoreChannel { func (s SqlStatusStore) Get(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var status model.Status var status model.Status
@@ -94,11 +95,11 @@ func (s SqlStatusStore) Get(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) GetByIds(userIds []string) StoreChannel { func (s SqlStatusStore) GetByIds(userIds []string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
props := make(map[string]interface{}) props := make(map[string]interface{})
idQuery := "" idQuery := ""
@@ -126,11 +127,11 @@ func (s SqlStatusStore) GetByIds(userIds []string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) GetOnlineAway() StoreChannel { func (s SqlStatusStore) GetOnlineAway() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Status var statuses []*model.Status
if _, err := s.GetReplica().Select(&statuses, "SELECT * FROM Status WHERE Status = :Online OR Status = :Away LIMIT 300", map[string]interface{}{"Online": model.STATUS_ONLINE, "Away": model.STATUS_AWAY}); err != nil { if _, err := s.GetReplica().Select(&statuses, "SELECT * FROM Status WHERE Status = :Online OR Status = :Away LIMIT 300", map[string]interface{}{"Online": model.STATUS_ONLINE, "Away": model.STATUS_AWAY}); err != nil {
@@ -146,11 +147,11 @@ func (s SqlStatusStore) GetOnlineAway() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) GetOnline() StoreChannel { func (s SqlStatusStore) GetOnline() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Status var statuses []*model.Status
if _, err := s.GetReplica().Select(&statuses, "SELECT * FROM Status WHERE Status = :Online", map[string]interface{}{"Online": model.STATUS_ONLINE}); err != nil { if _, err := s.GetReplica().Select(&statuses, "SELECT * FROM Status WHERE Status = :Online", map[string]interface{}{"Online": model.STATUS_ONLINE}); err != nil {
@@ -166,11 +167,11 @@ func (s SqlStatusStore) GetOnline() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) GetAllFromTeam(teamId string) StoreChannel { func (s SqlStatusStore) GetAllFromTeam(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var statuses []*model.Status var statuses []*model.Status
if _, err := s.GetReplica().Select(&statuses, if _, err := s.GetReplica().Select(&statuses,
@@ -188,11 +189,11 @@ func (s SqlStatusStore) GetAllFromTeam(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) ResetAll() StoreChannel { func (s SqlStatusStore) ResetAll() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("UPDATE Status SET Status = :Status WHERE Manual = false", map[string]interface{}{"Status": model.STATUS_OFFLINE}); err != nil { if _, err := s.GetMaster().Exec("UPDATE Status SET Status = :Status WHERE Manual = false", map[string]interface{}{"Status": model.STATUS_OFFLINE}); err != nil {
result.Err = model.NewAppError("SqlStatusStore.ResetAll", "store.sql_status.reset_all.app_error", nil, "", http.StatusInternalServerError) result.Err = model.NewAppError("SqlStatusStore.ResetAll", "store.sql_status.reset_all.app_error", nil, "", http.StatusInternalServerError)
@@ -205,11 +206,11 @@ func (s SqlStatusStore) ResetAll() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) GetTotalActiveUsersCount() StoreChannel { func (s SqlStatusStore) GetTotalActiveUsersCount() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
time := model.GetMillis() - (1000 * 60 * 60 * 24) time := model.GetMillis() - (1000 * 60 * 60 * 24)
@@ -226,11 +227,11 @@ func (s SqlStatusStore) GetTotalActiveUsersCount() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlStatusStore) UpdateLastActivityAt(userId string, lastActivityAt int64) StoreChannel { func (s SqlStatusStore) UpdateLastActivityAt(userId string, lastActivityAt int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("UPDATE Status SET LastActivityAt = :Time WHERE UserId = :UserId", map[string]interface{}{"UserId": userId, "Time": lastActivityAt}); err != nil { if _, err := s.GetMaster().Exec("UPDATE Status SET LastActivityAt = :Time WHERE UserId = :UserId", map[string]interface{}{"UserId": userId, "Time": lastActivityAt}); err != nil {
result.Err = model.NewAppError("SqlStatusStore.UpdateLastActivityAt", "store.sql_status.update_last_activity_at.app_error", nil, "", http.StatusInternalServerError) result.Err = model.NewAppError("SqlStatusStore.UpdateLastActivityAt", "store.sql_status.update_last_activity_at.app_error", nil, "", http.StatusInternalServerError)

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

@@ -1,44 +1,45 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestSqlStatusStore(t *testing.T) { func TestSqlStatusStore(t *testing.T) {
Setup() ss := Setup()
status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-store.Status().SaveOrUpdate(status)).Err; err != nil { if err := (<-ss.Status().SaveOrUpdate(status)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
status.LastActivityAt = 10 status.LastActivityAt = 10
if err := (<-store.Status().SaveOrUpdate(status)).Err; err != nil { if err := (<-ss.Status().SaveOrUpdate(status)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := (<-store.Status().Get(status.UserId)).Err; err != nil { if err := (<-ss.Status().Get(status.UserId)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
status2 := &model.Status{UserId: model.NewId(), Status: model.STATUS_AWAY, Manual: false, LastActivityAt: 0, ActiveChannel: ""} status2 := &model.Status{UserId: model.NewId(), Status: model.STATUS_AWAY, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-store.Status().SaveOrUpdate(status2)).Err; err != nil { if err := (<-ss.Status().SaveOrUpdate(status2)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
status3 := &model.Status{UserId: model.NewId(), Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} status3 := &model.Status{UserId: model.NewId(), Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-store.Status().SaveOrUpdate(status3)).Err; err != nil { if err := (<-ss.Status().SaveOrUpdate(status3)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result := <-store.Status().GetOnlineAway(); result.Err != nil { if result := <-ss.Status().GetOnlineAway(); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
statuses := result.Data.([]*model.Status) statuses := result.Data.([]*model.Status)
@@ -49,7 +50,7 @@ func TestSqlStatusStore(t *testing.T) {
} }
} }
if result := <-store.Status().GetOnline(); result.Err != nil { if result := <-ss.Status().GetOnline(); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
statuses := result.Data.([]*model.Status) statuses := result.Data.([]*model.Status)
@@ -60,7 +61,7 @@ func TestSqlStatusStore(t *testing.T) {
} }
} }
if result := <-store.Status().GetByIds([]string{status.UserId, "junk"}); result.Err != nil { if result := <-ss.Status().GetByIds([]string{status.UserId, "junk"}); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
statuses := result.Data.([]*model.Status) statuses := result.Data.([]*model.Status)
@@ -69,11 +70,11 @@ func TestSqlStatusStore(t *testing.T) {
} }
} }
if err := (<-store.Status().ResetAll()).Err; err != nil { if err := (<-ss.Status().ResetAll()).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if result := <-store.Status().Get(status.UserId); result.Err != nil { if result := <-ss.Status().Get(status.UserId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
status := result.Data.(*model.Status) status := result.Data.(*model.Status)
@@ -82,18 +83,18 @@ func TestSqlStatusStore(t *testing.T) {
} }
} }
if result := <-store.Status().UpdateLastActivityAt(status.UserId, 10); result.Err != nil { if result := <-ss.Status().UpdateLastActivityAt(status.UserId, 10); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
} }
func TestActiveUserCount(t *testing.T) { func TestActiveUserCount(t *testing.T) {
Setup() ss := Setup()
status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""}
Must(store.Status().SaveOrUpdate(status)) store.Must(ss.Status().SaveOrUpdate(status))
if result := <-store.Status().GetTotalActiveUsersCount(); result.Err != nil { if result := <-ss.Status().GetTotalActiveUsersCount(); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
count := result.Data.(int64) count := result.Data.(int64)

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

@@ -1,12 +1,14 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/store"
) )
/*type SqlStore struct { /*type SqlStore struct {
@@ -60,26 +62,26 @@ type SqlStore interface {
RemoveIndexIfExists(indexName string, tableName string) bool RemoveIndexIfExists(indexName string, tableName string) bool
GetAllConns() []*gorp.DbMap GetAllConns() []*gorp.DbMap
Close() Close()
Team() TeamStore Team() store.TeamStore
Channel() ChannelStore Channel() store.ChannelStore
Post() PostStore Post() store.PostStore
User() UserStore User() store.UserStore
Audit() AuditStore Audit() store.AuditStore
ClusterDiscovery() ClusterDiscoveryStore ClusterDiscovery() store.ClusterDiscoveryStore
Compliance() ComplianceStore Compliance() store.ComplianceStore
Session() SessionStore Session() store.SessionStore
OAuth() OAuthStore OAuth() store.OAuthStore
System() SystemStore System() store.SystemStore
Webhook() WebhookStore Webhook() store.WebhookStore
Command() CommandStore Command() store.CommandStore
CommandWebhook() CommandWebhookStore CommandWebhook() store.CommandWebhookStore
Preference() PreferenceStore Preference() store.PreferenceStore
License() LicenseStore License() store.LicenseStore
Token() TokenStore Token() store.TokenStore
Emoji() EmojiStore Emoji() store.EmojiStore
Status() StatusStore Status() store.StatusStore
FileInfo() FileInfoStore FileInfo() store.FileInfoStore
Reaction() ReactionStore Reaction() store.ReactionStore
Job() JobStore Job() store.JobStore
UserAccessToken() UserAccessTokenStore UserAccessToken() store.UserAccessTokenStore
} }

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

@@ -1,21 +1,25 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import "github.com/mattermost/mattermost-server/utils" import (
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils"
)
var store Store var sqlStore store.Store
func Setup() { func Setup() store.Store {
if store == nil { if sqlStore == nil {
utils.TranslationsPreInit() utils.TranslationsPreInit()
utils.LoadConfig("config.json") utils.LoadConfig("config.json")
utils.InitTranslations(utils.Cfg.LocalizationSettings) utils.InitTranslations(utils.Cfg.LocalizationSettings)
store = NewLayeredStore(nil, nil) sqlStore = store.NewLayeredStore(NewSqlSupplier(nil), nil, nil)
store.MarkSystemRanUnitTests() sqlStore.MarkSystemRanUnitTests()
} }
return sqlStore
} }
/* /*
@@ -25,20 +29,20 @@ func TestSqlStore1(t *testing.T) {
utils.Cfg.SqlSettings.Trace = true utils.Cfg.SqlSettings.Trace = true
store := NewSqlStore() store := NewSqlStore()
store.Close() ss.Close()
utils.Cfg.SqlSettings.DataSourceReplicas = []string{utils.Cfg.SqlSettings.DataSource} utils.Cfg.SqlSettings.DataSourceReplicas = []string{utils.Cfg.SqlSettings.DataSource}
store = NewSqlStore() store = NewSqlStore()
store.TotalMasterDbConnections() ss.TotalMasterDbConnections()
store.TotalReadDbConnections() ss.TotalReadDbConnections()
store.Close() ss.Close()
utils.LoadConfig("config.json") utils.LoadConfig("config.json")
} }
func TestAlertDbCmds(t *testing.T) { func TestAlertDbCmds(t *testing.T) {
Setup() ss := Setup()
sqlStore := store.(SqlStore) sqlStore := store.(SqlStore)
@@ -98,7 +102,7 @@ func TestAlertDbCmds(t *testing.T) {
} }
func TestCreateIndexIfNotExists(t *testing.T) { func TestCreateIndexIfNotExists(t *testing.T) {
Setup() ss := Setup()
sqlStore := store.(SqlStore) sqlStore := store.(SqlStore)
@@ -118,7 +122,7 @@ func TestCreateIndexIfNotExists(t *testing.T) {
} }
func TestRemoveIndexIfExists(t *testing.T) { func TestRemoveIndexIfExists(t *testing.T) {
Setup() ss := Setup()
sqlStore := store.(SqlStore) sqlStore := store.(SqlStore)

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

@@ -1,7 +1,7 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"context" "context"
@@ -21,6 +21,7 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -61,28 +62,28 @@ const (
) )
type SqlSupplierOldStores struct { type SqlSupplierOldStores struct {
team TeamStore team store.TeamStore
channel ChannelStore channel store.ChannelStore
post PostStore post store.PostStore
user UserStore user store.UserStore
audit AuditStore audit store.AuditStore
cluster ClusterDiscoveryStore cluster store.ClusterDiscoveryStore
compliance ComplianceStore compliance store.ComplianceStore
session SessionStore session store.SessionStore
oauth OAuthStore oauth store.OAuthStore
system SystemStore system store.SystemStore
webhook WebhookStore webhook store.WebhookStore
command CommandStore command store.CommandStore
commandWebhook CommandWebhookStore commandWebhook store.CommandWebhookStore
preference PreferenceStore preference store.PreferenceStore
license LicenseStore license store.LicenseStore
token TokenStore token store.TokenStore
emoji EmojiStore emoji store.EmojiStore
status StatusStore status store.StatusStore
fileInfo FileInfoStore fileInfo store.FileInfoStore
reaction ReactionStore reaction store.ReactionStore
job JobStore job store.JobStore
userAccessToken UserAccessTokenStore userAccessToken store.UserAccessTokenStore
} }
type SqlSupplier struct { type SqlSupplier struct {
@@ -90,7 +91,7 @@ type SqlSupplier struct {
// See https://github.com/mattermost/mattermost-server/pull/7281 // See https://github.com/mattermost/mattermost-server/pull/7281
rrCounter int64 rrCounter int64
srCounter int64 srCounter int64
next LayeredStoreSupplier next store.LayeredStoreSupplier
master *gorp.DbMap master *gorp.DbMap
replicas []*gorp.DbMap replicas []*gorp.DbMap
searchReplicas []*gorp.DbMap searchReplicas []*gorp.DbMap
@@ -164,11 +165,11 @@ func NewSqlSupplier(metrics einterfaces.MetricsInterface) *SqlSupplier {
return supplier return supplier
} }
func (s *SqlSupplier) SetChainNext(next LayeredStoreSupplier) { func (s *SqlSupplier) SetChainNext(next store.LayeredStoreSupplier) {
s.next = next s.next = next
} }
func (s *SqlSupplier) Next() LayeredStoreSupplier { func (s *SqlSupplier) Next() store.LayeredStoreSupplier {
return s.next return s.next
} }
@@ -700,91 +701,91 @@ func (ss *SqlSupplier) Close() {
} }
} }
func (ss *SqlSupplier) Team() TeamStore { func (ss *SqlSupplier) Team() store.TeamStore {
return ss.oldStores.team return ss.oldStores.team
} }
func (ss *SqlSupplier) Channel() ChannelStore { func (ss *SqlSupplier) Channel() store.ChannelStore {
return ss.oldStores.channel return ss.oldStores.channel
} }
func (ss *SqlSupplier) Post() PostStore { func (ss *SqlSupplier) Post() store.PostStore {
return ss.oldStores.post return ss.oldStores.post
} }
func (ss *SqlSupplier) User() UserStore { func (ss *SqlSupplier) User() store.UserStore {
return ss.oldStores.user return ss.oldStores.user
} }
func (ss *SqlSupplier) Session() SessionStore { func (ss *SqlSupplier) Session() store.SessionStore {
return ss.oldStores.session return ss.oldStores.session
} }
func (ss *SqlSupplier) Audit() AuditStore { func (ss *SqlSupplier) Audit() store.AuditStore {
return ss.oldStores.audit return ss.oldStores.audit
} }
func (ss *SqlSupplier) ClusterDiscovery() ClusterDiscoveryStore { func (ss *SqlSupplier) ClusterDiscovery() store.ClusterDiscoveryStore {
return ss.oldStores.cluster return ss.oldStores.cluster
} }
func (ss *SqlSupplier) Compliance() ComplianceStore { func (ss *SqlSupplier) Compliance() store.ComplianceStore {
return ss.oldStores.compliance return ss.oldStores.compliance
} }
func (ss *SqlSupplier) OAuth() OAuthStore { func (ss *SqlSupplier) OAuth() store.OAuthStore {
return ss.oldStores.oauth return ss.oldStores.oauth
} }
func (ss *SqlSupplier) System() SystemStore { func (ss *SqlSupplier) System() store.SystemStore {
return ss.oldStores.system return ss.oldStores.system
} }
func (ss *SqlSupplier) Webhook() WebhookStore { func (ss *SqlSupplier) Webhook() store.WebhookStore {
return ss.oldStores.webhook return ss.oldStores.webhook
} }
func (ss *SqlSupplier) Command() CommandStore { func (ss *SqlSupplier) Command() store.CommandStore {
return ss.oldStores.command return ss.oldStores.command
} }
func (ss *SqlSupplier) CommandWebhook() CommandWebhookStore { func (ss *SqlSupplier) CommandWebhook() store.CommandWebhookStore {
return ss.oldStores.commandWebhook return ss.oldStores.commandWebhook
} }
func (ss *SqlSupplier) Preference() PreferenceStore { func (ss *SqlSupplier) Preference() store.PreferenceStore {
return ss.oldStores.preference return ss.oldStores.preference
} }
func (ss *SqlSupplier) License() LicenseStore { func (ss *SqlSupplier) License() store.LicenseStore {
return ss.oldStores.license return ss.oldStores.license
} }
func (ss *SqlSupplier) Token() TokenStore { func (ss *SqlSupplier) Token() store.TokenStore {
return ss.oldStores.token return ss.oldStores.token
} }
func (ss *SqlSupplier) Emoji() EmojiStore { func (ss *SqlSupplier) Emoji() store.EmojiStore {
return ss.oldStores.emoji return ss.oldStores.emoji
} }
func (ss *SqlSupplier) Status() StatusStore { func (ss *SqlSupplier) Status() store.StatusStore {
return ss.oldStores.status return ss.oldStores.status
} }
func (ss *SqlSupplier) FileInfo() FileInfoStore { func (ss *SqlSupplier) FileInfo() store.FileInfoStore {
return ss.oldStores.fileInfo return ss.oldStores.fileInfo
} }
func (ss *SqlSupplier) Reaction() ReactionStore { func (ss *SqlSupplier) Reaction() store.ReactionStore {
return ss.oldStores.reaction return ss.oldStores.reaction
} }
func (ss *SqlSupplier) Job() JobStore { func (ss *SqlSupplier) Job() store.JobStore {
return ss.oldStores.job return ss.oldStores.job
} }
func (ss *SqlSupplier) UserAccessToken() UserAccessTokenStore { func (ss *SqlSupplier) UserAccessToken() store.UserAccessTokenStore {
return ss.oldStores.userAccessToken return ss.oldStores.userAccessToken
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"context" "context"
@@ -11,6 +11,7 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -23,8 +24,8 @@ func initSqlSupplierReactions(sqlStore SqlStore) {
} }
} }
func (s *SqlSupplier) ReactionSave(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *SqlSupplier) ReactionSave(ctx context.Context, reaction *model.Reaction, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
result := NewSupplierResult() result := store.NewSupplierResult()
reaction.PreSave() reaction.PreSave()
if result.Err = reaction.IsValid(); result.Err != nil { if result.Err = reaction.IsValid(); result.Err != nil {
@@ -58,8 +59,8 @@ func (s *SqlSupplier) ReactionSave(ctx context.Context, reaction *model.Reaction
return result return result
} }
func (s *SqlSupplier) ReactionDelete(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *SqlSupplier) ReactionDelete(ctx context.Context, reaction *model.Reaction, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
result := NewSupplierResult() result := store.NewSupplierResult()
if transaction, err := s.GetMaster().Begin(); err != nil { if transaction, err := s.GetMaster().Begin(); err != nil {
result.Err = model.NewAppError("SqlReactionStore.Delete", "store.sql_reaction.delete.begin.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlReactionStore.Delete", "store.sql_reaction.delete.begin.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -81,8 +82,8 @@ func (s *SqlSupplier) ReactionDelete(ctx context.Context, reaction *model.Reacti
return result return result
} }
func (s *SqlSupplier) ReactionGetForPost(ctx context.Context, postId string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *SqlSupplier) ReactionGetForPost(ctx context.Context, postId string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
result := NewSupplierResult() result := store.NewSupplierResult()
var reactions []*model.Reaction var reactions []*model.Reaction
@@ -103,8 +104,8 @@ func (s *SqlSupplier) ReactionGetForPost(ctx context.Context, postId string, hin
return result return result
} }
func (s *SqlSupplier) ReactionDeleteAllWithEmojiName(ctx context.Context, emojiName string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *SqlSupplier) ReactionDeleteAllWithEmojiName(ctx context.Context, emojiName string, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
result := NewSupplierResult() result := store.NewSupplierResult()
var reactions []*model.Reaction var reactions []*model.Reaction
@@ -142,8 +143,8 @@ func (s *SqlSupplier) ReactionDeleteAllWithEmojiName(ctx context.Context, emojiN
return result return result
} }
func (s *SqlSupplier) ReactionPermanentDeleteBatch(ctx context.Context, endTime int64, limit int64, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *SqlSupplier) ReactionPermanentDeleteBatch(ctx context.Context, endTime int64, limit int64, hints ...store.LayeredStoreHint) *store.LayeredStoreSupplierResult {
result := NewSupplierResult() result := store.NewSupplierResult()
var query string var query string
if *utils.Cfg.SqlSettings.DriverName == "postgres" { if *utils.Cfg.SqlSettings.DriverName == "postgres" {

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

@@ -1,19 +1,20 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlSystemStore struct { type SqlSystemStore struct {
SqlStore SqlStore
} }
func NewSqlSystemStore(sqlStore SqlStore) SystemStore { func NewSqlSystemStore(sqlStore SqlStore) store.SystemStore {
s := &SqlSystemStore{sqlStore} s := &SqlSystemStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -28,12 +29,12 @@ func NewSqlSystemStore(sqlStore SqlStore) SystemStore {
func (s SqlSystemStore) CreateIndexesIfNotExists() { func (s SqlSystemStore) CreateIndexesIfNotExists() {
} }
func (s SqlSystemStore) Save(system *model.System) StoreChannel { func (s SqlSystemStore) Save(system *model.System) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if err := s.GetMaster().Insert(system); err != nil { if err := s.GetMaster().Insert(system); err != nil {
result.Err = model.NewAppError("SqlSystemStore.Save", "store.sql_system.save.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlSystemStore.Save", "store.sql_system.save.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -46,12 +47,12 @@ func (s SqlSystemStore) Save(system *model.System) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlSystemStore) SaveOrUpdate(system *model.System) StoreChannel { func (s SqlSystemStore) SaveOrUpdate(system *model.System) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if err := s.GetReplica().SelectOne(&model.System{}, "SELECT * FROM Systems WHERE Name = :Name", map[string]interface{}{"Name": system.Name}); err == nil { if err := s.GetReplica().SelectOne(&model.System{}, "SELECT * FROM Systems WHERE Name = :Name", map[string]interface{}{"Name": system.Name}); err == nil {
if _, err := s.GetMaster().Update(system); err != nil { if _, err := s.GetMaster().Update(system); err != nil {
@@ -70,12 +71,12 @@ func (s SqlSystemStore) SaveOrUpdate(system *model.System) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlSystemStore) Update(system *model.System) StoreChannel { func (s SqlSystemStore) Update(system *model.System) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Update(system); err != nil { if _, err := s.GetMaster().Update(system); err != nil {
result.Err = model.NewAppError("SqlSystemStore.Update", "store.sql_system.update.app_error", nil, "", http.StatusInternalServerError) result.Err = model.NewAppError("SqlSystemStore.Update", "store.sql_system.update.app_error", nil, "", http.StatusInternalServerError)
@@ -88,12 +89,12 @@ func (s SqlSystemStore) Update(system *model.System) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlSystemStore) Get() StoreChannel { func (s SqlSystemStore) Get() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var systems []model.System var systems []model.System
props := make(model.StringMap) props := make(model.StringMap)
@@ -114,12 +115,12 @@ func (s SqlSystemStore) Get() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlSystemStore) GetByName(name string) StoreChannel { func (s SqlSystemStore) GetByName(name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var system model.System var system model.System
if err := s.GetReplica().SelectOne(&system, "SELECT * FROM Systems WHERE Name = :Name", map[string]interface{}{"Name": name}); err != nil { if err := s.GetReplica().SelectOne(&system, "SELECT * FROM Systems WHERE Name = :Name", map[string]interface{}{"Name": name}); err != nil {

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

@@ -1,21 +1,22 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestSqlSystemStore(t *testing.T) { func TestSqlSystemStore(t *testing.T) {
Setup() ss := Setup()
system := &model.System{Name: model.NewId(), Value: "value"} system := &model.System{Name: model.NewId(), Value: "value"}
Must(store.System().Save(system)) store.Must(ss.System().Save(system))
result := <-store.System().Get() result := <-ss.System().Get()
systems := result.Data.(model.StringMap) systems := result.Data.(model.StringMap)
if systems[system.Name] != system.Value { if systems[system.Name] != system.Value {
@@ -23,16 +24,16 @@ func TestSqlSystemStore(t *testing.T) {
} }
system.Value = "value2" system.Value = "value2"
Must(store.System().Update(system)) store.Must(ss.System().Update(system))
result2 := <-store.System().Get() result2 := <-ss.System().Get()
systems2 := result2.Data.(model.StringMap) systems2 := result2.Data.(model.StringMap)
if systems2[system.Name] != system.Value { if systems2[system.Name] != system.Value {
t.Fatal() t.Fatal()
} }
result3 := <-store.System().GetByName(system.Name) result3 := <-ss.System().GetByName(system.Name)
rsystem := result3.Data.(*model.System) rsystem := result3.Data.(*model.System)
if rsystem.Value != system.Value { if rsystem.Value != system.Value {
t.Fatal() t.Fatal()
@@ -40,17 +41,17 @@ func TestSqlSystemStore(t *testing.T) {
} }
func TestSqlSystemStoreSaveOrUpdate(t *testing.T) { func TestSqlSystemStoreSaveOrUpdate(t *testing.T) {
Setup() ss := Setup()
system := &model.System{Name: model.NewId(), Value: "value"} system := &model.System{Name: model.NewId(), Value: "value"}
if err := (<-store.System().SaveOrUpdate(system)).Err; err != nil { if err := (<-ss.System().SaveOrUpdate(system)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
system.Value = "value2" system.Value = "value2"
if r := <-store.System().SaveOrUpdate(system); r.Err != nil { if r := <-ss.System().SaveOrUpdate(system); r.Err != nil {
t.Fatal(r.Err) t.Fatal(r.Err)
} }
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -9,6 +9,7 @@ import (
"strconv" "strconv"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -20,7 +21,7 @@ type SqlTeamStore struct {
SqlStore SqlStore
} }
func NewSqlTeamStore(sqlStore SqlStore) TeamStore { func NewSqlTeamStore(sqlStore SqlStore) store.TeamStore {
s := &SqlTeamStore{sqlStore} s := &SqlTeamStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -56,11 +57,11 @@ func (s SqlTeamStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_teammembers_delete_at", "TeamMembers", "DeleteAt") s.CreateIndexIfNotExists("idx_teammembers_delete_at", "TeamMembers", "DeleteAt")
} }
func (s SqlTeamStore) Save(team *model.Team) StoreChannel { func (s SqlTeamStore) Save(team *model.Team) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(team.Id) > 0 { if len(team.Id) > 0 {
result.Err = model.NewAppError("SqlTeamStore.Save", result.Err = model.NewAppError("SqlTeamStore.Save",
@@ -95,12 +96,12 @@ func (s SqlTeamStore) Save(team *model.Team) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) Update(team *model.Team) StoreChannel { func (s SqlTeamStore) Update(team *model.Team) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
team.PreUpdate() team.PreUpdate()
@@ -136,12 +137,12 @@ func (s SqlTeamStore) Update(team *model.Team) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) UpdateDisplayName(name string, teamId string) StoreChannel { func (s SqlTeamStore) UpdateDisplayName(name string, teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("UPDATE Teams SET DisplayName = :Name WHERE Id = :Id", map[string]interface{}{"Name": name, "Id": teamId}); err != nil { if _, err := s.GetMaster().Exec("UPDATE Teams SET DisplayName = :Name WHERE Id = :Id", map[string]interface{}{"Name": name, "Id": teamId}); err != nil {
result.Err = model.NewAppError("SqlTeamStore.UpdateName", "store.sql_team.update_display_name.app_error", nil, "team_id="+teamId, http.StatusInternalServerError) result.Err = model.NewAppError("SqlTeamStore.UpdateName", "store.sql_team.update_display_name.app_error", nil, "team_id="+teamId, http.StatusInternalServerError)
@@ -156,11 +157,11 @@ func (s SqlTeamStore) UpdateDisplayName(name string, teamId string) StoreChannel
return storeChannel return storeChannel
} }
func (s SqlTeamStore) Get(id string) StoreChannel { func (s SqlTeamStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if obj, err := s.GetReplica().Get(model.Team{}, id); err != nil { if obj, err := s.GetReplica().Get(model.Team{}, id); err != nil {
result.Err = model.NewAppError("SqlTeamStore.Get", "store.sql_team.get.finding.app_error", nil, "id="+id+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlTeamStore.Get", "store.sql_team.get.finding.app_error", nil, "id="+id+", "+err.Error(), http.StatusInternalServerError)
@@ -182,11 +183,11 @@ func (s SqlTeamStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetByInviteId(inviteId string) StoreChannel { func (s SqlTeamStore) GetByInviteId(inviteId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
team := model.Team{} team := model.Team{}
@@ -211,11 +212,11 @@ func (s SqlTeamStore) GetByInviteId(inviteId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetByName(name string) StoreChannel { func (s SqlTeamStore) GetByName(name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
team := model.Team{} team := model.Team{}
@@ -236,11 +237,11 @@ func (s SqlTeamStore) GetByName(name string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) SearchByName(name string) StoreChannel { func (s SqlTeamStore) SearchByName(name string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var teams []*model.Team var teams []*model.Team
@@ -257,11 +258,11 @@ func (s SqlTeamStore) SearchByName(name string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) SearchAll(term string) StoreChannel { func (s SqlTeamStore) SearchAll(term string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var teams []*model.Team var teams []*model.Team
@@ -278,11 +279,11 @@ func (s SqlTeamStore) SearchAll(term string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) SearchOpen(term string) StoreChannel { func (s SqlTeamStore) SearchOpen(term string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var teams []*model.Team var teams []*model.Team
@@ -299,11 +300,11 @@ func (s SqlTeamStore) SearchOpen(term string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetAll() StoreChannel { func (s SqlTeamStore) GetAll() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.Team var data []*model.Team
if _, err := s.GetReplica().Select(&data, "SELECT * FROM Teams"); err != nil { if _, err := s.GetReplica().Select(&data, "SELECT * FROM Teams"); err != nil {
@@ -325,11 +326,11 @@ func (s SqlTeamStore) GetAll() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetAllPage(offset int, limit int) StoreChannel { func (s SqlTeamStore) GetAllPage(offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.Team var data []*model.Team
if _, err := s.GetReplica().Select(&data, "SELECT * FROM Teams LIMIT :Limit OFFSET :Offset", map[string]interface{}{"Offset": offset, "Limit": limit}); err != nil { if _, err := s.GetReplica().Select(&data, "SELECT * FROM Teams LIMIT :Limit OFFSET :Offset", map[string]interface{}{"Offset": offset, "Limit": limit}); err != nil {
@@ -351,11 +352,11 @@ func (s SqlTeamStore) GetAllPage(offset int, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetTeamsByUserId(userId string) StoreChannel { func (s SqlTeamStore) GetTeamsByUserId(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.Team var data []*model.Team
if _, err := s.GetReplica().Select(&data, "SELECT Teams.* FROM Teams, TeamMembers WHERE TeamMembers.TeamId = Teams.Id AND TeamMembers.UserId = :UserId AND TeamMembers.DeleteAt = 0 AND Teams.DeleteAt = 0", map[string]interface{}{"UserId": userId}); err != nil { if _, err := s.GetReplica().Select(&data, "SELECT Teams.* FROM Teams, TeamMembers WHERE TeamMembers.TeamId = Teams.Id AND TeamMembers.UserId = :UserId AND TeamMembers.DeleteAt = 0 AND Teams.DeleteAt = 0", map[string]interface{}{"UserId": userId}); err != nil {
@@ -377,11 +378,11 @@ func (s SqlTeamStore) GetTeamsByUserId(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetAllTeamListing() StoreChannel { func (s SqlTeamStore) GetAllTeamListing() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := "SELECT * FROM Teams WHERE AllowOpenInvite = 1" query := "SELECT * FROM Teams WHERE AllowOpenInvite = 1"
@@ -409,11 +410,11 @@ func (s SqlTeamStore) GetAllTeamListing() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetAllTeamPageListing(offset int, limit int) StoreChannel { func (s SqlTeamStore) GetAllTeamPageListing(offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := "SELECT * FROM Teams WHERE AllowOpenInvite = 1 LIMIT :Limit OFFSET :Offset" query := "SELECT * FROM Teams WHERE AllowOpenInvite = 1 LIMIT :Limit OFFSET :Offset"
@@ -441,11 +442,11 @@ func (s SqlTeamStore) GetAllTeamPageListing(offset int, limit int) StoreChannel
return storeChannel return storeChannel
} }
func (s SqlTeamStore) PermanentDelete(teamId string) StoreChannel { func (s SqlTeamStore) PermanentDelete(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM Teams WHERE Id = :TeamId", map[string]interface{}{"TeamId": teamId}); err != nil { if _, err := s.GetMaster().Exec("DELETE FROM Teams WHERE Id = :TeamId", map[string]interface{}{"TeamId": teamId}); err != nil {
result.Err = model.NewAppError("SqlTeamStore.Delete", "store.sql_team.permanent_delete.app_error", nil, "teamId="+teamId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlTeamStore.Delete", "store.sql_team.permanent_delete.app_error", nil, "teamId="+teamId+", "+err.Error(), http.StatusInternalServerError)
@@ -458,11 +459,11 @@ func (s SqlTeamStore) PermanentDelete(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) AnalyticsTeamCount() StoreChannel { func (s SqlTeamStore) AnalyticsTeamCount() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if c, err := s.GetReplica().SelectInt("SELECT COUNT(*) FROM Teams WHERE DeleteAt = 0", map[string]interface{}{}); err != nil { if c, err := s.GetReplica().SelectInt("SELECT COUNT(*) FROM Teams WHERE DeleteAt = 0", map[string]interface{}{}); err != nil {
result.Err = model.NewAppError("SqlTeamStore.AnalyticsTeamCount", "store.sql_team.analytics_team_count.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlTeamStore.AnalyticsTeamCount", "store.sql_team.analytics_team_count.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -477,11 +478,11 @@ func (s SqlTeamStore) AnalyticsTeamCount() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) SaveMember(member *model.TeamMember) StoreChannel { func (s SqlTeamStore) SaveMember(member *model.TeamMember) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if result.Err = member.IsValid(); result.Err != nil { if result.Err = member.IsValid(); result.Err != nil {
storeChannel <- result storeChannel <- result
@@ -530,11 +531,11 @@ func (s SqlTeamStore) SaveMember(member *model.TeamMember) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) UpdateMember(member *model.TeamMember) StoreChannel { func (s SqlTeamStore) UpdateMember(member *model.TeamMember) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
member.PreUpdate() member.PreUpdate()
@@ -557,11 +558,11 @@ func (s SqlTeamStore) UpdateMember(member *model.TeamMember) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetMember(teamId string, userId string) StoreChannel { func (s SqlTeamStore) GetMember(teamId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var member model.TeamMember var member model.TeamMember
err := s.GetReplica().SelectOne(&member, "SELECT * FROM TeamMembers WHERE TeamId = :TeamId AND UserId = :UserId", map[string]interface{}{"TeamId": teamId, "UserId": userId}) err := s.GetReplica().SelectOne(&member, "SELECT * FROM TeamMembers WHERE TeamId = :TeamId AND UserId = :UserId", map[string]interface{}{"TeamId": teamId, "UserId": userId})
@@ -582,11 +583,11 @@ func (s SqlTeamStore) GetMember(teamId string, userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetMembers(teamId string, offset int, limit int) StoreChannel { func (s SqlTeamStore) GetMembers(teamId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var members []*model.TeamMember var members []*model.TeamMember
_, err := s.GetReplica().Select(&members, "SELECT * FROM TeamMembers WHERE TeamId = :TeamId AND DeleteAt = 0 LIMIT :Limit OFFSET :Offset", map[string]interface{}{"TeamId": teamId, "Offset": offset, "Limit": limit}) _, err := s.GetReplica().Select(&members, "SELECT * FROM TeamMembers WHERE TeamId = :TeamId AND DeleteAt = 0 LIMIT :Limit OFFSET :Offset", map[string]interface{}{"TeamId": teamId, "Offset": offset, "Limit": limit})
@@ -603,11 +604,11 @@ func (s SqlTeamStore) GetMembers(teamId string, offset int, limit int) StoreChan
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetTotalMemberCount(teamId string) StoreChannel { func (s SqlTeamStore) GetTotalMemberCount(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
count, err := s.GetReplica().SelectInt(` count, err := s.GetReplica().SelectInt(`
SELECT SELECT
@@ -632,11 +633,11 @@ func (s SqlTeamStore) GetTotalMemberCount(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetActiveMemberCount(teamId string) StoreChannel { func (s SqlTeamStore) GetActiveMemberCount(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
count, err := s.GetReplica().SelectInt(` count, err := s.GetReplica().SelectInt(`
SELECT SELECT
@@ -662,11 +663,11 @@ func (s SqlTeamStore) GetActiveMemberCount(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetMembersByIds(teamId string, userIds []string) StoreChannel { func (s SqlTeamStore) GetMembersByIds(teamId string, userIds []string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var members []*model.TeamMember var members []*model.TeamMember
props := make(map[string]interface{}) props := make(map[string]interface{})
@@ -696,11 +697,11 @@ func (s SqlTeamStore) GetMembersByIds(teamId string, userIds []string) StoreChan
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetTeamsForUser(userId string) StoreChannel { func (s SqlTeamStore) GetTeamsForUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var members []*model.TeamMember var members []*model.TeamMember
_, err := s.GetReplica().Select(&members, "SELECT * FROM TeamMembers WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}) _, err := s.GetReplica().Select(&members, "SELECT * FROM TeamMembers WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
@@ -717,11 +718,11 @@ func (s SqlTeamStore) GetTeamsForUser(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetChannelUnreadsForAllTeams(excludeTeamId, userId string) StoreChannel { func (s SqlTeamStore) GetChannelUnreadsForAllTeams(excludeTeamId, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.ChannelUnread var data []*model.ChannelUnread
_, err := s.GetReplica().Select(&data, _, err := s.GetReplica().Select(&data,
@@ -749,11 +750,11 @@ func (s SqlTeamStore) GetChannelUnreadsForAllTeams(excludeTeamId, userId string)
return storeChannel return storeChannel
} }
func (s SqlTeamStore) GetChannelUnreadsForTeam(teamId, userId string) StoreChannel { func (s SqlTeamStore) GetChannelUnreadsForTeam(teamId, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.ChannelUnread var data []*model.ChannelUnread
_, err := s.GetReplica().Select(&data, _, err := s.GetReplica().Select(&data,
@@ -781,11 +782,11 @@ func (s SqlTeamStore) GetChannelUnreadsForTeam(teamId, userId string) StoreChann
return storeChannel return storeChannel
} }
func (s SqlTeamStore) RemoveMember(teamId string, userId string) StoreChannel { func (s SqlTeamStore) RemoveMember(teamId string, userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM TeamMembers WHERE TeamId = :TeamId AND UserId = :UserId", map[string]interface{}{"TeamId": teamId, "UserId": userId}) _, err := s.GetMaster().Exec("DELETE FROM TeamMembers WHERE TeamId = :TeamId AND UserId = :UserId", map[string]interface{}{"TeamId": teamId, "UserId": userId})
if err != nil { if err != nil {
@@ -799,11 +800,11 @@ func (s SqlTeamStore) RemoveMember(teamId string, userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) RemoveAllMembersByTeam(teamId string) StoreChannel { func (s SqlTeamStore) RemoveAllMembersByTeam(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM TeamMembers WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId}) _, err := s.GetMaster().Exec("DELETE FROM TeamMembers WHERE TeamId = :TeamId", map[string]interface{}{"TeamId": teamId})
if err != nil { if err != nil {
@@ -817,11 +818,11 @@ func (s SqlTeamStore) RemoveAllMembersByTeam(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTeamStore) RemoveAllMembersByUser(userId string) StoreChannel { func (s SqlTeamStore) RemoveAllMembersByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM TeamMembers WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}) _, err := s.GetMaster().Exec("DELETE FROM TeamMembers WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {

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

@@ -1,18 +1,19 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"time" "time"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
func TestTeamStoreSave(t *testing.T) { func TestTeamStoreSave(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -20,82 +21,82 @@ func TestTeamStoreSave(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err) t.Fatal("couldn't save item", err)
} }
if err := (<-store.Team().Save(&o1)).Err; err == nil { if err := (<-ss.Team().Save(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save") t.Fatal("shouldn't be able to update from save")
} }
o1.Id = "" o1.Id = ""
if err := (<-store.Team().Save(&o1)).Err; err == nil { if err := (<-ss.Team().Save(&o1)).Err; err == nil {
t.Fatal("should be unique domain") t.Fatal("should be unique domain")
} }
} }
func TestTeamStoreUpdate(t *testing.T) { func TestTeamStoreUpdate(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
o1.Name = "z-z-z" + model.NewId() + "b" o1.Name = "z-z-z" + model.NewId() + "b"
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
if err := (<-store.Team().Update(&o1)).Err; err != nil { if err := (<-ss.Team().Update(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
o1.Id = "missing" o1.Id = "missing"
if err := (<-store.Team().Update(&o1)).Err; err == nil { if err := (<-ss.Team().Update(&o1)).Err; err == nil {
t.Fatal("Update should have failed because of missing key") t.Fatal("Update should have failed because of missing key")
} }
o1.Id = model.NewId() o1.Id = model.NewId()
if err := (<-store.Team().Update(&o1)).Err; err == nil { if err := (<-ss.Team().Update(&o1)).Err; err == nil {
t.Fatal("Update should have faile because id change") t.Fatal("Update should have faile because id change")
} }
} }
func TestTeamStoreUpdateDisplayName(t *testing.T) { func TestTeamStoreUpdateDisplayName(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Team{} o1 := &model.Team{}
o1.DisplayName = "Display Name" o1.DisplayName = "Display Name"
o1.Name = "z-z-z" + model.NewId() + "b" o1.Name = "z-z-z" + model.NewId() + "b"
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1 = (<-store.Team().Save(o1)).Data.(*model.Team) o1 = (<-ss.Team().Save(o1)).Data.(*model.Team)
newDisplayName := "NewDisplayName" newDisplayName := "NewDisplayName"
if err := (<-store.Team().UpdateDisplayName(newDisplayName, o1.Id)).Err; err != nil { if err := (<-ss.Team().UpdateDisplayName(newDisplayName, o1.Id)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
ro1 := (<-store.Team().Get(o1.Id)).Data.(*model.Team) ro1 := (<-ss.Team().Get(o1.Id)).Data.(*model.Team)
if ro1.DisplayName != newDisplayName { if ro1.DisplayName != newDisplayName {
t.Fatal("DisplayName not updated") t.Fatal("DisplayName not updated")
} }
} }
func TestTeamStoreGet(t *testing.T) { func TestTeamStoreGet(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
o1.Name = "z-z-z" + model.NewId() + "b" o1.Name = "z-z-z" + model.NewId() + "b"
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
Must(store.Team().Save(&o1)) store.Must(ss.Team().Save(&o1))
if r1 := <-store.Team().Get(o1.Id); r1.Err != nil { if r1 := <-ss.Team().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Team).ToJson() != o1.ToJson() { if r1.Data.(*model.Team).ToJson() != o1.ToJson() {
@@ -103,13 +104,13 @@ func TestTeamStoreGet(t *testing.T) {
} }
} }
if err := (<-store.Team().Get("")).Err; err == nil { if err := (<-ss.Team().Get("")).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestTeamStoreGetByName(t *testing.T) { func TestTeamStoreGetByName(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -117,11 +118,11 @@ func TestTeamStoreGetByName(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if r1 := <-store.Team().GetByName(o1.Name); r1.Err != nil { if r1 := <-ss.Team().GetByName(o1.Name); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Team).ToJson() != o1.ToJson() { if r1.Data.(*model.Team).ToJson() != o1.ToJson() {
@@ -129,13 +130,13 @@ func TestTeamStoreGetByName(t *testing.T) {
} }
} }
if err := (<-store.Team().GetByName("")).Err; err == nil { if err := (<-ss.Team().GetByName("")).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestTeamStoreSearchByName(t *testing.T) { func TestTeamStoreSearchByName(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -144,11 +145,11 @@ func TestTeamStoreSearchByName(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if r1 := <-store.Team().SearchByName(name); r1.Err != nil { if r1 := <-ss.Team().SearchByName(name); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.([]*model.Team)[0].ToJson() != o1.ToJson() { if r1.Data.([]*model.Team)[0].ToJson() != o1.ToJson() {
@@ -158,7 +159,7 @@ func TestTeamStoreSearchByName(t *testing.T) {
} }
func TestTeamStoreSearchAll(t *testing.T) { func TestTeamStoreSearchAll(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "ADisplayName" + model.NewId() o1.DisplayName = "ADisplayName" + model.NewId()
@@ -166,7 +167,7 @@ func TestTeamStoreSearchAll(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -176,11 +177,11 @@ func TestTeamStoreSearchAll(t *testing.T) {
p2.Email = model.NewId() + "@nowhere.com" p2.Email = model.NewId() + "@nowhere.com"
p2.Type = model.TEAM_INVITE p2.Type = model.TEAM_INVITE
if err := (<-store.Team().Save(&p2)).Err; err != nil { if err := (<-ss.Team().Save(&p2)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
r1 := <-store.Team().SearchAll(o1.Name) r1 := <-ss.Team().SearchAll(o1.Name)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -191,7 +192,7 @@ func TestTeamStoreSearchAll(t *testing.T) {
t.Fatal("invalid returned team") t.Fatal("invalid returned team")
} }
r1 = <-store.Team().SearchAll(p2.DisplayName) r1 = <-ss.Team().SearchAll(p2.DisplayName)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -202,7 +203,7 @@ func TestTeamStoreSearchAll(t *testing.T) {
t.Fatal("invalid returned team") t.Fatal("invalid returned team")
} }
r1 = <-store.Team().SearchAll("junk") r1 = <-ss.Team().SearchAll("junk")
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -212,7 +213,7 @@ func TestTeamStoreSearchAll(t *testing.T) {
} }
func TestTeamStoreSearchOpen(t *testing.T) { func TestTeamStoreSearchOpen(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "ADisplayName" + model.NewId() o1.DisplayName = "ADisplayName" + model.NewId()
@@ -221,7 +222,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.AllowOpenInvite = true o1.AllowOpenInvite = true
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -232,7 +233,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
o2.Type = model.TEAM_OPEN o2.Type = model.TEAM_OPEN
o2.AllowOpenInvite = false o2.AllowOpenInvite = false
if err := (<-store.Team().Save(&o2)).Err; err != nil { if err := (<-ss.Team().Save(&o2)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -243,11 +244,11 @@ func TestTeamStoreSearchOpen(t *testing.T) {
p2.Type = model.TEAM_INVITE p2.Type = model.TEAM_INVITE
p2.AllowOpenInvite = true p2.AllowOpenInvite = true
if err := (<-store.Team().Save(&p2)).Err; err != nil { if err := (<-ss.Team().Save(&p2)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
r1 := <-store.Team().SearchOpen(o1.Name) r1 := <-ss.Team().SearchOpen(o1.Name)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -258,7 +259,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
t.Fatal("invalid returned team") t.Fatal("invalid returned team")
} }
r1 = <-store.Team().SearchOpen(o1.DisplayName) r1 = <-ss.Team().SearchOpen(o1.DisplayName)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -269,7 +270,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
t.Fatal("invalid returned team") t.Fatal("invalid returned team")
} }
r1 = <-store.Team().SearchOpen(p2.Name) r1 = <-ss.Team().SearchOpen(p2.Name)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -277,7 +278,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
t.Fatal("should have not returned a team") t.Fatal("should have not returned a team")
} }
r1 = <-store.Team().SearchOpen(p2.DisplayName) r1 = <-ss.Team().SearchOpen(p2.DisplayName)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -285,7 +286,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
t.Fatal("should have not returned a team") t.Fatal("should have not returned a team")
} }
r1 = <-store.Team().SearchOpen("junk") r1 = <-ss.Team().SearchOpen("junk")
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -293,7 +294,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
t.Fatal("should have not returned a team") t.Fatal("should have not returned a team")
} }
r1 = <-store.Team().SearchOpen(o2.DisplayName) r1 = <-ss.Team().SearchOpen(o2.DisplayName)
if r1.Err != nil { if r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
@@ -303,7 +304,7 @@ func TestTeamStoreSearchOpen(t *testing.T) {
} }
func TestTeamStoreGetByIniviteId(t *testing.T) { func TestTeamStoreGetByIniviteId(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -312,7 +313,7 @@ func TestTeamStoreGetByIniviteId(t *testing.T) {
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.InviteId = model.NewId() o1.InviteId = model.NewId()
if err := (<-store.Team().Save(&o1)).Err; err != nil { if err := (<-ss.Team().Save(&o1)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -322,11 +323,11 @@ func TestTeamStoreGetByIniviteId(t *testing.T) {
o2.Email = model.NewId() + "@nowhere.com" o2.Email = model.NewId() + "@nowhere.com"
o2.Type = model.TEAM_OPEN o2.Type = model.TEAM_OPEN
if err := (<-store.Team().Save(&o2)).Err; err != nil { if err := (<-ss.Team().Save(&o2)).Err; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if r1 := <-store.Team().GetByInviteId(o1.InviteId); r1.Err != nil { if r1 := <-ss.Team().GetByInviteId(o1.InviteId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Team).ToJson() != o1.ToJson() { if r1.Data.(*model.Team).ToJson() != o1.ToJson() {
@@ -335,9 +336,9 @@ func TestTeamStoreGetByIniviteId(t *testing.T) {
} }
o2.InviteId = "" o2.InviteId = ""
<-store.Team().Update(&o2) <-ss.Team().Update(&o2)
if r1 := <-store.Team().GetByInviteId(o2.Id); r1.Err != nil { if r1 := <-ss.Team().GetByInviteId(o2.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.Team).Id != o2.Id { if r1.Data.(*model.Team).Id != o2.Id {
@@ -345,13 +346,13 @@ func TestTeamStoreGetByIniviteId(t *testing.T) {
} }
} }
if err := (<-store.Team().GetByInviteId("")).Err; err == nil { if err := (<-ss.Team().GetByInviteId("")).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestTeamStoreByUserId(t *testing.T) { func TestTeamStoreByUserId(t *testing.T) {
Setup() ss := Setup()
o1 := &model.Team{} o1 := &model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -359,12 +360,12 @@ func TestTeamStoreByUserId(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.InviteId = model.NewId() o1.InviteId = model.NewId()
o1 = Must(store.Team().Save(o1)).(*model.Team) o1 = store.Must(ss.Team().Save(o1)).(*model.Team)
m1 := &model.TeamMember{TeamId: o1.Id, UserId: model.NewId()} m1 := &model.TeamMember{TeamId: o1.Id, UserId: model.NewId()}
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
if r1 := <-store.Team().GetTeamsByUserId(m1.UserId); r1.Err != nil { if r1 := <-ss.Team().GetTeamsByUserId(m1.UserId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
teams := r1.Data.([]*model.Team) teams := r1.Data.([]*model.Team)
@@ -380,7 +381,7 @@ func TestTeamStoreByUserId(t *testing.T) {
} }
func TestGetAllTeamListing(t *testing.T) { func TestGetAllTeamListing(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -388,14 +389,14 @@ func TestGetAllTeamListing(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.AllowOpenInvite = true o1.AllowOpenInvite = true
Must(store.Team().Save(&o1)) store.Must(ss.Team().Save(&o1))
o2 := model.Team{} o2 := model.Team{}
o2.DisplayName = "DisplayName" o2.DisplayName = "DisplayName"
o2.Name = "zz" + model.NewId() + "b" o2.Name = "zz" + model.NewId() + "b"
o2.Email = model.NewId() + "@nowhere.com" o2.Email = model.NewId() + "@nowhere.com"
o2.Type = model.TEAM_OPEN o2.Type = model.TEAM_OPEN
Must(store.Team().Save(&o2)) store.Must(ss.Team().Save(&o2))
o3 := model.Team{} o3 := model.Team{}
o3.DisplayName = "DisplayName" o3.DisplayName = "DisplayName"
@@ -403,16 +404,16 @@ func TestGetAllTeamListing(t *testing.T) {
o3.Email = model.NewId() + "@nowhere.com" o3.Email = model.NewId() + "@nowhere.com"
o3.Type = model.TEAM_INVITE o3.Type = model.TEAM_INVITE
o3.AllowOpenInvite = true o3.AllowOpenInvite = true
Must(store.Team().Save(&o3)) store.Must(ss.Team().Save(&o3))
o4 := model.Team{} o4 := model.Team{}
o4.DisplayName = "DisplayName" o4.DisplayName = "DisplayName"
o4.Name = "zz" + model.NewId() + "b" o4.Name = "zz" + model.NewId() + "b"
o4.Email = model.NewId() + "@nowhere.com" o4.Email = model.NewId() + "@nowhere.com"
o4.Type = model.TEAM_INVITE o4.Type = model.TEAM_INVITE
Must(store.Team().Save(&o4)) store.Must(ss.Team().Save(&o4))
if r1 := <-store.Team().GetAllTeamListing(); r1.Err != nil { if r1 := <-ss.Team().GetAllTeamListing(); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
teams := r1.Data.([]*model.Team) teams := r1.Data.([]*model.Team)
@@ -430,7 +431,7 @@ func TestGetAllTeamListing(t *testing.T) {
} }
func TestGetAllTeamPageListing(t *testing.T) { func TestGetAllTeamPageListing(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -438,7 +439,7 @@ func TestGetAllTeamPageListing(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.AllowOpenInvite = true o1.AllowOpenInvite = true
Must(store.Team().Save(&o1)) store.Must(ss.Team().Save(&o1))
o2 := model.Team{} o2 := model.Team{}
o2.DisplayName = "DisplayName" o2.DisplayName = "DisplayName"
@@ -446,7 +447,7 @@ func TestGetAllTeamPageListing(t *testing.T) {
o2.Email = model.NewId() + "@nowhere.com" o2.Email = model.NewId() + "@nowhere.com"
o2.Type = model.TEAM_OPEN o2.Type = model.TEAM_OPEN
o2.AllowOpenInvite = false o2.AllowOpenInvite = false
Must(store.Team().Save(&o2)) store.Must(ss.Team().Save(&o2))
o3 := model.Team{} o3 := model.Team{}
o3.DisplayName = "DisplayName" o3.DisplayName = "DisplayName"
@@ -454,7 +455,7 @@ func TestGetAllTeamPageListing(t *testing.T) {
o3.Email = model.NewId() + "@nowhere.com" o3.Email = model.NewId() + "@nowhere.com"
o3.Type = model.TEAM_INVITE o3.Type = model.TEAM_INVITE
o3.AllowOpenInvite = true o3.AllowOpenInvite = true
Must(store.Team().Save(&o3)) store.Must(ss.Team().Save(&o3))
o4 := model.Team{} o4 := model.Team{}
o4.DisplayName = "DisplayName" o4.DisplayName = "DisplayName"
@@ -462,9 +463,9 @@ func TestGetAllTeamPageListing(t *testing.T) {
o4.Email = model.NewId() + "@nowhere.com" o4.Email = model.NewId() + "@nowhere.com"
o4.Type = model.TEAM_INVITE o4.Type = model.TEAM_INVITE
o4.AllowOpenInvite = false o4.AllowOpenInvite = false
Must(store.Team().Save(&o4)) store.Must(ss.Team().Save(&o4))
if r1 := <-store.Team().GetAllTeamPageListing(0, 10); r1.Err != nil { if r1 := <-ss.Team().GetAllTeamPageListing(0, 10); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
teams := r1.Data.([]*model.Team) teams := r1.Data.([]*model.Team)
@@ -486,9 +487,9 @@ func TestGetAllTeamPageListing(t *testing.T) {
o5.Email = model.NewId() + "@nowhere.com" o5.Email = model.NewId() + "@nowhere.com"
o5.Type = model.TEAM_OPEN o5.Type = model.TEAM_OPEN
o5.AllowOpenInvite = true o5.AllowOpenInvite = true
Must(store.Team().Save(&o5)) store.Must(ss.Team().Save(&o5))
if r1 := <-store.Team().GetAllTeamPageListing(0, 4); r1.Err != nil { if r1 := <-ss.Team().GetAllTeamPageListing(0, 4); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
teams := r1.Data.([]*model.Team) teams := r1.Data.([]*model.Team)
@@ -504,7 +505,7 @@ func TestGetAllTeamPageListing(t *testing.T) {
} }
} }
if r1 := <-store.Team().GetAllTeamPageListing(1, 1); r1.Err != nil { if r1 := <-ss.Team().GetAllTeamPageListing(1, 1); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
teams := r1.Data.([]*model.Team) teams := r1.Data.([]*model.Team)
@@ -522,7 +523,7 @@ func TestGetAllTeamPageListing(t *testing.T) {
} }
func TestDelete(t *testing.T) { func TestDelete(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -530,22 +531,22 @@ func TestDelete(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.AllowOpenInvite = true o1.AllowOpenInvite = true
Must(store.Team().Save(&o1)) store.Must(ss.Team().Save(&o1))
o2 := model.Team{} o2 := model.Team{}
o2.DisplayName = "DisplayName" o2.DisplayName = "DisplayName"
o2.Name = "zz" + model.NewId() + "b" o2.Name = "zz" + model.NewId() + "b"
o2.Email = model.NewId() + "@nowhere.com" o2.Email = model.NewId() + "@nowhere.com"
o2.Type = model.TEAM_OPEN o2.Type = model.TEAM_OPEN
Must(store.Team().Save(&o2)) store.Must(ss.Team().Save(&o2))
if r1 := <-store.Team().PermanentDelete(o1.Id); r1.Err != nil { if r1 := <-ss.Team().PermanentDelete(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
} }
func TestTeamCount(t *testing.T) { func TestTeamCount(t *testing.T) {
Setup() ss := Setup()
o1 := model.Team{} o1 := model.Team{}
o1.DisplayName = "DisplayName" o1.DisplayName = "DisplayName"
@@ -553,9 +554,9 @@ func TestTeamCount(t *testing.T) {
o1.Email = model.NewId() + "@nowhere.com" o1.Email = model.NewId() + "@nowhere.com"
o1.Type = model.TEAM_OPEN o1.Type = model.TEAM_OPEN
o1.AllowOpenInvite = true o1.AllowOpenInvite = true
Must(store.Team().Save(&o1)) store.Must(ss.Team().Save(&o1))
if r1 := <-store.Team().AnalyticsTeamCount(); r1.Err != nil { if r1 := <-ss.Team().AnalyticsTeamCount(); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(int64) == 0 { if r1.Data.(int64) == 0 {
@@ -565,7 +566,7 @@ func TestTeamCount(t *testing.T) {
} }
func TestTeamMembers(t *testing.T) { func TestTeamMembers(t *testing.T) {
Setup() ss := Setup()
teamId1 := model.NewId() teamId1 := model.NewId()
teamId2 := model.NewId() teamId2 := model.NewId()
@@ -574,14 +575,14 @@ func TestTeamMembers(t *testing.T) {
m2 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()} m2 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()}
m3 := &model.TeamMember{TeamId: teamId2, UserId: model.NewId()} m3 := &model.TeamMember{TeamId: teamId2, UserId: model.NewId()}
if r1 := <-store.Team().SaveMember(m1); r1.Err != nil { if r1 := <-ss.Team().SaveMember(m1); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
Must(store.Team().SaveMember(m2)) store.Must(ss.Team().SaveMember(m2))
Must(store.Team().SaveMember(m3)) store.Must(ss.Team().SaveMember(m3))
if r1 := <-store.Team().GetMembers(teamId1, 0, 100); r1.Err != nil { if r1 := <-ss.Team().GetMembers(teamId1, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -591,7 +592,7 @@ func TestTeamMembers(t *testing.T) {
} }
} }
if r1 := <-store.Team().GetMembers(teamId2, 0, 100); r1.Err != nil { if r1 := <-ss.Team().GetMembers(teamId2, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -606,7 +607,7 @@ func TestTeamMembers(t *testing.T) {
} }
} }
if r1 := <-store.Team().GetTeamsForUser(m1.UserId); r1.Err != nil { if r1 := <-ss.Team().GetTeamsForUser(m1.UserId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -621,11 +622,11 @@ func TestTeamMembers(t *testing.T) {
} }
} }
if r1 := <-store.Team().RemoveMember(teamId1, m1.UserId); r1.Err != nil { if r1 := <-ss.Team().RemoveMember(teamId1, m1.UserId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
if r1 := <-store.Team().GetMembers(teamId1, 0, 100); r1.Err != nil { if r1 := <-ss.Team().GetMembers(teamId1, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -640,13 +641,13 @@ func TestTeamMembers(t *testing.T) {
} }
} }
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
if r1 := <-store.Team().RemoveAllMembersByTeam(teamId1); r1.Err != nil { if r1 := <-ss.Team().RemoveAllMembersByTeam(teamId1); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
if r1 := <-store.Team().GetMembers(teamId1, 0, 100); r1.Err != nil { if r1 := <-ss.Team().GetMembers(teamId1, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -659,10 +660,10 @@ func TestTeamMembers(t *testing.T) {
uid := model.NewId() uid := model.NewId()
m4 := &model.TeamMember{TeamId: teamId1, UserId: uid} m4 := &model.TeamMember{TeamId: teamId1, UserId: uid}
m5 := &model.TeamMember{TeamId: teamId2, UserId: uid} m5 := &model.TeamMember{TeamId: teamId2, UserId: uid}
Must(store.Team().SaveMember(m4)) store.Must(ss.Team().SaveMember(m4))
Must(store.Team().SaveMember(m5)) store.Must(ss.Team().SaveMember(m5))
if r1 := <-store.Team().GetTeamsForUser(uid); r1.Err != nil { if r1 := <-ss.Team().GetTeamsForUser(uid); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -672,11 +673,11 @@ func TestTeamMembers(t *testing.T) {
} }
} }
if r1 := <-store.Team().RemoveAllMembersByUser(uid); r1.Err != nil { if r1 := <-ss.Team().RemoveAllMembersByUser(uid); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
if r1 := <-store.Team().GetTeamsForUser(m1.UserId); r1.Err != nil { if r1 := <-ss.Team().GetTeamsForUser(m1.UserId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.TeamMember) ms := r1.Data.([]*model.TeamMember)
@@ -688,7 +689,7 @@ func TestTeamMembers(t *testing.T) {
} }
func TestSaveTeamMemberMaxMembers(t *testing.T) { func TestSaveTeamMemberMaxMembers(t *testing.T) {
Setup() ss := Setup()
MaxUsersPerTeam := *utils.Cfg.TeamSettings.MaxUsersPerTeam MaxUsersPerTeam := *utils.Cfg.TeamSettings.MaxUsersPerTeam
defer func() { defer func() {
@@ -696,118 +697,118 @@ func TestSaveTeamMemberMaxMembers(t *testing.T) {
}() }()
*utils.Cfg.TeamSettings.MaxUsersPerTeam = 5 *utils.Cfg.TeamSettings.MaxUsersPerTeam = 5
team := Must(store.Team().Save(&model.Team{ team := store.Must(ss.Team().Save(&model.Team{
DisplayName: "DisplayName", DisplayName: "DisplayName",
Name: "z-z-z" + model.NewId() + "b", Name: "z-z-z" + model.NewId() + "b",
Type: model.TEAM_OPEN, Type: model.TEAM_OPEN,
})).(*model.Team) })).(*model.Team)
defer func() { defer func() {
<-store.Team().PermanentDelete(team.Id) <-ss.Team().PermanentDelete(team.Id)
}() }()
userIds := make([]string, *utils.Cfg.TeamSettings.MaxUsersPerTeam) userIds := make([]string, *utils.Cfg.TeamSettings.MaxUsersPerTeam)
for i := 0; i < *utils.Cfg.TeamSettings.MaxUsersPerTeam; i++ { for i := 0; i < *utils.Cfg.TeamSettings.MaxUsersPerTeam; i++ {
userIds[i] = Must(store.User().Save(&model.User{ userIds[i] = store.Must(ss.User().Save(&model.User{
Username: model.NewId(), Username: model.NewId(),
Email: model.NewId(), Email: model.NewId(),
})).(*model.User).Id })).(*model.User).Id
defer func(userId string) { defer func(userId string) {
<-store.User().PermanentDelete(userId) <-ss.User().PermanentDelete(userId)
}(userIds[i]) }(userIds[i])
Must(store.Team().SaveMember(&model.TeamMember{ store.Must(ss.Team().SaveMember(&model.TeamMember{
TeamId: team.Id, TeamId: team.Id,
UserId: userIds[i], UserId: userIds[i],
})) }))
defer func(userId string) { defer func(userId string) {
<-store.Team().RemoveMember(team.Id, userId) <-ss.Team().RemoveMember(team.Id, userId)
}(userIds[i]) }(userIds[i])
} }
if result := <-store.Team().GetTotalMemberCount(team.Id); result.Err != nil { if result := <-ss.Team().GetTotalMemberCount(team.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam { } else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam {
t.Fatalf("should start with 5 team members, had %v instead", count) t.Fatalf("should start with 5 team members, had %v instead", count)
} }
newUserId := Must(store.User().Save(&model.User{ newUserId := store.Must(ss.User().Save(&model.User{
Username: model.NewId(), Username: model.NewId(),
Email: model.NewId(), Email: model.NewId(),
})).(*model.User).Id })).(*model.User).Id
defer func() { defer func() {
<-store.User().PermanentDelete(newUserId) <-ss.User().PermanentDelete(newUserId)
}() }()
if result := <-store.Team().SaveMember(&model.TeamMember{ if result := <-ss.Team().SaveMember(&model.TeamMember{
TeamId: team.Id, TeamId: team.Id,
UserId: newUserId, UserId: newUserId,
}); result.Err == nil { }); result.Err == nil {
t.Fatal("shouldn't be able to save member when at maximum members per team") t.Fatal("shouldn't be able to save member when at maximum members per team")
} }
if result := <-store.Team().GetTotalMemberCount(team.Id); result.Err != nil { if result := <-ss.Team().GetTotalMemberCount(team.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam { } else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam {
t.Fatalf("should still have 5 team members, had %v instead", count) t.Fatalf("should still have 5 team members, had %v instead", count)
} }
// Leaving the team from the UI sets DeleteAt instead of using TeamStore.RemoveMember // Leaving the team from the UI sets DeleteAt instead of using TeamStore.RemoveMember
Must(store.Team().UpdateMember(&model.TeamMember{ store.Must(ss.Team().UpdateMember(&model.TeamMember{
TeamId: team.Id, TeamId: team.Id,
UserId: userIds[0], UserId: userIds[0],
DeleteAt: 1234, DeleteAt: 1234,
})) }))
if result := <-store.Team().GetTotalMemberCount(team.Id); result.Err != nil { if result := <-ss.Team().GetTotalMemberCount(team.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam-1 { } else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam-1 {
t.Fatalf("should now only have 4 team members, had %v instead", count) t.Fatalf("should now only have 4 team members, had %v instead", count)
} }
if result := <-store.Team().SaveMember(&model.TeamMember{TeamId: team.Id, UserId: newUserId}); result.Err != nil { if result := <-ss.Team().SaveMember(&model.TeamMember{TeamId: team.Id, UserId: newUserId}); result.Err != nil {
t.Fatal("should've been able to save new member after deleting one", result.Err) t.Fatal("should've been able to save new member after deleting one", result.Err)
} else { } else {
defer func(userId string) { defer func(userId string) {
<-store.Team().RemoveMember(team.Id, userId) <-ss.Team().RemoveMember(team.Id, userId)
}(newUserId) }(newUserId)
} }
if result := <-store.Team().GetTotalMemberCount(team.Id); result.Err != nil { if result := <-ss.Team().GetTotalMemberCount(team.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam { } else if count := result.Data.(int64); int(count) != *utils.Cfg.TeamSettings.MaxUsersPerTeam {
t.Fatalf("should have 5 team members again, had %v instead", count) t.Fatalf("should have 5 team members again, had %v instead", count)
} }
// Deactivating a user should make them stop counting against max members // Deactivating a user should make them stop counting against max members
user2 := Must(store.User().Get(userIds[1])).(*model.User) user2 := store.Must(ss.User().Get(userIds[1])).(*model.User)
user2.DeleteAt = 1234 user2.DeleteAt = 1234
Must(store.User().Update(user2, true)) store.Must(ss.User().Update(user2, true))
newUserId2 := Must(store.User().Save(&model.User{ newUserId2 := store.Must(ss.User().Save(&model.User{
Username: model.NewId(), Username: model.NewId(),
Email: model.NewId(), Email: model.NewId(),
})).(*model.User).Id })).(*model.User).Id
if result := <-store.Team().SaveMember(&model.TeamMember{TeamId: team.Id, UserId: newUserId2}); result.Err != nil { if result := <-ss.Team().SaveMember(&model.TeamMember{TeamId: team.Id, UserId: newUserId2}); result.Err != nil {
t.Fatal("should've been able to save new member after deleting one", result.Err) t.Fatal("should've been able to save new member after deleting one", result.Err)
} else { } else {
defer func(userId string) { defer func(userId string) {
<-store.Team().RemoveMember(team.Id, userId) <-ss.Team().RemoveMember(team.Id, userId)
}(newUserId2) }(newUserId2)
} }
} }
func TestGetTeamMember(t *testing.T) { func TestGetTeamMember(t *testing.T) {
Setup() ss := Setup()
teamId1 := model.NewId() teamId1 := model.NewId()
m1 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()} m1 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()}
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
if r := <-store.Team().GetMember(m1.TeamId, m1.UserId); r.Err != nil { if r := <-ss.Team().GetMember(m1.TeamId, m1.UserId); r.Err != nil {
t.Fatal(r.Err) t.Fatal(r.Err)
} else { } else {
rm1 := r.Data.(*model.TeamMember) rm1 := r.Data.(*model.TeamMember)
@@ -821,24 +822,24 @@ func TestGetTeamMember(t *testing.T) {
} }
} }
if r := <-store.Team().GetMember(m1.TeamId, ""); r.Err == nil { if r := <-ss.Team().GetMember(m1.TeamId, ""); r.Err == nil {
t.Fatal("empty user id - should have failed") t.Fatal("empty user id - should have failed")
} }
if r := <-store.Team().GetMember("", m1.UserId); r.Err == nil { if r := <-ss.Team().GetMember("", m1.UserId); r.Err == nil {
t.Fatal("empty team id - should have failed") t.Fatal("empty team id - should have failed")
} }
} }
func TestGetTeamMembersByIds(t *testing.T) { func TestGetTeamMembersByIds(t *testing.T) {
Setup() ss := Setup()
teamId1 := model.NewId() teamId1 := model.NewId()
m1 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()} m1 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()}
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
if r := <-store.Team().GetMembersByIds(m1.TeamId, []string{m1.UserId}); r.Err != nil { if r := <-ss.Team().GetMembersByIds(m1.TeamId, []string{m1.UserId}); r.Err != nil {
t.Fatal(r.Err) t.Fatal(r.Err)
} else { } else {
rm1 := r.Data.([]*model.TeamMember)[0] rm1 := r.Data.([]*model.TeamMember)[0]
@@ -853,9 +854,9 @@ func TestGetTeamMembersByIds(t *testing.T) {
} }
m2 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()} m2 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()}
Must(store.Team().SaveMember(m2)) store.Must(ss.Team().SaveMember(m2))
if r := <-store.Team().GetMembersByIds(m1.TeamId, []string{m1.UserId, m2.UserId, model.NewId()}); r.Err != nil { if r := <-ss.Team().GetMembersByIds(m1.TeamId, []string{m1.UserId, m2.UserId, model.NewId()}); r.Err != nil {
t.Fatal(r.Err) t.Fatal(r.Err)
} else { } else {
rm := r.Data.([]*model.TeamMember) rm := r.Data.([]*model.TeamMember)
@@ -865,31 +866,31 @@ func TestGetTeamMembersByIds(t *testing.T) {
} }
} }
if r := <-store.Team().GetMembersByIds(m1.TeamId, []string{}); r.Err == nil { if r := <-ss.Team().GetMembersByIds(m1.TeamId, []string{}); r.Err == nil {
t.Fatal("empty user ids - should have failed") t.Fatal("empty user ids - should have failed")
} }
} }
func TestTeamStoreMemberCount(t *testing.T) { func TestTeamStoreMemberCount(t *testing.T) {
Setup() ss := Setup()
u1 := &model.User{} u1 := &model.User{}
u1.Email = model.NewId() u1.Email = model.NewId()
Must(store.User().Save(u1)) store.Must(ss.User().Save(u1))
u2 := &model.User{} u2 := &model.User{}
u2.Email = model.NewId() u2.Email = model.NewId()
u2.DeleteAt = 1 u2.DeleteAt = 1
Must(store.User().Save(u2)) store.Must(ss.User().Save(u2))
teamId1 := model.NewId() teamId1 := model.NewId()
m1 := &model.TeamMember{TeamId: teamId1, UserId: u1.Id} m1 := &model.TeamMember{TeamId: teamId1, UserId: u1.Id}
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
m2 := &model.TeamMember{TeamId: teamId1, UserId: u2.Id} m2 := &model.TeamMember{TeamId: teamId1, UserId: u2.Id}
Must(store.Team().SaveMember(m2)) store.Must(ss.Team().SaveMember(m2))
if result := <-store.Team().GetTotalMemberCount(teamId1); result.Err != nil { if result := <-ss.Team().GetTotalMemberCount(teamId1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if result.Data.(int64) != 2 { if result.Data.(int64) != 2 {
@@ -897,7 +898,7 @@ func TestTeamStoreMemberCount(t *testing.T) {
} }
} }
if result := <-store.Team().GetActiveMemberCount(teamId1); result.Err != nil { if result := <-ss.Team().GetActiveMemberCount(teamId1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if result.Data.(int64) != 1 { if result.Data.(int64) != 1 {
@@ -906,9 +907,9 @@ func TestTeamStoreMemberCount(t *testing.T) {
} }
m3 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()} m3 := &model.TeamMember{TeamId: teamId1, UserId: model.NewId()}
Must(store.Team().SaveMember(m3)) store.Must(ss.Team().SaveMember(m3))
if result := <-store.Team().GetTotalMemberCount(teamId1); result.Err != nil { if result := <-ss.Team().GetTotalMemberCount(teamId1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if result.Data.(int64) != 2 { if result.Data.(int64) != 2 {
@@ -916,7 +917,7 @@ func TestTeamStoreMemberCount(t *testing.T) {
} }
} }
if result := <-store.Team().GetActiveMemberCount(teamId1); result.Err != nil { if result := <-ss.Team().GetActiveMemberCount(teamId1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if result.Data.(int64) != 1 { if result.Data.(int64) != 1 {
@@ -926,7 +927,7 @@ func TestTeamStoreMemberCount(t *testing.T) {
} }
func TestGetChannelUnreadsForAllTeams(t *testing.T) { func TestGetChannelUnreadsForAllTeams(t *testing.T) {
Setup() ss := Setup()
teamId1 := model.NewId() teamId1 := model.NewId()
teamId2 := model.NewId() teamId2 := model.NewId()
@@ -934,20 +935,20 @@ func TestGetChannelUnreadsForAllTeams(t *testing.T) {
uid := model.NewId() uid := model.NewId()
m1 := &model.TeamMember{TeamId: teamId1, UserId: uid} m1 := &model.TeamMember{TeamId: teamId1, UserId: uid}
m2 := &model.TeamMember{TeamId: teamId2, UserId: uid} m2 := &model.TeamMember{TeamId: teamId2, UserId: uid}
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
Must(store.Team().SaveMember(m2)) store.Must(ss.Team().SaveMember(m2))
c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100}
Must(store.Channel().Save(c1)) store.Must(ss.Channel().Save(c1))
c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100}
Must(store.Channel().Save(c2)) store.Must(ss.Channel().Save(c2))
cm1 := &model.ChannelMember{ChannelId: c1.Id, UserId: m1.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90} cm1 := &model.ChannelMember{ChannelId: c1.Id, UserId: m1.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90}
Must(store.Channel().SaveMember(cm1)) store.Must(ss.Channel().SaveMember(cm1))
cm2 := &model.ChannelMember{ChannelId: c2.Id, UserId: m2.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90} cm2 := &model.ChannelMember{ChannelId: c2.Id, UserId: m2.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90}
Must(store.Channel().SaveMember(cm2)) store.Must(ss.Channel().SaveMember(cm2))
if r1 := <-store.Team().GetChannelUnreadsForAllTeams("", uid); r1.Err != nil { if r1 := <-ss.Team().GetChannelUnreadsForAllTeams("", uid); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.ChannelUnread) ms := r1.Data.([]*model.ChannelUnread)
@@ -967,7 +968,7 @@ func TestGetChannelUnreadsForAllTeams(t *testing.T) {
} }
} }
if r2 := <-store.Team().GetChannelUnreadsForAllTeams(teamId1, uid); r2.Err != nil { if r2 := <-ss.Team().GetChannelUnreadsForAllTeams(teamId1, uid); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} else { } else {
ms := r2.Data.([]*model.ChannelUnread) ms := r2.Data.([]*model.ChannelUnread)
@@ -988,31 +989,31 @@ func TestGetChannelUnreadsForAllTeams(t *testing.T) {
} }
} }
if r1 := <-store.Team().RemoveAllMembersByUser(uid); r1.Err != nil { if r1 := <-ss.Team().RemoveAllMembersByUser(uid); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} }
} }
func TestGetChannelUnreadsForTeam(t *testing.T) { func TestGetChannelUnreadsForTeam(t *testing.T) {
Setup() ss := Setup()
teamId1 := model.NewId() teamId1 := model.NewId()
uid := model.NewId() uid := model.NewId()
m1 := &model.TeamMember{TeamId: teamId1, UserId: uid} m1 := &model.TeamMember{TeamId: teamId1, UserId: uid}
Must(store.Team().SaveMember(m1)) store.Must(ss.Team().SaveMember(m1))
c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100}
Must(store.Channel().Save(c1)) store.Must(ss.Channel().Save(c1))
c2 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} c2 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100}
Must(store.Channel().Save(c2)) store.Must(ss.Channel().Save(c2))
cm1 := &model.ChannelMember{ChannelId: c1.Id, UserId: m1.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90} cm1 := &model.ChannelMember{ChannelId: c1.Id, UserId: m1.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90}
Must(store.Channel().SaveMember(cm1)) store.Must(ss.Channel().SaveMember(cm1))
cm2 := &model.ChannelMember{ChannelId: c2.Id, UserId: m1.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90} cm2 := &model.ChannelMember{ChannelId: c2.Id, UserId: m1.UserId, NotifyProps: model.GetDefaultChannelNotifyProps(), MsgCount: 90}
Must(store.Channel().SaveMember(cm2)) store.Must(ss.Channel().SaveMember(cm2))
if r1 := <-store.Team().GetChannelUnreadsForTeam(m1.TeamId, m1.UserId); r1.Err != nil { if r1 := <-ss.Team().GetChannelUnreadsForTeam(m1.TeamId, m1.UserId); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
ms := r1.Data.([]*model.ChannelUnread) ms := r1.Data.([]*model.ChannelUnread)

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

@@ -1,7 +1,7 @@
// Copyright (c) 2017 Mattermost, Inc. All Rights Reserved. // Copyright (c) 2017 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -10,13 +10,14 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
type SqlTokenStore struct { type SqlTokenStore struct {
SqlStore SqlStore
} }
func NewSqlTokenStore(sqlStore SqlStore) TokenStore { func NewSqlTokenStore(sqlStore SqlStore) store.TokenStore {
s := &SqlTokenStore{sqlStore} s := &SqlTokenStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -32,12 +33,12 @@ func NewSqlTokenStore(sqlStore SqlStore) TokenStore {
func (s SqlTokenStore) CreateIndexesIfNotExists() { func (s SqlTokenStore) CreateIndexesIfNotExists() {
} }
func (s SqlTokenStore) Save(token *model.Token) StoreChannel { func (s SqlTokenStore) Save(token *model.Token) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if result.Err = token.IsValid(); result.Err != nil { if result.Err = token.IsValid(); result.Err != nil {
storeChannel <- result storeChannel <- result
@@ -56,12 +57,12 @@ func (s SqlTokenStore) Save(token *model.Token) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTokenStore) Delete(token string) StoreChannel { func (s SqlTokenStore) Delete(token string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := s.GetMaster().Exec("DELETE FROM Tokens WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil { if _, err := s.GetMaster().Exec("DELETE FROM Tokens WHERE Token = :Token", map[string]interface{}{"Token": token}); err != nil {
result.Err = model.NewAppError("SqlTokenStore.Delete", "store.sql_recover.delete.app_error", nil, "", http.StatusInternalServerError) result.Err = model.NewAppError("SqlTokenStore.Delete", "store.sql_recover.delete.app_error", nil, "", http.StatusInternalServerError)
@@ -74,12 +75,12 @@ func (s SqlTokenStore) Delete(token string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlTokenStore) GetByToken(tokenString string) StoreChannel { func (s SqlTokenStore) GetByToken(tokenString string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
token := model.Token{} token := model.Token{}

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

@@ -1,7 +1,7 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"os" "os"

41
store/sqlstore/upgrade_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,41 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestStoreUpgrade(t *testing.T) {
ss := Setup()
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), VERSION_3_0_0)
UpgradeDatabase(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore))
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), "")
UpgradeDatabase(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore))
}
func TestSaveSchemaVersion(t *testing.T) {
ss := Setup()
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), VERSION_3_0_0)
if result := <-ss.System().Get(); result.Err != nil {
t.Fatal(result.Err)
} else {
props := result.Data.(model.StringMap)
if props["Version"] != VERSION_3_0_0 {
t.Fatal("version not updated")
}
}
if ss.(*store.LayeredStore).DatabaseLayer.(SqlStore).GetCurrentSchemaVersion() != VERSION_3_0_0 {
t.Fatal("version not updated")
}
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), model.CurrentVersion)
}

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

@@ -1,7 +1,7 @@
// Copyright (c) 2017 Mattermost, Inc. All Rights Reserved. // Copyright (c) 2017 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -9,6 +9,7 @@ import (
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -16,7 +17,7 @@ type SqlUserAccessTokenStore struct {
SqlStore SqlStore
} }
func NewSqlUserAccessTokenStore(sqlStore SqlStore) UserAccessTokenStore { func NewSqlUserAccessTokenStore(sqlStore SqlStore) store.UserAccessTokenStore {
s := &SqlUserAccessTokenStore{sqlStore} s := &SqlUserAccessTokenStore{sqlStore}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
@@ -35,12 +36,12 @@ func (s SqlUserAccessTokenStore) CreateIndexesIfNotExists() {
s.CreateIndexIfNotExists("idx_user_access_tokens_user_id", "UserAccessTokens", "UserId") s.CreateIndexIfNotExists("idx_user_access_tokens_user_id", "UserAccessTokens", "UserId")
} }
func (s SqlUserAccessTokenStore) Save(token *model.UserAccessToken) StoreChannel { func (s SqlUserAccessTokenStore) Save(token *model.UserAccessToken) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
token.PreSave() token.PreSave()
@@ -63,12 +64,12 @@ func (s SqlUserAccessTokenStore) Save(token *model.UserAccessToken) StoreChannel
return storeChannel return storeChannel
} }
func (s SqlUserAccessTokenStore) Delete(tokenId string) StoreChannel { func (s SqlUserAccessTokenStore) Delete(tokenId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
transaction, err := s.GetMaster().Begin() transaction, err := s.GetMaster().Begin()
if err != nil { if err != nil {
@@ -97,8 +98,8 @@ func (s SqlUserAccessTokenStore) Delete(tokenId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlUserAccessTokenStore) deleteSessionsAndTokensById(transaction *gorp.Transaction, tokenId string) StoreResult { func (s SqlUserAccessTokenStore) deleteSessionsAndTokensById(transaction *gorp.Transaction, tokenId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
query := "" query := ""
if *utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES { if *utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
@@ -115,8 +116,8 @@ func (s SqlUserAccessTokenStore) deleteSessionsAndTokensById(transaction *gorp.T
return s.deleteTokensById(transaction, tokenId) return s.deleteTokensById(transaction, tokenId)
} }
func (s SqlUserAccessTokenStore) deleteTokensById(transaction *gorp.Transaction, tokenId string) StoreResult { func (s SqlUserAccessTokenStore) deleteTokensById(transaction *gorp.Transaction, tokenId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if _, err := transaction.Exec("DELETE FROM UserAccessTokens WHERE Id = :Id", map[string]interface{}{"Id": tokenId}); err != nil { if _, err := transaction.Exec("DELETE FROM UserAccessTokens WHERE Id = :Id", map[string]interface{}{"Id": tokenId}); err != nil {
result.Err = model.NewAppError("SqlUserAccessTokenStore.deleteTokensById", "store.sql_user_access_token.delete.app_error", nil, "", http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserAccessTokenStore.deleteTokensById", "store.sql_user_access_token.delete.app_error", nil, "", http.StatusInternalServerError)
@@ -125,12 +126,12 @@ func (s SqlUserAccessTokenStore) deleteTokensById(transaction *gorp.Transaction,
return result return result
} }
func (s SqlUserAccessTokenStore) DeleteAllForUser(userId string) StoreChannel { func (s SqlUserAccessTokenStore) DeleteAllForUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
transaction, err := s.GetMaster().Begin() transaction, err := s.GetMaster().Begin()
if err != nil { if err != nil {
@@ -159,8 +160,8 @@ func (s SqlUserAccessTokenStore) DeleteAllForUser(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlUserAccessTokenStore) deleteSessionsandTokensByUser(transaction *gorp.Transaction, userId string) StoreResult { func (s SqlUserAccessTokenStore) deleteSessionsandTokensByUser(transaction *gorp.Transaction, userId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
query := "" query := ""
if *utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES { if *utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
@@ -177,8 +178,8 @@ func (s SqlUserAccessTokenStore) deleteSessionsandTokensByUser(transaction *gorp
return s.deleteTokensByUser(transaction, userId) return s.deleteTokensByUser(transaction, userId)
} }
func (s SqlUserAccessTokenStore) deleteTokensByUser(transaction *gorp.Transaction, userId string) StoreResult { func (s SqlUserAccessTokenStore) deleteTokensByUser(transaction *gorp.Transaction, userId string) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
if _, err := transaction.Exec("DELETE FROM UserAccessTokens WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}); err != nil { if _, err := transaction.Exec("DELETE FROM UserAccessTokens WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlUserAccessTokenStore.deleteTokensByUser", "store.sql_user_access_token.delete.app_error", nil, "", http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserAccessTokenStore.deleteTokensByUser", "store.sql_user_access_token.delete.app_error", nil, "", http.StatusInternalServerError)
@@ -187,12 +188,12 @@ func (s SqlUserAccessTokenStore) deleteTokensByUser(transaction *gorp.Transactio
return result return result
} }
func (s SqlUserAccessTokenStore) Get(tokenId string) StoreChannel { func (s SqlUserAccessTokenStore) Get(tokenId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
token := model.UserAccessToken{} token := model.UserAccessToken{}
@@ -213,12 +214,12 @@ func (s SqlUserAccessTokenStore) Get(tokenId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlUserAccessTokenStore) GetByToken(tokenString string) StoreChannel { func (s SqlUserAccessTokenStore) GetByToken(tokenString string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
token := model.UserAccessToken{} token := model.UserAccessToken{}
@@ -239,12 +240,12 @@ func (s SqlUserAccessTokenStore) GetByToken(tokenString string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlUserAccessTokenStore) GetByUser(userId string, offset, limit int) StoreChannel { func (s SqlUserAccessTokenStore) GetByUser(userId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
tokens := []*model.UserAccessToken{} tokens := []*model.UserAccessToken{}

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

@@ -1,16 +1,17 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
) )
func TestUserAccessTokenSaveGetDelete(t *testing.T) { func TestUserAccessTokenSaveGetDelete(t *testing.T) {
Setup() ss := Setup()
uat := &model.UserAccessToken{ uat := &model.UserAccessToken{
Token: model.NewId(), Token: model.NewId(),
@@ -22,43 +23,43 @@ func TestUserAccessTokenSaveGetDelete(t *testing.T) {
s1.UserId = uat.UserId s1.UserId = uat.UserId
s1.Token = uat.Token s1.Token = uat.Token
Must(store.Session().Save(&s1)) store.Must(ss.Session().Save(&s1))
if result := <-store.UserAccessToken().Save(uat); result.Err != nil { if result := <-ss.UserAccessToken().Save(uat); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.UserAccessToken().Get(uat.Id); result.Err != nil { if result := <-ss.UserAccessToken().Get(uat.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token { } else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token {
t.Fatal("received incorrect token after save") t.Fatal("received incorrect token after save")
} }
if result := <-store.UserAccessToken().GetByToken(uat.Token); result.Err != nil { if result := <-ss.UserAccessToken().GetByToken(uat.Token); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token { } else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token {
t.Fatal("received incorrect token after save") t.Fatal("received incorrect token after save")
} }
if result := <-store.UserAccessToken().GetByToken("notarealtoken"); result.Err == nil { if result := <-ss.UserAccessToken().GetByToken("notarealtoken"); result.Err == nil {
t.Fatal("should have failed on bad token") t.Fatal("should have failed on bad token")
} }
if result := <-store.UserAccessToken().GetByUser(uat.UserId, 0, 100); result.Err != nil { if result := <-ss.UserAccessToken().GetByUser(uat.UserId, 0, 100); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else if received := result.Data.([]*model.UserAccessToken); len(received) != 1 { } else if received := result.Data.([]*model.UserAccessToken); len(received) != 1 {
t.Fatal("received incorrect number of tokens after save") t.Fatal("received incorrect number of tokens after save")
} }
if result := <-store.UserAccessToken().Delete(uat.Id); result.Err != nil { if result := <-ss.UserAccessToken().Delete(uat.Id); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if err := (<-store.Session().Get(s1.Token)).Err; err == nil { if err := (<-ss.Session().Get(s1.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted") t.Fatal("should error - session should be deleted")
} }
if err := (<-store.UserAccessToken().GetByToken(s1.Token)).Err; err == nil { if err := (<-ss.UserAccessToken().GetByToken(s1.Token)).Err; err == nil {
t.Fatal("should error - access token should be deleted") t.Fatal("should error - access token should be deleted")
} }
@@ -66,21 +67,21 @@ func TestUserAccessTokenSaveGetDelete(t *testing.T) {
s2.UserId = uat.UserId s2.UserId = uat.UserId
s2.Token = uat.Token s2.Token = uat.Token
Must(store.Session().Save(&s2)) store.Must(ss.Session().Save(&s2))
if result := <-store.UserAccessToken().Save(uat); result.Err != nil { if result := <-ss.UserAccessToken().Save(uat); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if result := <-store.UserAccessToken().DeleteAllForUser(uat.UserId); result.Err != nil { if result := <-ss.UserAccessToken().DeleteAllForUser(uat.UserId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} }
if err := (<-store.Session().Get(s2.Token)).Err; err == nil { if err := (<-ss.Session().Get(s2.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted") t.Fatal("should error - session should be deleted")
} }
if err := (<-store.UserAccessToken().GetByToken(s2.Token)).Err; err == nil { if err := (<-ss.UserAccessToken().GetByToken(s2.Token)).Err; err == nil {
t.Fatal("should error - access token should be deleted") t.Fatal("should error - access token should be deleted")
} }
} }

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"database/sql" "database/sql"
@@ -12,24 +12,19 @@ import (
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
const ( const (
MISSING_ACCOUNT_ERROR = "store.sql_user.missing_account.const" PROFILES_IN_CHANNEL_CACHE_SIZE = model.CHANNEL_CACHE_SIZE
MISSING_AUTH_ACCOUNT_ERROR = "store.sql_user.get_by_auth.missing_account.app_error" PROFILES_IN_CHANNEL_CACHE_SEC = 900 // 15 mins
PROFILES_IN_CHANNEL_CACHE_SIZE = model.CHANNEL_CACHE_SIZE PROFILE_BY_IDS_CACHE_SIZE = model.SESSION_CACHE_SIZE
PROFILES_IN_CHANNEL_CACHE_SEC = 900 // 15 mins PROFILE_BY_IDS_CACHE_SEC = 900 // 15 mins
PROFILE_BY_IDS_CACHE_SIZE = model.SESSION_CACHE_SIZE USER_SEARCH_TYPE_NAMES_NO_FULL_NAME = "Username, Nickname"
PROFILE_BY_IDS_CACHE_SEC = 900 // 15 mins USER_SEARCH_TYPE_NAMES = "Username, FirstName, LastName, Nickname"
USER_SEARCH_OPTION_NAMES_ONLY = "names_only" USER_SEARCH_TYPE_ALL_NO_FULL_NAME = "Username, Nickname, Email"
USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME = "names_only_no_full_name" USER_SEARCH_TYPE_ALL = "Username, FirstName, LastName, Nickname, Email"
USER_SEARCH_OPTION_ALL_NO_FULL_NAME = "all_no_full_name"
USER_SEARCH_OPTION_ALLOW_INACTIVE = "allow_inactive"
USER_SEARCH_TYPE_NAMES_NO_FULL_NAME = "Username, Nickname"
USER_SEARCH_TYPE_NAMES = "Username, FirstName, LastName, Nickname"
USER_SEARCH_TYPE_ALL_NO_FULL_NAME = "Username, Nickname, Email"
USER_SEARCH_TYPE_ALL = "Username, FirstName, LastName, Nickname, Email"
) )
type SqlUserStore struct { type SqlUserStore struct {
@@ -49,7 +44,7 @@ func (us SqlUserStore) InvalidatProfileCacheForUser(userId string) {
profileByIdsCache.Remove(userId) profileByIdsCache.Remove(userId)
} }
func NewSqlUserStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) UserStore { func NewSqlUserStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.UserStore {
us := &SqlUserStore{ us := &SqlUserStore{
SqlStore: sqlStore, SqlStore: sqlStore,
metrics: metrics, metrics: metrics,
@@ -89,12 +84,12 @@ func (us SqlUserStore) CreateIndexesIfNotExists() {
us.CreateFullTextIndexIfNotExists("idx_users_names_no_full_name_txt", "Users", USER_SEARCH_TYPE_NAMES_NO_FULL_NAME) us.CreateFullTextIndexIfNotExists("idx_users_names_no_full_name_txt", "Users", USER_SEARCH_TYPE_NAMES_NO_FULL_NAME)
} }
func (us SqlUserStore) Save(user *model.User) StoreChannel { func (us SqlUserStore) Save(user *model.User) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(user.Id) > 0 { if len(user.Id) > 0 {
result.Err = model.NewAppError("SqlUserStore.Save", "store.sql_user.save.existing.app_error", nil, "user_id="+user.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlUserStore.Save", "store.sql_user.save.existing.app_error", nil, "user_id="+user.Id, http.StatusBadRequest)
@@ -129,11 +124,11 @@ func (us SqlUserStore) Save(user *model.User) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) Update(user *model.User, trustedUpdateData bool) StoreChannel { func (us SqlUserStore) Update(user *model.User, trustedUpdateData bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
user.PreUpdate() user.PreUpdate()
@@ -209,11 +204,11 @@ func (us SqlUserStore) Update(user *model.User, trustedUpdateData bool) StoreCha
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdateLastPictureUpdate(userId string) StoreChannel { func (us SqlUserStore) UpdateLastPictureUpdate(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
curTime := model.GetMillis() curTime := model.GetMillis()
@@ -230,11 +225,11 @@ func (us SqlUserStore) UpdateLastPictureUpdate(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdateUpdateAt(userId string) StoreChannel { func (us SqlUserStore) UpdateUpdateAt(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
curTime := model.GetMillis() curTime := model.GetMillis()
@@ -251,12 +246,12 @@ func (us SqlUserStore) UpdateUpdateAt(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdatePassword(userId, hashedPassword string) StoreChannel { func (us SqlUserStore) UpdatePassword(userId, hashedPassword string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
updateAt := model.GetMillis() updateAt := model.GetMillis()
@@ -273,11 +268,11 @@ func (us SqlUserStore) UpdatePassword(userId, hashedPassword string) StoreChanne
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdateFailedPasswordAttempts(userId string, attempts int) StoreChannel { func (us SqlUserStore) UpdateFailedPasswordAttempts(userId string, attempts int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := us.GetMaster().Exec("UPDATE Users SET FailedAttempts = :FailedAttempts WHERE Id = :UserId", map[string]interface{}{"FailedAttempts": attempts, "UserId": userId}); err != nil { if _, err := us.GetMaster().Exec("UPDATE Users SET FailedAttempts = :FailedAttempts WHERE Id = :UserId", map[string]interface{}{"FailedAttempts": attempts, "UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlUserStore.UpdateFailedPasswordAttempts", "store.sql_user.update_failed_pwd_attempts.app_error", nil, "user_id="+userId, http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.UpdateFailedPasswordAttempts", "store.sql_user.update_failed_pwd_attempts.app_error", nil, "user_id="+userId, http.StatusInternalServerError)
@@ -292,12 +287,12 @@ func (us SqlUserStore) UpdateFailedPasswordAttempts(userId string, attempts int)
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdateAuthData(userId string, service string, authData *string, email string, resetMfa bool) StoreChannel { func (us SqlUserStore) UpdateAuthData(userId string, service string, authData *string, email string, resetMfa bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
email = strings.ToLower(email) email = strings.ToLower(email)
@@ -341,12 +336,12 @@ func (us SqlUserStore) UpdateAuthData(userId string, service string, authData *s
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdateMfaSecret(userId, secret string) StoreChannel { func (us SqlUserStore) UpdateMfaSecret(userId, secret string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
updateAt := model.GetMillis() updateAt := model.GetMillis()
@@ -363,12 +358,12 @@ func (us SqlUserStore) UpdateMfaSecret(userId, secret string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) UpdateMfaActive(userId string, active bool) StoreChannel { func (us SqlUserStore) UpdateMfaActive(userId string, active bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
updateAt := model.GetMillis() updateAt := model.GetMillis()
@@ -385,17 +380,17 @@ func (us SqlUserStore) UpdateMfaActive(userId string, active bool) StoreChannel
return storeChannel return storeChannel
} }
func (us SqlUserStore) Get(id string) StoreChannel { func (us SqlUserStore) Get(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if obj, err := us.GetReplica().Get(model.User{}, id); err != nil { if obj, err := us.GetReplica().Get(model.User{}, id); err != nil {
result.Err = model.NewAppError("SqlUserStore.Get", "store.sql_user.get.app_error", nil, "user_id="+id+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.Get", "store.sql_user.get.app_error", nil, "user_id="+id+", "+err.Error(), http.StatusInternalServerError)
} else if obj == nil { } else if obj == nil {
result.Err = model.NewAppError("SqlUserStore.Get", MISSING_ACCOUNT_ERROR, nil, "user_id="+id, http.StatusNotFound) result.Err = model.NewAppError("SqlUserStore.Get", store.MISSING_ACCOUNT_ERROR, nil, "user_id="+id, http.StatusNotFound)
} else { } else {
result.Data = obj.(*model.User) result.Data = obj.(*model.User)
} }
@@ -408,12 +403,12 @@ func (us SqlUserStore) Get(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetAll() StoreChannel { func (us SqlUserStore) GetAll() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.User var data []*model.User
if _, err := us.GetReplica().Select(&data, "SELECT * FROM Users"); err != nil { if _, err := us.GetReplica().Select(&data, "SELECT * FROM Users"); err != nil {
@@ -430,11 +425,11 @@ func (us SqlUserStore) GetAll() StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlUserStore) GetEtagForAllProfiles() StoreChannel { func (s SqlUserStore) GetEtagForAllProfiles() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
updateAt, err := s.GetReplica().SelectInt("SELECT UpdateAt FROM Users ORDER BY UpdateAt DESC LIMIT 1") updateAt, err := s.GetReplica().SelectInt("SELECT UpdateAt FROM Users ORDER BY UpdateAt DESC LIMIT 1")
if err != nil { if err != nil {
@@ -450,12 +445,12 @@ func (s SqlUserStore) GetEtagForAllProfiles() StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetAllProfiles(offset int, limit int) StoreChannel { func (us SqlUserStore) GetAllProfiles(offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -477,11 +472,11 @@ func (us SqlUserStore) GetAllProfiles(offset int, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlUserStore) GetEtagForProfiles(teamId string) StoreChannel { func (s SqlUserStore) GetEtagForProfiles(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
updateAt, err := s.GetReplica().SelectInt("SELECT UpdateAt FROM Users, TeamMembers WHERE TeamMembers.TeamId = :TeamId AND Users.Id = TeamMembers.UserId ORDER BY UpdateAt DESC LIMIT 1", map[string]interface{}{"TeamId": teamId}) updateAt, err := s.GetReplica().SelectInt("SELECT UpdateAt FROM Users, TeamMembers WHERE TeamMembers.TeamId = :TeamId AND Users.Id = TeamMembers.UserId ORDER BY UpdateAt DESC LIMIT 1", map[string]interface{}{"TeamId": teamId})
if err != nil { if err != nil {
@@ -497,12 +492,12 @@ func (s SqlUserStore) GetEtagForProfiles(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetProfiles(teamId string, offset int, limit int) StoreChannel { func (us SqlUserStore) GetProfiles(teamId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -541,12 +536,12 @@ func (us SqlUserStore) InvalidateProfilesInChannelCache(channelId string) {
profilesInChannelCache.Remove(channelId) profilesInChannelCache.Remove(channelId)
} }
func (us SqlUserStore) GetProfilesInChannel(channelId string, offset int, limit int) StoreChannel { func (us SqlUserStore) GetProfilesInChannel(channelId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -570,12 +565,12 @@ func (us SqlUserStore) GetProfilesInChannel(channelId string, offset int, limit
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetAllProfilesInChannel(channelId string, allowFromCache bool) StoreChannel { func (us SqlUserStore) GetAllProfilesInChannel(channelId string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := profilesInChannelCache.Get(channelId); ok { if cacheItem, ok := profilesInChannelCache.Get(channelId); ok {
@@ -626,12 +621,12 @@ func (us SqlUserStore) GetAllProfilesInChannel(channelId string, allowFromCache
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetProfilesNotInChannel(teamId string, channelId string, offset int, limit int) StoreChannel { func (us SqlUserStore) GetProfilesNotInChannel(teamId string, channelId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -667,11 +662,11 @@ func (us SqlUserStore) GetProfilesNotInChannel(teamId string, channelId string,
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetProfilesWithoutTeam(offset int, limit int) StoreChannel { func (us SqlUserStore) GetProfilesWithoutTeam(offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -713,11 +708,11 @@ func (us SqlUserStore) GetProfilesWithoutTeam(offset int, limit int) StoreChanne
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetProfilesByUsernames(usernames []string, teamId string) StoreChannel { func (us SqlUserStore) GetProfilesByUsernames(usernames []string, teamId string) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
props := make(map[string]interface{}) props := make(map[string]interface{})
@@ -759,12 +754,12 @@ type UserWithLastActivityAt struct {
LastActivityAt int64 LastActivityAt int64
} }
func (us SqlUserStore) GetRecentlyActiveUsersForTeam(teamId string, offset, limit int) StoreChannel { func (us SqlUserStore) GetRecentlyActiveUsersForTeam(teamId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*UserWithLastActivityAt var users []*UserWithLastActivityAt
@@ -801,12 +796,12 @@ func (us SqlUserStore) GetRecentlyActiveUsersForTeam(teamId string, offset, limi
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetNewUsersForTeam(teamId string, offset, limit int) StoreChannel { func (us SqlUserStore) GetNewUsersForTeam(teamId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -835,12 +830,12 @@ func (us SqlUserStore) GetNewUsersForTeam(teamId string, offset, limit int) Stor
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) StoreChannel { func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
users := []*model.User{} users := []*model.User{}
props := make(map[string]interface{}) props := make(map[string]interface{})
@@ -907,12 +902,12 @@ func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) St
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetSystemAdminProfiles() StoreChannel { func (us SqlUserStore) GetSystemAdminProfiles() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -937,19 +932,19 @@ func (us SqlUserStore) GetSystemAdminProfiles() StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetByEmail(email string) StoreChannel { func (us SqlUserStore) GetByEmail(email string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
email = strings.ToLower(email) email = strings.ToLower(email)
user := model.User{} user := model.User{}
if err := us.GetReplica().SelectOne(&user, "SELECT * FROM Users WHERE Email = :Email", map[string]interface{}{"Email": email}); err != nil { if err := us.GetReplica().SelectOne(&user, "SELECT * FROM Users WHERE Email = :Email", map[string]interface{}{"Email": email}); err != nil {
result.Err = model.NewAppError("SqlUserStore.GetByEmail", MISSING_ACCOUNT_ERROR, nil, "email="+email+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.GetByEmail", store.MISSING_ACCOUNT_ERROR, nil, "email="+email+", "+err.Error(), http.StatusInternalServerError)
} }
result.Data = &user result.Data = &user
@@ -961,15 +956,15 @@ func (us SqlUserStore) GetByEmail(email string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetByAuth(authData *string, authService string) StoreChannel { func (us SqlUserStore) GetByAuth(authData *string, authService string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if authData == nil || *authData == "" { if authData == nil || *authData == "" {
result.Err = model.NewAppError("SqlUserStore.GetByAuth", MISSING_AUTH_ACCOUNT_ERROR, nil, "authData='', authService="+authService, http.StatusBadRequest) result.Err = model.NewAppError("SqlUserStore.GetByAuth", store.MISSING_AUTH_ACCOUNT_ERROR, nil, "authData='', authService="+authService, http.StatusBadRequest)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
@@ -979,7 +974,7 @@ func (us SqlUserStore) GetByAuth(authData *string, authService string) StoreChan
if err := us.GetReplica().SelectOne(&user, "SELECT * FROM Users WHERE AuthData = :AuthData AND AuthService = :AuthService", map[string]interface{}{"AuthData": authData, "AuthService": authService}); err != nil { if err := us.GetReplica().SelectOne(&user, "SELECT * FROM Users WHERE AuthData = :AuthData AND AuthService = :AuthService", map[string]interface{}{"AuthData": authData, "AuthService": authService}); err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
result.Err = model.NewAppError("SqlUserStore.GetByAuth", MISSING_AUTH_ACCOUNT_ERROR, nil, "authData="+*authData+", authService="+authService+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.GetByAuth", store.MISSING_AUTH_ACCOUNT_ERROR, nil, "authData="+*authData+", authService="+authService+", "+err.Error(), http.StatusInternalServerError)
} else { } else {
result.Err = model.NewAppError("SqlUserStore.GetByAuth", "store.sql_user.get_by_auth.other.app_error", nil, "authData="+*authData+", authService="+authService+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.GetByAuth", "store.sql_user.get_by_auth.other.app_error", nil, "authData="+*authData+", authService="+authService+", "+err.Error(), http.StatusInternalServerError)
} }
@@ -994,12 +989,12 @@ func (us SqlUserStore) GetByAuth(authData *string, authService string) StoreChan
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetAllUsingAuthService(authService string) StoreChannel { func (us SqlUserStore) GetAllUsingAuthService(authService string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var data []*model.User var data []*model.User
if _, err := us.GetReplica().Select(&data, "SELECT * FROM Users WHERE AuthService = :AuthService", map[string]interface{}{"AuthService": authService}); err != nil { if _, err := us.GetReplica().Select(&data, "SELECT * FROM Users WHERE AuthService = :AuthService", map[string]interface{}{"AuthService": authService}); err != nil {
@@ -1015,12 +1010,12 @@ func (us SqlUserStore) GetAllUsingAuthService(authService string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetByUsername(username string) StoreChannel { func (us SqlUserStore) GetByUsername(username string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
user := model.User{} user := model.User{}
@@ -1037,11 +1032,11 @@ func (us SqlUserStore) GetByUsername(username string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetForLogin(loginId string, allowSignInWithUsername, allowSignInWithEmail, ldapEnabled bool) StoreChannel { func (us SqlUserStore) GetForLogin(loginId string, allowSignInWithUsername, allowSignInWithEmail, ldapEnabled bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
params := map[string]interface{}{ params := map[string]interface{}{
"LoginId": loginId, "LoginId": loginId,
@@ -1078,11 +1073,11 @@ func (us SqlUserStore) GetForLogin(loginId string, allowSignInWithUsername, allo
return storeChannel return storeChannel
} }
func (us SqlUserStore) VerifyEmail(userId string) StoreChannel { func (us SqlUserStore) VerifyEmail(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := us.GetMaster().Exec("UPDATE Users SET EmailVerified = true WHERE Id = :UserId", map[string]interface{}{"UserId": userId}); err != nil { if _, err := us.GetMaster().Exec("UPDATE Users SET EmailVerified = true WHERE Id = :UserId", map[string]interface{}{"UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlUserStore.VerifyEmail", "store.sql_user.verify_email.app_error", nil, "userId="+userId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.VerifyEmail", "store.sql_user.verify_email.app_error", nil, "userId="+userId+", "+err.Error(), http.StatusInternalServerError)
@@ -1097,11 +1092,11 @@ func (us SqlUserStore) VerifyEmail(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetTotalUsersCount() StoreChannel { func (us SqlUserStore) GetTotalUsersCount() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if count, err := us.GetReplica().SelectInt("SELECT COUNT(Id) FROM Users"); err != nil { if count, err := us.GetReplica().SelectInt("SELECT COUNT(Id) FROM Users"); err != nil {
result.Err = model.NewAppError("SqlUserStore.GetTotalUsersCount", "store.sql_user.get_total_users_count.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.GetTotalUsersCount", "store.sql_user.get_total_users_count.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -1116,12 +1111,12 @@ func (us SqlUserStore) GetTotalUsersCount() StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) PermanentDelete(userId string) StoreChannel { func (us SqlUserStore) PermanentDelete(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if _, err := us.GetMaster().Exec("DELETE FROM Users WHERE Id = :UserId", map[string]interface{}{"UserId": userId}); err != nil { if _, err := us.GetMaster().Exec("DELETE FROM Users WHERE Id = :UserId", map[string]interface{}{"UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlUserStore.PermanentDelete", "store.sql_user.permanent_delete.app_error", nil, "userId="+userId+", "+err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.PermanentDelete", "store.sql_user.permanent_delete.app_error", nil, "userId="+userId+", "+err.Error(), http.StatusInternalServerError)
@@ -1134,12 +1129,12 @@ func (us SqlUserStore) PermanentDelete(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) AnalyticsUniqueUserCount(teamId string) StoreChannel { func (us SqlUserStore) AnalyticsUniqueUserCount(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := "" query := ""
if len(teamId) > 0 { if len(teamId) > 0 {
@@ -1162,12 +1157,12 @@ func (us SqlUserStore) AnalyticsUniqueUserCount(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) AnalyticsActiveCount(timePeriod int64) StoreChannel { func (us SqlUserStore) AnalyticsActiveCount(timePeriod int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
time := model.GetMillis() - timePeriod time := model.GetMillis() - timePeriod
@@ -1187,11 +1182,11 @@ func (us SqlUserStore) AnalyticsActiveCount(timePeriod int64) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetUnreadCount(userId string) StoreChannel { func (us SqlUserStore) GetUnreadCount(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if count, err := us.GetReplica().SelectInt(` if count, err := us.GetReplica().SelectInt(`
SELECT SUM(CASE WHEN c.Type = 'D' THEN (c.TotalMsgCount - cm.MsgCount) ELSE cm.MentionCount END) SELECT SUM(CASE WHEN c.Type = 'D' THEN (c.TotalMsgCount - cm.MsgCount) ELSE cm.MentionCount END)
@@ -1212,11 +1207,11 @@ func (us SqlUserStore) GetUnreadCount(userId string) StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetUnreadCountForChannel(userId string, channelId string) StoreChannel { func (us SqlUserStore) GetUnreadCountForChannel(userId string, channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if count, err := us.GetReplica().SelectInt("SELECT SUM(CASE WHEN c.Type = 'D' THEN (c.TotalMsgCount - cm.MsgCount) ELSE cm.MentionCount END) FROM Channels c INNER JOIN ChannelMembers cm ON c.Id = :ChannelId AND cm.ChannelId = :ChannelId AND cm.UserId = :UserId", map[string]interface{}{"ChannelId": channelId, "UserId": userId}); err != nil { if count, err := us.GetReplica().SelectInt("SELECT SUM(CASE WHEN c.Type = 'D' THEN (c.TotalMsgCount - cm.MsgCount) ELSE cm.MentionCount END) FROM Channels c INNER JOIN ChannelMembers cm ON c.Id = :ChannelId AND cm.ChannelId = :ChannelId AND cm.UserId = :UserId", map[string]interface{}{"ChannelId": channelId, "UserId": userId}); err != nil {
result.Err = model.NewAppError("SqlUserStore.GetMentionCountForChannel", "store.sql_user.get_unread_count_for_channel.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.GetMentionCountForChannel", "store.sql_user.get_unread_count_for_channel.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -1231,8 +1226,8 @@ func (us SqlUserStore) GetUnreadCountForChannel(userId string, channelId string)
return storeChannel return storeChannel
} }
func (us SqlUserStore) Search(teamId string, term string, options map[string]bool) StoreChannel { func (us SqlUserStore) Search(teamId string, term string, options map[string]bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := "" searchQuery := ""
@@ -1275,8 +1270,8 @@ func (us SqlUserStore) Search(teamId string, term string, options map[string]boo
return storeChannel return storeChannel
} }
func (us SqlUserStore) SearchWithoutTeam(term string, options map[string]bool) StoreChannel { func (us SqlUserStore) SearchWithoutTeam(term string, options map[string]bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := ` searchQuery := `
@@ -1305,8 +1300,8 @@ func (us SqlUserStore) SearchWithoutTeam(term string, options map[string]bool) S
return storeChannel return storeChannel
} }
func (us SqlUserStore) SearchNotInTeam(notInTeamId string, term string, options map[string]bool) StoreChannel { func (us SqlUserStore) SearchNotInTeam(notInTeamId string, term string, options map[string]bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := ` searchQuery := `
@@ -1331,8 +1326,8 @@ func (us SqlUserStore) SearchNotInTeam(notInTeamId string, term string, options
return storeChannel return storeChannel
} }
func (us SqlUserStore) SearchNotInChannel(teamId string, channelId string, term string, options map[string]bool) StoreChannel { func (us SqlUserStore) SearchNotInChannel(teamId string, channelId string, term string, options map[string]bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := "" searchQuery := ""
@@ -1378,8 +1373,8 @@ func (us SqlUserStore) SearchNotInChannel(teamId string, channelId string, term
return storeChannel return storeChannel
} }
func (us SqlUserStore) SearchInChannel(channelId string, term string, options map[string]bool) StoreChannel { func (us SqlUserStore) SearchInChannel(channelId string, term string, options map[string]bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
searchQuery := ` searchQuery := `
@@ -1425,8 +1420,8 @@ var postgresSearchChar = []string{
"!", "!",
} }
func (us SqlUserStore) performSearch(searchQuery string, term string, options map[string]bool, parameters map[string]interface{}) StoreResult { func (us SqlUserStore) performSearch(searchQuery string, term string, options map[string]bool, parameters map[string]interface{}) store.StoreResult {
result := StoreResult{} result := store.StoreResult{}
// Special handling for emails // Special handling for emails
originalTerm := term originalTerm := term
@@ -1446,15 +1441,15 @@ func (us SqlUserStore) performSearch(searchQuery string, term string, options ma
} }
searchType := USER_SEARCH_TYPE_ALL searchType := USER_SEARCH_TYPE_ALL
if ok := options[USER_SEARCH_OPTION_NAMES_ONLY]; ok { if ok := options[store.USER_SEARCH_OPTION_NAMES_ONLY]; ok {
searchType = USER_SEARCH_TYPE_NAMES searchType = USER_SEARCH_TYPE_NAMES
} else if ok = options[USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME]; ok { } else if ok = options[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME]; ok {
searchType = USER_SEARCH_TYPE_NAMES_NO_FULL_NAME searchType = USER_SEARCH_TYPE_NAMES_NO_FULL_NAME
} else if ok = options[USER_SEARCH_OPTION_ALL_NO_FULL_NAME]; ok { } else if ok = options[store.USER_SEARCH_OPTION_ALL_NO_FULL_NAME]; ok {
searchType = USER_SEARCH_TYPE_ALL_NO_FULL_NAME searchType = USER_SEARCH_TYPE_ALL_NO_FULL_NAME
} }
if ok := options[USER_SEARCH_OPTION_ALLOW_INACTIVE]; ok { if ok := options[store.USER_SEARCH_OPTION_ALLOW_INACTIVE]; ok {
searchQuery = strings.Replace(searchQuery, "INACTIVE_CLAUSE", "", 1) searchQuery = strings.Replace(searchQuery, "INACTIVE_CLAUSE", "", 1)
} else { } else {
searchQuery = strings.Replace(searchQuery, "INACTIVE_CLAUSE", "AND Users.DeleteAt = 0", 1) searchQuery = strings.Replace(searchQuery, "INACTIVE_CLAUSE", "AND Users.DeleteAt = 0", 1)
@@ -1514,11 +1509,11 @@ func (us SqlUserStore) performSearch(searchQuery string, term string, options ma
return result return result
} }
func (us SqlUserStore) AnalyticsGetInactiveUsersCount() StoreChannel { func (us SqlUserStore) AnalyticsGetInactiveUsersCount() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if count, err := us.GetReplica().SelectInt("SELECT COUNT(Id) FROM Users WHERE DeleteAt > 0"); err != nil { if count, err := us.GetReplica().SelectInt("SELECT COUNT(Id) FROM Users WHERE DeleteAt > 0"); err != nil {
result.Err = model.NewAppError("SqlUserStore.AnalyticsGetInactiveUsersCount", "store.sql_user.analytics_get_inactive_users_count.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.AnalyticsGetInactiveUsersCount", "store.sql_user.analytics_get_inactive_users_count.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -1533,12 +1528,12 @@ func (us SqlUserStore) AnalyticsGetInactiveUsersCount() StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) AnalyticsGetSystemAdminCount() StoreChannel { func (us SqlUserStore) AnalyticsGetSystemAdminCount() store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if count, err := us.GetReplica().SelectInt("SELECT count(*) FROM Users WHERE Roles LIKE :Roles and DeleteAt = 0", map[string]interface{}{"Roles": "%system_admin%"}); err != nil { if count, err := us.GetReplica().SelectInt("SELECT count(*) FROM Users WHERE Roles LIKE :Roles and DeleteAt = 0", map[string]interface{}{"Roles": "%system_admin%"}); err != nil {
result.Err = model.NewAppError("SqlUserStore.AnalyticsGetSystemAdminCount", "store.sql_user.analytics_get_system_admin_count.app_error", nil, err.Error(), http.StatusInternalServerError) result.Err = model.NewAppError("SqlUserStore.AnalyticsGetSystemAdminCount", "store.sql_user.analytics_get_system_admin_count.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -1553,12 +1548,12 @@ func (us SqlUserStore) AnalyticsGetSystemAdminCount() StoreChannel {
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetProfilesNotInTeam(teamId string, offset int, limit int) StoreChannel { func (us SqlUserStore) GetProfilesNotInTeam(teamId string, offset int, limit int) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var users []*model.User var users []*model.User
@@ -1591,12 +1586,12 @@ func (us SqlUserStore) GetProfilesNotInTeam(teamId string, offset int, limit int
return storeChannel return storeChannel
} }
func (us SqlUserStore) GetEtagForProfilesNotInTeam(teamId string) StoreChannel { func (us SqlUserStore) GetEtagForProfilesNotInTeam(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel) storeChannel := make(store.StoreChannel)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
updateAt, err := us.GetReplica().SelectInt(` updateAt, err := us.GetReplica().SelectInt(`
SELECT SELECT

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"net/http" "net/http"
@@ -10,6 +10,7 @@ import (
"github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -29,7 +30,7 @@ func ClearWebhookCaches() {
webhookCache.Purge() webhookCache.Purge()
} }
func NewSqlWebhookStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) WebhookStore { func NewSqlWebhookStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.WebhookStore {
s := &SqlWebhookStore{ s := &SqlWebhookStore{
SqlStore: sqlStore, SqlStore: sqlStore,
metrics: metrics, metrics: metrics,
@@ -79,11 +80,11 @@ func (s SqlWebhookStore) InvalidateWebhookCache(webhookId string) {
webhookCache.Remove(webhookId) webhookCache.Remove(webhookId)
} }
func (s SqlWebhookStore) SaveIncoming(webhook *model.IncomingWebhook) StoreChannel { func (s SqlWebhookStore) SaveIncoming(webhook *model.IncomingWebhook) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(webhook.Id) > 0 { if len(webhook.Id) > 0 {
result.Err = model.NewAppError("SqlWebhookStore.SaveIncoming", "store.sql_webhooks.save_incoming.existing.app_error", nil, "id="+webhook.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlWebhookStore.SaveIncoming", "store.sql_webhooks.save_incoming.existing.app_error", nil, "id="+webhook.Id, http.StatusBadRequest)
@@ -112,11 +113,11 @@ func (s SqlWebhookStore) SaveIncoming(webhook *model.IncomingWebhook) StoreChann
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) UpdateIncoming(hook *model.IncomingWebhook) StoreChannel { func (s SqlWebhookStore) UpdateIncoming(hook *model.IncomingWebhook) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
hook.UpdateAt = model.GetMillis() hook.UpdateAt = model.GetMillis()
@@ -133,11 +134,11 @@ func (s SqlWebhookStore) UpdateIncoming(hook *model.IncomingWebhook) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetIncoming(id string, allowFromCache bool) StoreChannel { func (s SqlWebhookStore) GetIncoming(id string, allowFromCache bool) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := webhookCache.Get(id); ok { if cacheItem, ok := webhookCache.Get(id); ok {
@@ -178,11 +179,11 @@ func (s SqlWebhookStore) GetIncoming(id string, allowFromCache bool) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) DeleteIncoming(webhookId string, time int64) StoreChannel { func (s SqlWebhookStore) DeleteIncoming(webhookId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("Update IncomingWebhooks SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": webhookId}) _, err := s.GetMaster().Exec("Update IncomingWebhooks SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": webhookId})
if err != nil { if err != nil {
@@ -198,11 +199,11 @@ func (s SqlWebhookStore) DeleteIncoming(webhookId string, time int64) StoreChann
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) PermanentDeleteIncomingByUser(userId string) StoreChannel { func (s SqlWebhookStore) PermanentDeleteIncomingByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM IncomingWebhooks WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}) _, err := s.GetMaster().Exec("DELETE FROM IncomingWebhooks WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {
@@ -218,11 +219,11 @@ func (s SqlWebhookStore) PermanentDeleteIncomingByUser(userId string) StoreChann
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) PermanentDeleteIncomingByChannel(channelId string) StoreChannel { func (s SqlWebhookStore) PermanentDeleteIncomingByChannel(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM IncomingWebhooks WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId}) _, err := s.GetMaster().Exec("DELETE FROM IncomingWebhooks WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId})
if err != nil { if err != nil {
@@ -238,11 +239,11 @@ func (s SqlWebhookStore) PermanentDeleteIncomingByChannel(channelId string) Stor
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetIncomingList(offset, limit int) StoreChannel { func (s SqlWebhookStore) GetIncomingList(offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhooks []*model.IncomingWebhook var webhooks []*model.IncomingWebhook
@@ -259,11 +260,11 @@ func (s SqlWebhookStore) GetIncomingList(offset, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetIncomingByTeam(teamId string, offset, limit int) StoreChannel { func (s SqlWebhookStore) GetIncomingByTeam(teamId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhooks []*model.IncomingWebhook var webhooks []*model.IncomingWebhook
@@ -280,11 +281,11 @@ func (s SqlWebhookStore) GetIncomingByTeam(teamId string, offset, limit int) Sto
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetIncomingByChannel(channelId string) StoreChannel { func (s SqlWebhookStore) GetIncomingByChannel(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhooks []*model.IncomingWebhook var webhooks []*model.IncomingWebhook
@@ -301,11 +302,11 @@ func (s SqlWebhookStore) GetIncomingByChannel(channelId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) SaveOutgoing(webhook *model.OutgoingWebhook) StoreChannel { func (s SqlWebhookStore) SaveOutgoing(webhook *model.OutgoingWebhook) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
if len(webhook.Id) > 0 { if len(webhook.Id) > 0 {
result.Err = model.NewAppError("SqlWebhookStore.SaveOutgoing", "store.sql_webhooks.save_outgoing.override.app_error", nil, "id="+webhook.Id, http.StatusBadRequest) result.Err = model.NewAppError("SqlWebhookStore.SaveOutgoing", "store.sql_webhooks.save_outgoing.override.app_error", nil, "id="+webhook.Id, http.StatusBadRequest)
@@ -334,11 +335,11 @@ func (s SqlWebhookStore) SaveOutgoing(webhook *model.OutgoingWebhook) StoreChann
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetOutgoing(id string) StoreChannel { func (s SqlWebhookStore) GetOutgoing(id string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhook model.OutgoingWebhook var webhook model.OutgoingWebhook
@@ -355,11 +356,11 @@ func (s SqlWebhookStore) GetOutgoing(id string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetOutgoingList(offset, limit int) StoreChannel { func (s SqlWebhookStore) GetOutgoingList(offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhooks []*model.OutgoingWebhook var webhooks []*model.OutgoingWebhook
@@ -376,11 +377,11 @@ func (s SqlWebhookStore) GetOutgoingList(offset, limit int) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetOutgoingByChannel(channelId string, offset, limit int) StoreChannel { func (s SqlWebhookStore) GetOutgoingByChannel(channelId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhooks []*model.OutgoingWebhook var webhooks []*model.OutgoingWebhook
@@ -404,11 +405,11 @@ func (s SqlWebhookStore) GetOutgoingByChannel(channelId string, offset, limit in
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) GetOutgoingByTeam(teamId string, offset, limit int) StoreChannel { func (s SqlWebhookStore) GetOutgoingByTeam(teamId string, offset, limit int) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
var webhooks []*model.OutgoingWebhook var webhooks []*model.OutgoingWebhook
@@ -432,11 +433,11 @@ func (s SqlWebhookStore) GetOutgoingByTeam(teamId string, offset, limit int) Sto
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) DeleteOutgoing(webhookId string, time int64) StoreChannel { func (s SqlWebhookStore) DeleteOutgoing(webhookId string, time int64) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("Update OutgoingWebhooks SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": webhookId}) _, err := s.GetMaster().Exec("Update OutgoingWebhooks SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt WHERE Id = :Id", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": webhookId})
if err != nil { if err != nil {
@@ -450,11 +451,11 @@ func (s SqlWebhookStore) DeleteOutgoing(webhookId string, time int64) StoreChann
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) PermanentDeleteOutgoingByUser(userId string) StoreChannel { func (s SqlWebhookStore) PermanentDeleteOutgoingByUser(userId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM OutgoingWebhooks WHERE CreatorId = :UserId", map[string]interface{}{"UserId": userId}) _, err := s.GetMaster().Exec("DELETE FROM OutgoingWebhooks WHERE CreatorId = :UserId", map[string]interface{}{"UserId": userId})
if err != nil { if err != nil {
@@ -468,11 +469,11 @@ func (s SqlWebhookStore) PermanentDeleteOutgoingByUser(userId string) StoreChann
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) PermanentDeleteOutgoingByChannel(channelId string) StoreChannel { func (s SqlWebhookStore) PermanentDeleteOutgoingByChannel(channelId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
_, err := s.GetMaster().Exec("DELETE FROM OutgoingWebhooks WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId}) _, err := s.GetMaster().Exec("DELETE FROM OutgoingWebhooks WHERE ChannelId = :ChannelId", map[string]interface{}{"ChannelId": channelId})
if err != nil { if err != nil {
@@ -488,11 +489,11 @@ func (s SqlWebhookStore) PermanentDeleteOutgoingByChannel(channelId string) Stor
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) UpdateOutgoing(hook *model.OutgoingWebhook) StoreChannel { func (s SqlWebhookStore) UpdateOutgoing(hook *model.OutgoingWebhook) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
hook.UpdateAt = model.GetMillis() hook.UpdateAt = model.GetMillis()
@@ -509,11 +510,11 @@ func (s SqlWebhookStore) UpdateOutgoing(hook *model.OutgoingWebhook) StoreChanne
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) AnalyticsIncomingCount(teamId string) StoreChannel { func (s SqlWebhookStore) AnalyticsIncomingCount(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT `SELECT
@@ -540,11 +541,11 @@ func (s SqlWebhookStore) AnalyticsIncomingCount(teamId string) StoreChannel {
return storeChannel return storeChannel
} }
func (s SqlWebhookStore) AnalyticsOutgoingCount(teamId string) StoreChannel { func (s SqlWebhookStore) AnalyticsOutgoingCount(teamId string) store.StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(store.StoreChannel, 1)
go func() { go func() {
result := StoreResult{} result := store.StoreResult{}
query := query :=
`SELECT `SELECT

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

@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information. // See License.txt for license information.
package store package sqlstore
import ( import (
"testing" "testing"
@@ -13,28 +13,28 @@ import (
) )
func TestWebhookStoreSaveIncoming(t *testing.T) { func TestWebhookStoreSaveIncoming(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
if err := (<-store.Webhook().SaveIncoming(o1)).Err; err != nil { if err := (<-ss.Webhook().SaveIncoming(o1)).Err; err != nil {
t.Fatal("couldn't save item", err) t.Fatal("couldn't save item", err)
} }
if err := (<-store.Webhook().SaveIncoming(o1)).Err; err == nil { if err := (<-ss.Webhook().SaveIncoming(o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save") t.Fatal("shouldn't be able to update from save")
} }
} }
func TestWebhookStoreUpdateIncoming(t *testing.T) { func TestWebhookStoreUpdateIncoming(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
previousUpdatedAt := o1.UpdateAt previousUpdatedAt := o1.UpdateAt
o1.DisplayName = "TestHook" o1.DisplayName = "TestHook"
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
if result := (<-store.Webhook().UpdateIncoming(o1)); result.Err != nil { if result := (<-ss.Webhook().UpdateIncoming(o1)); result.Err != nil {
t.Fatal("updation of incoming hook failed", result.Err) t.Fatal("updation of incoming hook failed", result.Err)
} else { } else {
if result.Data.(*model.IncomingWebhook).UpdateAt == previousUpdatedAt { if result.Data.(*model.IncomingWebhook).UpdateAt == previousUpdatedAt {
@@ -48,12 +48,12 @@ func TestWebhookStoreUpdateIncoming(t *testing.T) {
} }
func TestWebhookStoreGetIncoming(t *testing.T) { func TestWebhookStoreGetIncoming(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-store.Webhook().GetIncoming(o1.Id, false); r1.Err != nil { if r1 := <-ss.Webhook().GetIncoming(o1.Id, false); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
@@ -61,7 +61,7 @@ func TestWebhookStoreGetIncoming(t *testing.T) {
} }
} }
if r1 := <-store.Webhook().GetIncoming(o1.Id, true); r1.Err != nil { if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
@@ -69,30 +69,30 @@ func TestWebhookStoreGetIncoming(t *testing.T) {
} }
} }
if err := (<-store.Webhook().GetIncoming("123", false)).Err; err == nil { if err := (<-ss.Webhook().GetIncoming("123", false)).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
if err := (<-store.Webhook().GetIncoming("123", true)).Err; err == nil { if err := (<-ss.Webhook().GetIncoming("123", true)).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
if err := (<-store.Webhook().GetIncoming("123", true)).Err; err.StatusCode != http.StatusNotFound { if err := (<-ss.Webhook().GetIncoming("123", true)).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for missing id") t.Fatal("Should have set the status as not found for missing id")
} }
} }
func TestWebhookStoreGetIncomingList(t *testing.T) { func TestWebhookStoreGetIncomingList(t *testing.T) {
Setup() ss := Setup()
o1 := &model.IncomingWebhook{} o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
o1.UserId = model.NewId() o1.UserId = model.NewId()
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-store.Webhook().GetIncomingList(0, 1000); r1.Err != nil { if r1 := <-ss.Webhook().GetIncomingList(0, 1000); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
found := false found := false
@@ -107,7 +107,7 @@ func TestWebhookStoreGetIncomingList(t *testing.T) {
} }
} }
if result := <-store.Webhook().GetIncomingList(0, 1); result.Err != nil { if result := <-ss.Webhook().GetIncomingList(0, 1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if len(result.Data.([]*model.IncomingWebhook)) != 1 { if len(result.Data.([]*model.IncomingWebhook)) != 1 {
@@ -117,12 +117,12 @@ func TestWebhookStoreGetIncomingList(t *testing.T) {
} }
func TestWebhookStoreGetIncomingByTeam(t *testing.T) { func TestWebhookStoreGetIncomingByTeam(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-store.Webhook().GetIncomingByTeam(o1.TeamId, 0, 100); r1.Err != nil { if r1 := <-ss.Webhook().GetIncomingByTeam(o1.TeamId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.([]*model.IncomingWebhook)[0].CreateAt != o1.CreateAt { if r1.Data.([]*model.IncomingWebhook)[0].CreateAt != o1.CreateAt {
@@ -130,7 +130,7 @@ func TestWebhookStoreGetIncomingByTeam(t *testing.T) {
} }
} }
if result := <-store.Webhook().GetIncomingByTeam("123", 0, 100); result.Err != nil { if result := <-ss.Webhook().GetIncomingByTeam("123", 0, 100); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if len(result.Data.([]*model.IncomingWebhook)) != 0 { if len(result.Data.([]*model.IncomingWebhook)) != 0 {
@@ -140,12 +140,12 @@ func TestWebhookStoreGetIncomingByTeam(t *testing.T) {
} }
func TestWebhookStoreDeleteIncoming(t *testing.T) { func TestWebhookStoreDeleteIncoming(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-store.Webhook().GetIncoming(o1.Id, true); r1.Err != nil { if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
@@ -153,23 +153,23 @@ func TestWebhookStoreDeleteIncoming(t *testing.T) {
} }
} }
if r2 := <-store.Webhook().DeleteIncoming(o1.Id, model.GetMillis()); r2.Err != nil { if r2 := <-ss.Webhook().DeleteIncoming(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil { if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestWebhookStoreDeleteIncomingByChannel(t *testing.T) { func TestWebhookStoreDeleteIncomingByChannel(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-store.Webhook().GetIncoming(o1.Id, true); r1.Err != nil { if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
@@ -177,23 +177,23 @@ func TestWebhookStoreDeleteIncomingByChannel(t *testing.T) {
} }
} }
if r2 := <-store.Webhook().PermanentDeleteIncomingByChannel(o1.ChannelId); r2.Err != nil { if r2 := <-ss.Webhook().PermanentDeleteIncomingByChannel(o1.ChannelId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil { if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestWebhookStoreDeleteIncomingByUser(t *testing.T) { func TestWebhookStoreDeleteIncomingByUser(t *testing.T) {
Setup() ss := Setup()
o1 := buildIncomingWebhook() o1 := buildIncomingWebhook()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-store.Webhook().GetIncoming(o1.Id, true); r1.Err != nil { if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
@@ -201,11 +201,11 @@ func TestWebhookStoreDeleteIncomingByUser(t *testing.T) {
} }
} }
if r2 := <-store.Webhook().PermanentDeleteIncomingByUser(o1.UserId); r2.Err != nil { if r2 := <-ss.Webhook().PermanentDeleteIncomingByUser(o1.UserId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil { if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
@@ -221,7 +221,7 @@ func buildIncomingWebhook() *model.IncomingWebhook {
} }
func TestWebhookStoreSaveOutgoing(t *testing.T) { func TestWebhookStoreSaveOutgoing(t *testing.T) {
Setup() ss := Setup()
o1 := model.OutgoingWebhook{} o1 := model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -229,17 +229,17 @@ func TestWebhookStoreSaveOutgoing(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
if err := (<-store.Webhook().SaveOutgoing(&o1)).Err; err != nil { if err := (<-ss.Webhook().SaveOutgoing(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err) t.Fatal("couldn't save item", err)
} }
if err := (<-store.Webhook().SaveOutgoing(&o1)).Err; err == nil { if err := (<-ss.Webhook().SaveOutgoing(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save") t.Fatal("shouldn't be able to update from save")
} }
} }
func TestWebhookStoreGetOutgoing(t *testing.T) { func TestWebhookStoreGetOutgoing(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -247,9 +247,9 @@ func TestWebhookStoreGetOutgoing(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoing(o1.Id); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
@@ -257,13 +257,13 @@ func TestWebhookStoreGetOutgoing(t *testing.T) {
} }
} }
if err := (<-store.Webhook().GetOutgoing("123")).Err; err == nil { if err := (<-ss.Webhook().GetOutgoing("123")).Err; err == nil {
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestWebhookStoreGetOutgoingList(t *testing.T) { func TestWebhookStoreGetOutgoingList(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -271,7 +271,7 @@ func TestWebhookStoreGetOutgoingList(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
o2 := &model.OutgoingWebhook{} o2 := &model.OutgoingWebhook{}
o2.ChannelId = model.NewId() o2.ChannelId = model.NewId()
@@ -279,9 +279,9 @@ func TestWebhookStoreGetOutgoingList(t *testing.T) {
o2.TeamId = model.NewId() o2.TeamId = model.NewId()
o2.CallbackURLs = []string{"http://nowhere.com/"} o2.CallbackURLs = []string{"http://nowhere.com/"}
o2 = (<-store.Webhook().SaveOutgoing(o2)).Data.(*model.OutgoingWebhook) o2 = (<-ss.Webhook().SaveOutgoing(o2)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoingList(0, 1000); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoingList(0, 1000); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
hooks := r1.Data.([]*model.OutgoingWebhook) hooks := r1.Data.([]*model.OutgoingWebhook)
@@ -306,7 +306,7 @@ func TestWebhookStoreGetOutgoingList(t *testing.T) {
} }
} }
if result := <-store.Webhook().GetOutgoingList(0, 2); result.Err != nil { if result := <-ss.Webhook().GetOutgoingList(0, 2); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if len(result.Data.([]*model.OutgoingWebhook)) != 2 { if len(result.Data.([]*model.OutgoingWebhook)) != 2 {
@@ -316,7 +316,7 @@ func TestWebhookStoreGetOutgoingList(t *testing.T) {
} }
func TestWebhookStoreGetOutgoingByChannel(t *testing.T) { func TestWebhookStoreGetOutgoingByChannel(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -324,9 +324,9 @@ func TestWebhookStoreGetOutgoingByChannel(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoingByChannel(o1.ChannelId, 0, 100); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoingByChannel(o1.ChannelId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt { if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt {
@@ -334,7 +334,7 @@ func TestWebhookStoreGetOutgoingByChannel(t *testing.T) {
} }
} }
if result := <-store.Webhook().GetOutgoingByChannel("123", -1, -1); result.Err != nil { if result := <-ss.Webhook().GetOutgoingByChannel("123", -1, -1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if len(result.Data.([]*model.OutgoingWebhook)) != 0 { if len(result.Data.([]*model.OutgoingWebhook)) != 0 {
@@ -344,7 +344,7 @@ func TestWebhookStoreGetOutgoingByChannel(t *testing.T) {
} }
func TestWebhookStoreGetOutgoingByTeam(t *testing.T) { func TestWebhookStoreGetOutgoingByTeam(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -352,9 +352,9 @@ func TestWebhookStoreGetOutgoingByTeam(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoingByTeam(o1.TeamId, 0, 100); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoingByTeam(o1.TeamId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt { if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt {
@@ -362,7 +362,7 @@ func TestWebhookStoreGetOutgoingByTeam(t *testing.T) {
} }
} }
if result := <-store.Webhook().GetOutgoingByTeam("123", -1, -1); result.Err != nil { if result := <-ss.Webhook().GetOutgoingByTeam("123", -1, -1); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
if len(result.Data.([]*model.OutgoingWebhook)) != 0 { if len(result.Data.([]*model.OutgoingWebhook)) != 0 {
@@ -372,7 +372,7 @@ func TestWebhookStoreGetOutgoingByTeam(t *testing.T) {
} }
func TestWebhookStoreDeleteOutgoing(t *testing.T) { func TestWebhookStoreDeleteOutgoing(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -380,9 +380,9 @@ func TestWebhookStoreDeleteOutgoing(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoing(o1.Id); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
@@ -390,18 +390,18 @@ func TestWebhookStoreDeleteOutgoing(t *testing.T) {
} }
} }
if r2 := <-store.Webhook().DeleteOutgoing(o1.Id, model.GetMillis()); r2.Err != nil { if r2 := <-ss.Webhook().DeleteOutgoing(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Webhook().GetOutgoing(o1.Id)); r3.Err == nil { if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestWebhookStoreDeleteOutgoingByChannel(t *testing.T) { func TestWebhookStoreDeleteOutgoingByChannel(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -409,9 +409,9 @@ func TestWebhookStoreDeleteOutgoingByChannel(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoing(o1.Id); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
@@ -419,18 +419,18 @@ func TestWebhookStoreDeleteOutgoingByChannel(t *testing.T) {
} }
} }
if r2 := <-store.Webhook().PermanentDeleteOutgoingByChannel(o1.ChannelId); r2.Err != nil { if r2 := <-ss.Webhook().PermanentDeleteOutgoingByChannel(o1.ChannelId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Webhook().GetOutgoing(o1.Id)); r3.Err == nil { if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestWebhookStoreDeleteOutgoingByUser(t *testing.T) { func TestWebhookStoreDeleteOutgoingByUser(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -438,9 +438,9 @@ func TestWebhookStoreDeleteOutgoingByUser(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-store.Webhook().GetOutgoing(o1.Id); r1.Err != nil { if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err) t.Fatal(r1.Err)
} else { } else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt { if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
@@ -448,18 +448,18 @@ func TestWebhookStoreDeleteOutgoingByUser(t *testing.T) {
} }
} }
if r2 := <-store.Webhook().PermanentDeleteOutgoingByUser(o1.CreatorId); r2.Err != nil { if r2 := <-ss.Webhook().PermanentDeleteOutgoingByUser(o1.CreatorId); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
if r3 := (<-store.Webhook().GetOutgoing(o1.Id)); r3.Err == nil { if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data) t.Log(r3.Data)
t.Fatal("Missing id should have failed") t.Fatal("Missing id should have failed")
} }
} }
func TestWebhookStoreUpdateOutgoing(t *testing.T) { func TestWebhookStoreUpdateOutgoing(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -467,26 +467,26 @@ func TestWebhookStoreUpdateOutgoing(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
o1.Token = model.NewId() o1.Token = model.NewId()
if r2 := <-store.Webhook().UpdateOutgoing(o1); r2.Err != nil { if r2 := <-ss.Webhook().UpdateOutgoing(o1); r2.Err != nil {
t.Fatal(r2.Err) t.Fatal(r2.Err)
} }
} }
func TestWebhookStoreCountIncoming(t *testing.T) { func TestWebhookStoreCountIncoming(t *testing.T) {
Setup() ss := Setup()
o1 := &model.IncomingWebhook{} o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
o1.UserId = model.NewId() o1.UserId = model.NewId()
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1 = (<-store.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook) o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r := <-store.Webhook().AnalyticsIncomingCount(""); r.Err != nil { if r := <-ss.Webhook().AnalyticsIncomingCount(""); r.Err != nil {
t.Fatal(r.Err) t.Fatal(r.Err)
} else { } else {
if r.Data.(int64) == 0 { if r.Data.(int64) == 0 {
@@ -496,7 +496,7 @@ func TestWebhookStoreCountIncoming(t *testing.T) {
} }
func TestWebhookStoreCountOutgoing(t *testing.T) { func TestWebhookStoreCountOutgoing(t *testing.T) {
Setup() ss := Setup()
o1 := &model.OutgoingWebhook{} o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId() o1.ChannelId = model.NewId()
@@ -504,9 +504,9 @@ func TestWebhookStoreCountOutgoing(t *testing.T) {
o1.TeamId = model.NewId() o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"} o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-store.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook) o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r := <-store.Webhook().AnalyticsOutgoingCount(""); r.Err != nil { if r := <-ss.Webhook().AnalyticsOutgoingCount(""); r.Err != nil {
t.Fatal(r.Err) t.Fatal(r.Err)
} else { } else {
if r.Data.(int64) == 0 { if r.Data.(int64) == 0 {