@@ -61,19 +61,10 @@ FROM agent_stats_by_interval_and_user;
61
61
-- GetTemplateAppInsights returns the aggregate usage of each app in a given
62
62
-- timeframe. The result can be filtered on template_ids, meaning only user data
63
63
-- from workspaces based on those templates will be included.
64
- WITH ts AS (
65
- SELECT
66
- d::timestamptz AS from_,
67
- (d::timestamptz + ' 5 minute' ::interval) AS to_,
68
- EXTRACT(epoch FROM ' 5 minute' ::interval) AS seconds
69
- FROM
70
- -- Subtract 1 second from end_time to avoid including the next interval in the results.
71
- generate_series(@start_time::timestamptz , (@end_time::timestamptz ) - ' 1 second' ::interval, ' 5 minute' ::interval) d
72
- ), app_stats_by_user_and_agent AS (
64
+ WITH app_stats_by_user_and_agent AS (
73
65
SELECT
74
- ts .from_ ,
75
- ts .to_ ,
76
- ts .seconds ,
66
+ s .start_time ,
67
+ 60 as seconds,
77
68
w .template_id ,
78
69
was .user_id ,
79
70
was .agent_id ,
@@ -82,12 +73,7 @@ WITH ts AS (
82
73
wa .display_name ,
83
74
wa .icon ,
84
75
(wa .slug IS NOT NULL )::boolean AS is_app
85
- FROM ts
86
- JOIN workspace_app_stats was ON (
87
- (was .session_started_at >= ts .from_ AND was .session_started_at < ts .to_ )
88
- OR (was .session_ended_at > ts .from_ AND was .session_ended_at < ts .to_ )
89
- OR (was .session_started_at < ts .from_ AND was .session_ended_at >= ts .to_ )
90
- )
76
+ FROM workspace_app_stats was
91
77
JOIN workspaces w ON (
92
78
w .id = was .workspace_id
93
79
AND CASE WHEN COALESCE(array_length(@template_ids::uuid[], 1 ), 0 ) > 0 THEN w .template_id = ANY(@template_ids::uuid[]) ELSE TRUE END
@@ -98,7 +84,20 @@ WITH ts AS (
98
84
wa .agent_id = was .agent_id
99
85
AND wa .slug = was .slug_or_port
100
86
)
101
- GROUP BY ts .from_ , ts .to_ , ts .seconds , w .template_id , was .user_id , was .agent_id , was .access_method , was .slug_or_port , wa .display_name , wa .icon , wa .slug
87
+ -- This table contains both 1 minute entries and >1 minute entries,
88
+ -- to calculate this with our uniqueness constraints, we generate series
89
+ -- for the longer intervals.
90
+ CROSS JOIN LATERAL generate_series(
91
+ date_trunc(' minute' , was .session_started_at ),
92
+ -- Subtract 1 microsecond to avoid creating an extra series.
93
+ date_trunc(' minute' , was .session_ended_at - ' 1 microsecond' ::interval),
94
+ ' 1 minute' ::interval
95
+ ) s(start_time)
96
+ WHERE
97
+ s .start_time >= @start_time::timestamptz
98
+ -- Subtract one minute because the series only contains the start time.
99
+ AND s .start_time < (@end_time::timestamptz ) - ' 1 minute' ::interval
100
+ GROUP BY s .start_time , w .template_id , was .user_id , was .agent_id , was .access_method , was .slug_or_port , wa .display_name , wa .icon , wa .slug
102
101
)
103
102
104
103
SELECT
0 commit comments