Skip to content

Commit 1ab03e2

Browse files
committed
Improve query performance
1 parent 65fbf44 commit 1ab03e2

File tree

3 files changed

+53
-31
lines changed

3 files changed

+53
-31
lines changed

cli/testdata/coder_list_--output_json.golden

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@
3535
"file_id": "[workspace build file ID]",
3636
"tags": {
3737
"scope": "organization"
38-
}
38+
},
39+
"queue_position": 1,
40+
"queue_size": 0
3941
},
4042
"reason": "initiator",
4143
"resources": [],

coderd/database/queries.sql.go

Lines changed: 25 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/queries/provisionerjobs.sql

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,33 @@ WHERE
4848
id = ANY(@ids :: uuid [ ]);
4949

5050
-- name: GetProvisionerJobsByIDsWithQueuePosition :many
51+
WITH unstarted_jobs AS (
52+
SELECT
53+
id, created_at
54+
FROM
55+
provisioner_jobs
56+
WHERE
57+
started_at IS NULL
58+
),
59+
queue_position AS (
60+
SELECT
61+
id,
62+
ROW_NUMBER() OVER (ORDER BY created_at) AS queue_position
63+
FROM
64+
unstarted_jobs
65+
),
66+
queue_size AS (
67+
SELECT COUNT(*) as count FROM unstarted_jobs
68+
)
5169
SELECT
52-
sqlc.embed(pj),
53-
COALESCE(a.queue_position, 0) AS queue_position,
54-
COALESCE(a.queue_size, 0) AS queue_size
70+
sqlc.embed(pj),
71+
COALESCE(qp.queue_position, 0) AS queue_position,
72+
COALESCE(qs.count, 0) AS queue_size
5573
FROM
56-
provisioner_jobs pj
57-
LEFT JOIN (
58-
SELECT
59-
id,
60-
ROW_NUMBER() OVER (ORDER BY created_at) AS queue_position,
61-
COUNT(*) OVER (PARTITION BY started_at IS NULL) AS queue_size
62-
FROM
63-
provisioner_jobs
64-
WHERE
65-
started_at IS NULL
66-
GROUP BY id
67-
) a ON a.id = pj.id
74+
provisioner_jobs pj
75+
LEFT JOIN
76+
queue_position qp ON qp.id = pj.id
77+
LEFT JOIN queue_size qs ON TRUE
6878
WHERE pj.id = ANY(@ids :: uuid [ ]);
6979

7080
-- name: GetProvisionerJobsCreatedAfter :many

0 commit comments

Comments
 (0)