Skip to content

Commit 19d5524

Browse files
committed
fix(gluwave): ⚡ improve sql query performance
1 parent 682930e commit 19d5524

File tree

1 file changed

+37
-24
lines changed

1 file changed

+37
-24
lines changed

gluwave/src/lib/cob.ts

+37-24
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,44 @@ async function getSafeStartTime(
88
inputTime: Date,
99
userId: string
1010
): Promise<Date> {
11-
const data = await db.select({
12-
timestamp: sql` timestamp
13-
`.mapWith(glucose.timestamp),
14-
}).from(sql`(
11+
const [data] = await db
12+
.select({
13+
timestamp: sql`max`.mapWith(glucose.timestamp).as('timestamp'),
14+
})
15+
.from(
16+
sql`
17+
(
18+
WITH timeline AS (
19+
SELECT
20+
-1 AS direction,
21+
timestamp
22+
FROM carbs
23+
WHERE carbs.user_id = ${userId}
24+
UNION ALL
1525
SELECT
16-
glucose.timestamp
17-
FROM (
18-
SELECT
19-
timestamp,
20-
LEAD(timestamp) OVER (PARTITION BY user_id ORDER BY timestamp) as next_timestamp,
21-
user_id
22-
FROM glucose
23-
) as glucose LEFT JOIN carbs
24-
ON carbs.timestamp <= next_timestamp
25-
AND carbs.timestamp + MAKE_INTERVAL(mins => (carbs.decay * 1.5)::integer) >= glucose.timestamp
26-
AND carbs.user_id = glucose.user_id
27-
WHERE glucose.user_id = ${userId}
28-
AND glucose.timestamp <= ${inputTime.toISOString()}
29-
GROUP BY glucose.timestamp
30-
HAVING COUNT(carbs.id) = 0
31-
ORDER BY glucose.timestamp DESC
32-
LIMIT 1
33-
)`)
34-
35-
return data[0]?.timestamp ?? inputTime
26+
1 as direction,
27+
timestamp + MAKE_INTERVAL(mins => (carbs.decay * 1.5)::int) as timestamp
28+
FROM carbs
29+
WHERE carbs.user_id = ${userId}
30+
), concurrent AS (
31+
SELECT
32+
SUM(direction) OVER (order by timestamp desc rows between unbounded preceding and current row) as overlapping,
33+
timestamp
34+
FROM timeline
35+
), non_concurrent AS (
36+
SELECT MAX(timestamp) FROM concurrent
37+
WHERE overlapping = 0
38+
AND timestamp < ${inputTime.toISOString()}
39+
)
40+
41+
SELECT MAX(timestamp) FROM glucose
42+
WHERE timestamp < (SELECT * FROM non_concurrent)
43+
AND glucose.user_id = ${userId}
44+
)
45+
`
46+
)
47+
48+
return data?.timestamp ?? inputTime
3649
}
3750

3851
// Function to check if a meal is active

0 commit comments

Comments
 (0)