diff --git a/src/features/ci-cd/hooks/service-installs.ts b/src/features/ci-cd/hooks/service-installs.ts index b919765ba0..923b20eea7 100644 --- a/src/features/ci-cd/hooks/service-installs.ts +++ b/src/features/ci-cd/hooks/service-installs.ts @@ -1,12 +1,7 @@ import _ from 'lodash'; import { sbvrUtils, hooks, permissions } from '@balena/pinejs'; import type { Filter, FilterObj } from 'pinejs-client-core'; -import type { - Device, - PickDeferred, - Service, - ServiceInstall, -} from '../../../balena-model'; +import type { Device, Service } from '../../../balena-model'; const createReleaseServiceInstalls = async ( api: sbvrUtils.PinejsClient, @@ -73,14 +68,6 @@ const createReleaseServiceInstalls = async ( resource: 'device', options: { $select: 'id', - $expand: { - service_install: { - $select: 'installs__service', - $filter: { - installs__service: { $in: serviceIds }, - }, - }, - }, $filter: { // Pass the device filters instead of IDs, since a using $in errors with `code: '08P01'` for more than 66k IDs. ...(Array.isArray(deviceFilterOrIds) @@ -96,28 +83,35 @@ const createReleaseServiceInstalls = async ( }), }, }, - })) as Array< - Pick & { - service_install: Array>; - } - >; + })) as Array>; + if (devicesToAddServiceInstalls.length === 0) { + return; + } + + const deviceIds = devicesToAddServiceInstalls.map((d) => d.id); - await api.passthrough.tx.executeSql.executeSql( + await api.passthrough.tx!.executeSql( `\ INSERT INTO "service install" ("device", "installs-service") -SELECT d."id", i."is a build of-service" +SELECT d."id" AS "device", s."id" AS "installs-service" FROM "device" d -JOIN "application" a ON a."id" = d."belongs to-application" -JOIN "release" r ON r."id" = COALESCE(d."should be running-release", a."should be running-release") -JOIN "image-is part of-release" iipor ON iipor."is part of-release" = r."id" -JOIN "image" i ON i."id" = iipor."image" -WHERE NOT EXISTS ( +CROSS JOIN "service" s +WHERE d."id" IN (${_.range(1, deviceIds.length + 1) + .map((i) => `$${i}`) + .join(',')}) +AND s."id" IN (${_.range( + deviceIds.length + 1, + deviceIds.length + serviceIds.length + 1, + ) + .map((i) => `$${i}`) + .join(',')}) +AND NOT EXISTS ( SELECT 1 FROM "service install" si WHERE si."device" = d."id" - AND si."installs-service" = i."is a build of-service" + AND si."installs-service" = s."id" ) ;`, - [request.resourceName, id], + [...deviceIds, ...serviceIds], ); };