[MM-39642] - Migrate from gorp to sqlx in store/sqlstore/session_store.go (#18891)

* migrate from gorp to sqlx

Signed-off-by: Penthaa Patel <penthaapatel@gmail.com>

* fix Save function

Signed-off-by: Penthaa Patel <penthaapatel@gmail.com>

* fix Get function

Signed-off-by: Penthaa Patel <penthaapatel@gmail.com>

* use json.Marshal() for session.Props

Signed-off-by: Penthaa Patel <penthaapatel@gmail.com>
Этот коммит содержится в:
Penthaa Patel
2021-11-15 19:40:37 +05:30
коммит произвёл GitHub
родитель 21a61813e8
Коммит ae897bc59a

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

@@ -5,6 +5,7 @@ package sqlstore
import (
"context"
"encoding/json"
"fmt"
"time"
@@ -57,8 +58,20 @@ func (me SqlSessionStore) Save(session *model.Session) (*model.Session, error) {
if err := session.IsValid(); err != nil {
return nil, err
}
jsonProps, err := json.Marshal(session.Props)
if err != nil {
return nil, errors.Wrap(err, "failed marshalling session props")
}
if err := me.GetMaster().Insert(session); err != nil {
query, args, err := me.getQueryBuilder().
Insert("Sessions").
Columns("Id", "Token", "CreateAt", "ExpiresAt", "LastActivityAt", "UserId", "DeviceId", "Roles", "IsOAuth", "ExpiredNotify", "Props").
Values(session.Id, session.Token, session.CreateAt, session.ExpiresAt, session.LastActivityAt, session.UserId, session.DeviceId, session.Roles, session.IsOAuth, session.ExpiredNotify, string(jsonProps)).
ToSql()
if err != nil {
return nil, errors.Wrap(err, "sessions_tosql")
}
if _, err = me.GetMasterX().Exec(query, args...); err != nil {
return nil, errors.Wrapf(err, "failed to save Session with id=%s", session.Id)
}
@@ -78,11 +91,12 @@ func (me SqlSessionStore) Save(session *model.Session) (*model.Session, error) {
}
func (me SqlSessionStore) Get(ctx context.Context, sessionIdOrToken string) (*model.Session, error) {
var sessions []*model.Session
sessions := []*model.Session{}
if _, err := me.DBFromContext(ctx).Select(&sessions, "SELECT * FROM Sessions WHERE Token = :Token OR Id = :Id LIMIT 1", map[string]interface{}{"Token": sessionIdOrToken, "Id": sessionIdOrToken}); err != nil {
if err := me.DBXFromContext(ctx).Select(&sessions, "SELECT * FROM Sessions WHERE Token = ? OR Id = ? LIMIT 1", sessionIdOrToken, sessionIdOrToken); err != nil {
return nil, errors.Wrapf(err, "failed to find Sessions with sessionIdOrToken=%s", sessionIdOrToken)
} else if len(sessions) == 0 {
}
if len(sessions) == 0 {
return nil, store.NewErrNotFound("Session", fmt.Sprintf("sessionIdOrToken=%s", sessionIdOrToken))
}
session := sessions[0]
@@ -103,9 +117,9 @@ func (me SqlSessionStore) Get(ctx context.Context, sessionIdOrToken string) (*mo
}
func (me SqlSessionStore) GetSessions(userId string) ([]*model.Session, error) {
var sessions []*model.Session
sessions := []*model.Session{}
if _, err := me.GetReplica().Select(&sessions, "SELECT * FROM Sessions WHERE UserId = :UserId ORDER BY LastActivityAt DESC", map[string]interface{}{"UserId": userId}); err != nil {
if err := me.GetReplicaX().Select(&sessions, "SELECT * FROM Sessions WHERE UserId = ? ORDER BY LastActivityAt DESC", userId); err != nil {
return nil, errors.Wrapf(err, "failed to find Sessions with userId=%s", userId)
}
@@ -131,15 +145,14 @@ func (me SqlSessionStore) GetSessionsWithActiveDeviceIds(userId string) ([]*mode
FROM
Sessions
WHERE
UserId = :UserId AND
UserId = ? AND
ExpiresAt != 0 AND
:ExpiresAt <= ExpiresAt AND
? <= ExpiresAt AND
DeviceId != ''`
var sessions []*model.Session
sessions := []*model.Session{}
_, err := me.GetReplica().Select(&sessions, query, map[string]interface{}{"UserId": userId, "ExpiresAt": model.GetMillis()})
if err != nil {
if err := me.GetReplicaX().Select(&sessions, query, userId, model.GetMillis()); err != nil {
return nil, errors.Wrapf(err, "failed to find Sessions with userId=%s", userId)
}
return sessions, nil
@@ -165,9 +178,9 @@ func (me SqlSessionStore) GetSessionsExpired(thresholdMillis int64, mobileOnly b
return nil, errors.Wrap(err, "sessions_tosql")
}
var sessions []*model.Session
sessions := []*model.Session{}
_, err = me.GetReplica().Select(&sessions, query, args...)
err = me.GetReplicaX().Select(&sessions, query, args...)
if err != nil {
return nil, errors.Wrap(err, "failed to find Sessions")
}
@@ -184,7 +197,7 @@ func (me SqlSessionStore) UpdateExpiredNotify(sessionId string, notified bool) e
return errors.Wrap(err, "sessions_tosql")
}
_, err = me.GetMaster().Exec(query, args...)
_, err = me.GetMasterX().Exec(query, args...)
if err != nil {
return errors.Wrapf(err, "failed to update Session with id=%s", sessionId)
}
@@ -192,7 +205,7 @@ func (me SqlSessionStore) UpdateExpiredNotify(sessionId string, notified bool) e
}
func (me SqlSessionStore) Remove(sessionIdOrToken string) error {
_, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE Id = :Id Or Token = :Token", map[string]interface{}{"Id": sessionIdOrToken, "Token": sessionIdOrToken})
_, err := me.GetMasterX().Exec("DELETE FROM Sessions WHERE Id = ? Or Token = ?", sessionIdOrToken, sessionIdOrToken)
if err != nil {
return errors.Wrapf(err, "failed to delete Session with sessionIdOrToken=%s", sessionIdOrToken)
}
@@ -200,7 +213,7 @@ func (me SqlSessionStore) Remove(sessionIdOrToken string) error {
}
func (me SqlSessionStore) RemoveAllSessions() error {
_, err := me.GetMaster().Exec("DELETE FROM Sessions")
_, err := me.GetMasterX().Exec("DELETE FROM Sessions")
if err != nil {
return errors.Wrap(err, "failed to delete all Sessions")
}
@@ -208,7 +221,7 @@ func (me SqlSessionStore) RemoveAllSessions() error {
}
func (me SqlSessionStore) PermanentDeleteSessionsByUser(userId string) error {
_, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE UserId = :UserId", map[string]interface{}{"UserId": userId})
_, err := me.GetMasterX().Exec("DELETE FROM Sessions WHERE UserId = ?", userId)
if err != nil {
return errors.Wrapf(err, "failed to delete Session with userId=%s", userId)
}
@@ -217,7 +230,7 @@ func (me SqlSessionStore) PermanentDeleteSessionsByUser(userId string) error {
}
func (me SqlSessionStore) UpdateExpiresAt(sessionId string, time int64) error {
_, err := me.GetMaster().Exec("UPDATE Sessions SET ExpiresAt = :ExpiresAt, ExpiredNotify = false WHERE Id = :Id", map[string]interface{}{"ExpiresAt": time, "Id": sessionId})
_, err := me.GetMasterX().Exec("UPDATE Sessions SET ExpiresAt = ?, ExpiredNotify = false WHERE Id = ?", time, sessionId)
if err != nil {
return errors.Wrapf(err, "failed to update Session with sessionId=%s", sessionId)
}
@@ -225,7 +238,7 @@ func (me SqlSessionStore) UpdateExpiresAt(sessionId string, time int64) error {
}
func (me SqlSessionStore) UpdateLastActivityAt(sessionId string, time int64) error {
_, err := me.GetMaster().Exec("UPDATE Sessions SET LastActivityAt = :LastActivityAt WHERE Id = :Id", map[string]interface{}{"LastActivityAt": time, "Id": sessionId})
_, err := me.GetMasterX().Exec("UPDATE Sessions SET LastActivityAt = ? WHERE Id = ?", time, sessionId)
if err != nil {
return errors.Wrapf(err, "failed to update Session with id=%s", sessionId)
}
@@ -234,12 +247,10 @@ func (me SqlSessionStore) UpdateLastActivityAt(sessionId string, time int64) err
func (me SqlSessionStore) UpdateRoles(userId, roles string) (string, error) {
if len(roles) > model.UserRolesMaxLength {
return "", fmt.Errorf("Given session roles length (%d) exceeds max storage limit (%d)", len(roles), model.UserRolesMaxLength)
return "", fmt.Errorf("given session roles length (%d) exceeds max storage limit (%d)", len(roles), model.UserRolesMaxLength)
}
query := "UPDATE Sessions SET Roles = :Roles WHERE UserId = :UserId"
_, err := me.GetMaster().Exec(query, map[string]interface{}{"Roles": roles, "UserId": userId})
_, err := me.GetMasterX().Exec("UPDATE Sessions SET Roles = ? WHERE UserId = ?", roles, userId)
if err != nil {
return "", errors.Wrapf(err, "failed to update Session with userId=%s and roles=%s", userId, roles)
}
@@ -247,9 +258,9 @@ func (me SqlSessionStore) UpdateRoles(userId, roles string) (string, error) {
}
func (me SqlSessionStore) UpdateDeviceId(id string, deviceId string, expiresAt int64) (string, error) {
query := "UPDATE Sessions SET DeviceId = :DeviceId, ExpiresAt = :ExpiresAt, ExpiredNotify = false WHERE Id = :Id"
query := "UPDATE Sessions SET DeviceId = ?, ExpiresAt = ?, ExpiredNotify = false WHERE Id = ?"
_, err := me.GetMaster().Exec(query, map[string]interface{}{"DeviceId": deviceId, "Id": id, "ExpiresAt": expiresAt})
_, err := me.GetMasterX().Exec(query, deviceId, expiresAt, id)
if err != nil {
return "", errors.Wrapf(err, "failed to update Session with id=%s", id)
}
@@ -257,12 +268,19 @@ func (me SqlSessionStore) UpdateDeviceId(id string, deviceId string, expiresAt i
}
func (me SqlSessionStore) UpdateProps(session *model.Session) error {
_, err := me.GetMaster().Exec(`UPDATE Sessions
SET Props=:Props
WHERE Id=:Id`, map[string]interface{}{
"Props": model.MapToJSON(session.Props),
"Id": session.Id,
})
jsonProps, err := json.Marshal(session.Props)
if err != nil {
return errors.Wrap(err, "failed marshalling session props")
}
query, args, err := me.getQueryBuilder().
Update("Sessions").
Set("Props", string(jsonProps)).
Where(sq.Eq{"Id": session.Id}).
ToSql()
if err != nil {
errors.Wrap(err, "sessions_tosql")
}
_, err = me.GetMasterX().Exec(query, args...)
if err != nil {
return errors.Wrap(err, "failed to update Session")
}
@@ -270,14 +288,14 @@ func (me SqlSessionStore) UpdateProps(session *model.Session) error {
}
func (me SqlSessionStore) AnalyticsSessionCount() (int64, error) {
var count int64
query :=
`SELECT
COUNT(*)
FROM
Sessions
WHERE ExpiresAt > :Time`
count, err := me.GetReplica().SelectInt(query, map[string]interface{}{"Time": model.GetMillis()})
if err != nil {
WHERE ExpiresAt > ?`
if err := me.GetReplicaX().Get(&count, query, model.GetMillis()); err != nil {
return int64(0), errors.Wrap(err, "failed to count Sessions")
}
return count, nil
@@ -286,15 +304,15 @@ func (me SqlSessionStore) AnalyticsSessionCount() (int64, error) {
func (me SqlSessionStore) Cleanup(expiryTime int64, batchSize int64) error {
var query string
if me.DriverName() == model.DatabaseDriverPostgres {
query = "DELETE FROM Sessions WHERE Id IN (SELECT Id FROM Sessions WHERE ExpiresAt != 0 AND :ExpiresAt > ExpiresAt LIMIT :Limit)"
query = "DELETE FROM Sessions WHERE Id IN (SELECT Id FROM Sessions WHERE ExpiresAt != 0 AND ? > ExpiresAt LIMIT ?)"
} else {
query = "DELETE FROM Sessions WHERE ExpiresAt != 0 AND :ExpiresAt > ExpiresAt LIMIT :Limit"
query = "DELETE FROM Sessions WHERE ExpiresAt != 0 AND ? > ExpiresAt LIMIT ?"
}
var rowsAffected int64 = 1
for rowsAffected > 0 {
sqlResult, err := me.GetMaster().Exec(query, map[string]interface{}{"ExpiresAt": expiryTime, "Limit": batchSize})
sqlResult, err := me.GetMasterX().Exec(query, expiryTime, batchSize)
if err != nil {
return errors.Wrap(err, "unable to delete sessions")
}