@@ -2,7 +2,6 @@ package sql
2
2
3
3
import (
4
4
"context"
5
- "database/sql"
6
5
"fmt"
7
6
"time"
8
7
@@ -77,14 +76,17 @@ func (p *Persister) ListSessionsByIdentity(ctx context.Context, iID uuid.UUID, a
77
76
return s , nil
78
77
}
79
78
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.
80
82
func (p * Persister ) UpsertSession (ctx context.Context , s * session.Session ) error {
81
83
ctx , span := p .r .Tracer (ctx ).Tracer ().Start (ctx , "persistence.sql.UpsertSession" )
82
84
defer span .End ()
83
85
84
86
s .NID = p .NetworkID (ctx )
85
87
86
88
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 ) {
88
90
// This must not be eager or identities will be created / updated
89
91
if err := sqlcon .HandleError (tx .Create (s )); err != nil {
90
92
return err
@@ -95,7 +97,7 @@ func (p *Persister) UpsertSession(ctx context.Context, s *session.Session) error
95
97
device .SessionID = s .ID
96
98
device .NID = s .NID
97
99
98
- if err := tx .Create (device ); err != nil {
100
+ if err := sqlcon . HandleError ( tx .Create (device ) ); err != nil {
99
101
return err
100
102
}
101
103
@@ -104,10 +106,11 @@ func (p *Persister) UpsertSession(ctx context.Context, s *session.Session) error
104
106
105
107
return nil
106
108
} else if err != nil {
107
- return errors . WithStack ( err )
109
+ return err
108
110
}
109
111
110
112
// This must not be eager or identities will be created / updated
113
+ // Only update session and not corresponding session device records
111
114
return tx .Update (s )
112
115
}))
113
116
}
0 commit comments