diff --git a/internal/db/schema/migrations/oss/postgres/28/01_session_create_time_idx.up.sql b/internal/db/schema/migrations/oss/postgres/28/01_session_create_time_idx.up.sql new file mode 100644 index 000000000..e60b8ffdb --- /dev/null +++ b/internal/db/schema/migrations/oss/postgres/28/01_session_create_time_idx.up.sql @@ -0,0 +1,11 @@ +begin; +-- Session list queries always use an order by on create_time. +-- This index can aide in performing this order by. +create index + session_create_time +on + session (create_time); + +analyze session; + +commit; diff --git a/internal/session/query.go b/internal/session/query.go index 541c4b475..7a10af70f 100644 --- a/internal/session/query.go +++ b/internal/session/query.go @@ -126,13 +126,22 @@ select public_id, scope_id, user_id from session ` sessionList = ` -select * -from - (select public_id from session %s) s, - session_list ss -where - s.public_id = ss.public_id +with +session_ids as ( + select public_id + from session as s + -- where clause is constructed %s + -- order by clause is constructed + %s + -- limit is constructed + %s +) +select * +from session_list +where + session_list.public_id in (select * from session_ids) +-- order by clause again since order from cte is not guaranteed to be preserved %s ; ` diff --git a/internal/session/repository_session.go b/internal/session/repository_session.go index f1d5dbcd5..d16edfa21 100644 --- a/internal/session/repository_session.go +++ b/internal/session/repository_session.go @@ -319,10 +319,10 @@ func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Sessio var whereClause string if len(where) > 0 { - whereClause = " and " + strings.Join(where, " and ") + whereClause = " where " + strings.Join(where, " and ") } q := sessionList - query := fmt.Sprintf(q, limit, whereClause, withOrder) + query := fmt.Sprintf(q, whereClause, withOrder, limit, withOrder) rows, err := r.reader.Query(ctx, query, args) if err != nil {