@@ -151,26 +151,41 @@ SET
151
151
deleted = true,
152
152
updated_at = @updated_at
153
153
FROM
154
- (SELECT active_version_id FROM templates WHERE id = @template_id) AS active_version
154
+ -- Delete all versions that are returned from this query.
155
+ (
156
+ SELECT
157
+ id
158
+ FROM
159
+ -- Scope a prune to a single template and ignore already deleted template versions
160
+ (SELECT * FROM template_versions WHERE template_id = @template_id AND deleted = false) AS template_versions
161
+ LEFT JOIN
162
+ provisioner_jobs ON template_versions .job_id = provisioner_jobs .id
163
+ LEFT JOIN
164
+ templates ON template_versions .template_id = templates .id
165
+ WHERE
166
+ -- Actively used template versions (meaning the latest build is using
167
+ -- the version) are never pruned. A "restart" command on the workspace,
168
+ -- even if failed, would use the version. So it cannot be pruned until
169
+ -- the build is outdated.
170
+ -- TODO: This is an issue for "deleted workspaces", since a deleted workspace
171
+ -- has a build with the transition "delete". This will prevent that template
172
+ -- version from ever being pruned. We need a method to prune deleted workspaces.
173
+ template_versions .id != ANY(
174
+ SELECT DISTINCT ON (workspace_id)
175
+ template_version_id
176
+ FROM
177
+ workspace_builds
178
+ ORDER BY build_number DESC
179
+ )
180
+ -- Also never delete the active template version
181
+ AND active_version_id != template_versions .id
182
+ AND CASE
183
+ WHEN @job_status != ' ' THEN
184
+ provisioner_jobs .job_status = @job_status
185
+ ELSE
186
+ true
187
+ END
188
+
189
+ ) AS deleted_versions
155
190
WHERE
156
- -- Actively used template versions (meaning the latest build is using
157
- -- the version) are never pruned. A "restart" command on the workspace,
158
- -- even if failed, would use the version. So it cannot be pruned until
159
- -- the build is outdated.
160
- -- TODO: This is an issue for "deleted workspaces", since a deleted workspace
161
- -- has a build with the transition "delete". This will prevent that template
162
- -- version from ever being pruned. We need a method to prune deleted workspaces.
163
- template_versions .id != ANY(
164
- SELECT DISTINCT ON (workspace_id)
165
- template_version_id
166
- FROM
167
- workspace_builds
168
- ORDER BY build_number DESC
169
- )
170
- -- Also never delete the active template version
171
- AND template_versions .id != ANY(active_version)
172
- -- Ignore already deleted versions.
173
- AND template_versions .deleted = false
174
- -- Scope a prune to a single template.
175
- AND template_id = @template_id :: uuid
176
- RETURNING id;
191
+ id = ANY(deleted_versions);
0 commit comments