Skip to content

Commit bed0602

Browse files
author
Ajay Kelkar
committed
refactor: use sqlcon for error handling; add comments
1 parent 4aff50f commit bed0602

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

persistence/sql/persister_session.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package sql
22

33
import (
44
"context"
5-
"database/sql"
65
"fmt"
76
"time"
87

@@ -77,14 +76,17 @@ func (p *Persister) ListSessionsByIdentity(ctx context.Context, iID uuid.UUID, a
7776
return s, nil
7877
}
7978

79+
// UpsertSession creates a session if not found else updates.
80+
// This operation also inserts Session device records when a session is being created.
81+
// The update operation skips updating Session device records since only one record would need to be updated in this case.
8082
func (p *Persister) UpsertSession(ctx context.Context, s *session.Session) error {
8183
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.UpsertSession")
8284
defer span.End()
8385

8486
s.NID = p.NetworkID(ctx)
8587

8688
return errors.WithStack(p.Transaction(ctx, func(ctx context.Context, tx *pop.Connection) error {
87-
if err := tx.Find(new(session.Session), s.ID); errors.Is(err, sql.ErrNoRows) {
89+
if err := sqlcon.HandleError(tx.Where("id = ? AND nid = ?", s.ID, s.NID).First(new(session.Session))); errors.Is(err, sqlcon.ErrNoRows) {
8890
// This must not be eager or identities will be created / updated
8991
if err := sqlcon.HandleError(tx.Create(s)); err != nil {
9092
return err
@@ -95,7 +97,7 @@ func (p *Persister) UpsertSession(ctx context.Context, s *session.Session) error
9597
device.SessionID = s.ID
9698
device.NID = s.NID
9799

98-
if err := tx.Create(device); err != nil {
100+
if err := sqlcon.HandleError(tx.Create(device)); err != nil {
99101
return err
100102
}
101103

@@ -104,10 +106,11 @@ func (p *Persister) UpsertSession(ctx context.Context, s *session.Session) error
104106

105107
return nil
106108
} else if err != nil {
107-
return errors.WithStack(err)
109+
return err
108110
}
109111

110112
// This must not be eager or identities will be created / updated
113+
// Only update session and not corresponding session device records
111114
return tx.Update(s)
112115
}))
113116
}

0 commit comments

Comments
 (0)