浏览代码

Began work on user favorites backend support & storage

Torkel Ödegaard 11 年之前
父节点
当前提交
e02e60171e
共有 3 个文件被更改,包括 64 次插入1 次删除
  1. 17 0
      pkg/models/favorite.go
  2. 34 0
      pkg/services/sqlstore/favorite.go
  3. 13 1
      pkg/services/sqlstore/migrations.go

+ 17 - 0
pkg/models/favorite.go

@@ -0,0 +1,17 @@
+package models
+
+type Favorite struct {
+	Id          int64
+	UserId      int64
+	DashboardId int64
+}
+
+type AddAsFavoriteCommand struct {
+	UserId      int64
+	DashboardId int64
+}
+
+type RemoveAsFavoriteCommand struct {
+	UserId      int64
+	DashboardId int64
+}

+ 34 - 0
pkg/services/sqlstore/favorite.go

@@ -0,0 +1,34 @@
+package sqlstore
+
+import (
+	"github.com/go-xorm/xorm"
+
+	"github.com/torkelo/grafana-pro/pkg/bus"
+	m "github.com/torkelo/grafana-pro/pkg/models"
+)
+
+func init() {
+	bus.AddHandler("sql", AddAsFavorite)
+	bus.AddHandler("sql", RemoveAsFavorite)
+}
+
+func AddAsFavorite(cmd *m.AddAsFavoriteCommand) error {
+	return inTransaction(func(sess *xorm.Session) error {
+
+		entity := m.Favorite{
+			UserId:      cmd.UserId,
+			DashboardId: cmd.DashboardId,
+		}
+
+		_, err := sess.Insert(&entity)
+		return err
+	})
+}
+
+func RemoveAsFavorite(cmd *m.RemoveAsFavoriteCommand) error {
+	return inTransaction(func(sess *xorm.Session) error {
+		var rawSql = "DELETE FROM favorite WHERE user_id=? and dashboard_id=?"
+		_, err := sess.Exec(rawSql, cmd.UserId, cmd.DashboardId)
+		return err
+	})
+}

+ 13 - 1
pkg/services/sqlstore/migrations.go

@@ -6,11 +6,11 @@ import . "github.com/torkelo/grafana-pro/pkg/services/sqlstore/migrator"
 // 1. Never change a migration that is committed and pushed to master
 // 2. Always add new migrations (to change or undo previous migrations)
 // 3. Some migraitons are not yet written (rename column, table, drop table, index etc)
-// 4
 
 func addMigrations(mg *Migrator) {
 	addMigrationLogMigrations(mg)
 	addUserMigrations(mg)
+	addFavoritesMigrations(mg)
 	addAccountMigrations(mg)
 	addDashboardMigration(mg)
 	addDataSourceMigration(mg)
@@ -55,6 +55,18 @@ func addUserMigrations(mg *Migrator) {
 		Table("user").Column(&Column{Name: "rands", Type: DB_NVarchar, Length: 255, Nullable: true}))
 }
 
+func addFavoritesMigrations(mg *Migrator) {
+	mg.AddMigration("create favorite table", new(AddTableMigration).
+		Name("favorite").WithColumns(
+		&Column{Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
+		&Column{Name: "user_id", Type: DB_BigInt, Nullable: false},
+		&Column{Name: "dashboard_id", Type: DB_BigInt, Nullable: false},
+	))
+
+	mg.AddMigration("add unique index favorite.user_id_dashboard_id", new(AddIndexMigration).
+		Table("favorite").Columns("user_id", "dashboard_id").Unique())
+}
+
 func addAccountMigrations(mg *Migrator) {
 	mg.AddMigration("create account table", new(AddTableMigration).
 		Name("account").WithColumns(