summaryrefslogtreecommitdiffstats
path: root/store
diff options
context:
space:
mode:
Diffstat (limited to 'store')
-rw-r--r--store/sql_preference_store.go214
-rw-r--r--store/sql_preference_store_test.go146
-rw-r--r--store/sql_store.go30
-rw-r--r--store/store.go7
4 files changed, 386 insertions, 11 deletions
diff --git a/store/sql_preference_store.go b/store/sql_preference_store.go
new file mode 100644
index 000000000..46cef38b1
--- /dev/null
+++ b/store/sql_preference_store.go
@@ -0,0 +1,214 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package store
+
+import (
+ "github.com/go-gorp/gorp"
+ "github.com/mattermost/platform/model"
+ "github.com/mattermost/platform/utils"
+)
+
+type SqlPreferenceStore struct {
+ *SqlStore
+}
+
+func NewSqlPreferenceStore(sqlStore *SqlStore) PreferenceStore {
+ s := &SqlPreferenceStore{sqlStore}
+
+ for _, db := range sqlStore.GetAllConns() {
+ table := db.AddTableWithName(model.Preference{}, "Preferences").SetKeys(false, "UserId", "Category", "Name")
+ table.ColMap("UserId").SetMaxSize(26)
+ table.ColMap("Category").SetMaxSize(32)
+ table.ColMap("Name").SetMaxSize(32)
+ table.ColMap("Value").SetMaxSize(128)
+ }
+
+ return s
+}
+
+func (s SqlPreferenceStore) UpgradeSchemaIfNeeded() {
+}
+
+func (s SqlPreferenceStore) CreateIndexesIfNotExists() {
+ s.CreateIndexIfNotExists("idx_preferences_user_id", "Preferences", "UserId")
+ s.CreateIndexIfNotExists("idx_preferences_category", "Preferences", "Category")
+ s.CreateIndexIfNotExists("idx_preferences_name", "Preferences", "Name")
+}
+
+func (s SqlPreferenceStore) Save(preferences *model.Preferences) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ // wrap in a transaction so that if one fails, everything fails
+ transaction, err := s.GetReplica().Begin()
+ if err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.Save", "Unable to open transaction to save preferences", err.Error())
+ } else {
+ for _, preference := range *preferences {
+ if upsertResult := s.save(transaction, &preference); upsertResult.Err != nil {
+ result = upsertResult
+ break
+ }
+ }
+
+ if result.Err == nil {
+ if err := transaction.Commit(); err != nil {
+ // don't need to rollback here since the transaction is already closed
+ result.Err = model.NewAppError("SqlPreferenceStore.Save", "Unable to commit transaction to save preferences", err.Error())
+ } else {
+ result.Data = len(*preferences)
+ }
+ } else {
+ if err := transaction.Rollback(); err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.Save", "Unable to rollback transaction to save preferences", err.Error())
+ }
+ }
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
+
+func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
+ result := StoreResult{}
+
+ if result.Err = preference.IsValid(); result.Err != nil {
+ return result
+ }
+
+ params := map[string]interface{}{
+ "UserId": preference.UserId,
+ "Category": preference.Category,
+ "Name": preference.Name,
+ "Value": preference.Value,
+ }
+
+ if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_MYSQL {
+ if _, err := transaction.Exec(
+ `INSERT INTO
+ Preferences
+ (UserId, Category, Name, Value)
+ VALUES
+ (:UserId, :Category, :Name, :Value)
+ ON DUPLICATE KEY UPDATE
+ Value = :Value`, params); err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.save", "We encountered an error while updating preferences", err.Error())
+ }
+ } else if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
+ // postgres has no way to upsert values until version 9.5 and trying inserting and then updating causes transactions to abort
+ count, err := transaction.SelectInt(
+ `SELECT
+ count(0)
+ FROM
+ Preferences
+ WHERE
+ UserId = :UserId
+ AND Category = :Category
+ AND Name = :Name`, params)
+ if err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.save", "We encountered an error while updating preferences", err.Error())
+ return result
+ }
+
+ if count == 1 {
+ s.update(transaction, preference)
+ } else {
+ s.insert(transaction, preference)
+ }
+ } else {
+ result.Err = model.NewAppError("SqlPreferenceStore.save", "We encountered an error while updating preferences",
+ "Failed to update preference because of missing driver")
+ }
+
+ return result
+}
+
+func (s SqlPreferenceStore) insert(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
+ result := StoreResult{}
+
+ if err := transaction.Insert(preference); err != nil {
+ if IsUniqueConstraintError(err.Error(), "UserId", "preferences_pkey") {
+ result.Err = model.NewAppError("SqlPreferenceStore.insert", "A preference with that user id, category, and name already exists",
+ "user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
+ } else {
+ result.Err = model.NewAppError("SqlPreferenceStore.insert", "We couldn't save the preference",
+ "user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
+ }
+ }
+
+ return result
+}
+
+func (s SqlPreferenceStore) update(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
+ result := StoreResult{}
+
+ if _, err := transaction.Update(preference); err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.update", "We couldn't update the preference",
+ "user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
+ }
+
+ return result
+}
+
+func (s SqlPreferenceStore) Get(userId string, category string, name string) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ var preference model.Preference
+
+ if err := s.GetReplica().SelectOne(&preference,
+ `SELECT
+ *
+ FROM
+ Preferences
+ WHERE
+ UserId = :UserId
+ AND Category = :Category
+ AND Name = :Name`, map[string]interface{}{"UserId": userId, "Category": category, "Name": name}); err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.Get", "We encounted an error while finding preferences", err.Error())
+ } else {
+ result.Data = preference
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
+
+func (s SqlPreferenceStore) GetCategory(userId string, category string) StoreChannel {
+ storeChannel := make(StoreChannel)
+
+ go func() {
+ result := StoreResult{}
+
+ var preferences model.Preferences
+
+ if _, err := s.GetReplica().Select(&preferences,
+ `SELECT
+ *
+ FROM
+ Preferences
+ WHERE
+ UserId = :UserId
+ AND Category = :Category`, map[string]interface{}{"UserId": userId, "Category": category}); err != nil {
+ result.Err = model.NewAppError("SqlPreferenceStore.GetCategory", "We encounted an error while finding preferences", err.Error())
+ } else {
+ result.Data = preferences
+ }
+
+ storeChannel <- result
+ close(storeChannel)
+ }()
+
+ return storeChannel
+}
diff --git a/store/sql_preference_store_test.go b/store/sql_preference_store_test.go
new file mode 100644
index 000000000..76b1bcb17
--- /dev/null
+++ b/store/sql_preference_store_test.go
@@ -0,0 +1,146 @@
+// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
+// See License.txt for license information.
+
+package store
+
+import (
+ "github.com/mattermost/platform/model"
+ "testing"
+)
+
+func TestPreferenceSave(t *testing.T) {
+ Setup()
+
+ id := model.NewId()
+
+ preferences := model.Preferences{
+ {
+ UserId: id,
+ Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
+ Name: model.NewId(),
+ Value: "value1a",
+ },
+ {
+ UserId: id,
+ Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
+ Name: model.NewId(),
+ Value: "value1b",
+ },
+ }
+ if count := Must(store.Preference().Save(&preferences)); count != 2 {
+ t.Fatal("got incorrect number of rows saved")
+ }
+
+ for _, preference := range preferences {
+ if data := Must(store.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
+ t.Fatal("got incorrect preference after first Save")
+ }
+ }
+
+ preferences[0].Value = "value2a"
+ preferences[1].Value = "value2b"
+ if count := Must(store.Preference().Save(&preferences)); count != 2 {
+ t.Fatal("got incorrect number of rows saved")
+ }
+
+ for _, preference := range preferences {
+ if data := Must(store.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
+ t.Fatal("got incorrect preference after second Save")
+ }
+ }
+}
+
+func TestPreferenceGet(t *testing.T) {
+ Setup()
+
+ userId := model.NewId()
+ category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
+ name := model.NewId()
+
+ preferences := model.Preferences{
+ {
+ UserId: userId,
+ Category: category,
+ Name: name,
+ },
+ {
+ UserId: userId,
+ Category: category,
+ Name: model.NewId(),
+ },
+ {
+ UserId: userId,
+ Category: model.NewId(),
+ Name: name,
+ },
+ {
+ UserId: model.NewId(),
+ Category: category,
+ Name: name,
+ },
+ }
+
+ Must(store.Preference().Save(&preferences))
+
+ if result := <-store.Preference().Get(userId, category, name); result.Err != nil {
+ t.Fatal(result.Err)
+ } else if data := result.Data.(model.Preference); data != preferences[0] {
+ t.Fatal("got incorrect preference")
+ }
+
+ // make sure getting a missing preference fails
+ if result := <-store.Preference().Get(model.NewId(), model.NewId(), model.NewId()); result.Err == nil {
+ t.Fatal("no error on getting a missing preference")
+ }
+}
+
+func TestPreferenceGetCategory(t *testing.T) {
+ Setup()
+
+ userId := model.NewId()
+ category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
+ name := model.NewId()
+
+ preferences := model.Preferences{
+ {
+ UserId: userId,
+ Category: category,
+ Name: name,
+ },
+ // same user/category, different name
+ {
+ UserId: userId,
+ Category: category,
+ Name: model.NewId(),
+ },
+ // same user/name, different category
+ {
+ UserId: userId,
+ Category: model.NewId(),
+ Name: name,
+ },
+ // same name/category, different user
+ {
+ UserId: model.NewId(),
+ Category: category,
+ Name: name,
+ },
+ }
+
+ Must(store.Preference().Save(&preferences))
+
+ if result := <-store.Preference().GetCategory(userId, category); result.Err != nil {
+ t.Fatal(result.Err)
+ } else if data := result.Data.(model.Preferences); len(data) != 2 {
+ t.Fatal("got the wrong number of preferences")
+ } else if !((data[0] == preferences[0] && data[1] == preferences[1]) || (data[0] == preferences[1] && data[1] == preferences[0])) {
+ t.Fatal("got incorrect preferences")
+ }
+
+ // make sure getting a missing preference category doesn't fail
+ if result := <-store.Preference().GetCategory(model.NewId(), model.NewId()); result.Err != nil {
+ t.Fatal(result.Err)
+ } else if data := result.Data.(model.Preferences); len(data) != 0 {
+ t.Fatal("shouldn't have got any preferences")
+ }
+}
diff --git a/store/sql_store.go b/store/sql_store.go
index 900543460..4b055e455 100644
--- a/store/sql_store.go
+++ b/store/sql_store.go
@@ -30,17 +30,18 @@ import (
)
type SqlStore struct {
- master *gorp.DbMap
- replicas []*gorp.DbMap
- team TeamStore
- channel ChannelStore
- post PostStore
- user UserStore
- audit AuditStore
- session SessionStore
- oauth OAuthStore
- system SystemStore
- webhook WebhookStore
+ master *gorp.DbMap
+ replicas []*gorp.DbMap
+ team TeamStore
+ channel ChannelStore
+ post PostStore
+ user UserStore
+ audit AuditStore
+ session SessionStore
+ oauth OAuthStore
+ system SystemStore
+ webhook WebhookStore
+ preference PreferenceStore
}
func NewSqlStore() Store {
@@ -93,6 +94,7 @@ func NewSqlStore() Store {
sqlStore.oauth = NewSqlOAuthStore(sqlStore)
sqlStore.system = NewSqlSystemStore(sqlStore)
sqlStore.webhook = NewSqlWebhookStore(sqlStore)
+ sqlStore.preference = NewSqlPreferenceStore(sqlStore)
sqlStore.master.CreateTablesIfNotExists()
@@ -105,6 +107,7 @@ func NewSqlStore() Store {
sqlStore.oauth.(*SqlOAuthStore).UpgradeSchemaIfNeeded()
sqlStore.system.(*SqlSystemStore).UpgradeSchemaIfNeeded()
sqlStore.webhook.(*SqlWebhookStore).UpgradeSchemaIfNeeded()
+ sqlStore.preference.(*SqlPreferenceStore).UpgradeSchemaIfNeeded()
sqlStore.team.(*SqlTeamStore).CreateIndexesIfNotExists()
sqlStore.channel.(*SqlChannelStore).CreateIndexesIfNotExists()
@@ -115,6 +118,7 @@ func NewSqlStore() Store {
sqlStore.oauth.(*SqlOAuthStore).CreateIndexesIfNotExists()
sqlStore.system.(*SqlSystemStore).CreateIndexesIfNotExists()
sqlStore.webhook.(*SqlWebhookStore).CreateIndexesIfNotExists()
+ sqlStore.preference.(*SqlPreferenceStore).CreateIndexesIfNotExists()
if model.IsPreviousVersion(schemaVersion) {
sqlStore.system.Update(&model.System{Name: "Version", Value: model.CurrentVersion})
@@ -472,6 +476,10 @@ func (ss SqlStore) Webhook() WebhookStore {
return ss.webhook
}
+func (ss SqlStore) Preference() PreferenceStore {
+ return ss.preference
+}
+
type mattermConverter struct{}
func (me mattermConverter) ToDb(val interface{}) (interface{}, error) {
diff --git a/store/store.go b/store/store.go
index e539bc98a..6e1614ccb 100644
--- a/store/store.go
+++ b/store/store.go
@@ -37,6 +37,7 @@ type Store interface {
OAuth() OAuthStore
System() SystemStore
Webhook() WebhookStore
+ Preference() PreferenceStore
Close()
}
@@ -149,3 +150,9 @@ type WebhookStore interface {
GetIncomingByUser(userId string) StoreChannel
DeleteIncoming(webhookId string, time int64) StoreChannel
}
+
+type PreferenceStore interface {
+ Save(preferences *model.Preferences) StoreChannel
+ Get(userId string, category string, name string) StoreChannel
+ GetCategory(userId string, category string) StoreChannel
+}