Create the new networks for each site resource

This commit is contained in:
Owen
2026-04-21 16:13:22 -07:00
parent 5b18612426
commit 38243ad887
2 changed files with 104 additions and 0 deletions

View File

@@ -67,6 +67,25 @@ export default async function migration() {
`Found ${existingHealthChecks.length} existing targetHealthCheck row(s) to migrate`
);
// Query existing siteResources with siteId before the transaction recreates
// the table without that column. We use this data below to create a dedicated
// network for each resource.
const existingSiteResourcesForNetwork = db
.prepare(
`SELECT sr."siteResourceId", sr."orgId", sr."siteId"
FROM 'siteResources' sr
WHERE sr."siteId" IS NOT NULL`
)
.all() as {
siteResourceId: number;
orgId: string;
siteId: number;
}[];
console.log(
`Found ${existingSiteResourcesForNetwork.length} existing siteResource(s) to migrate to networks`
);
db.transaction(() => {
db.prepare(
`
@@ -315,6 +334,36 @@ export default async function migration() {
db.pragma("foreign_keys = ON");
// Create a dedicated network for each existing siteResource and link the
// old siteId via siteNetworks. Then set networkId and defaultNetworkId on
// the siteResource row so the app can use the new network model.
if (existingSiteResourcesForNetwork.length > 0) {
const insertNetwork = db.prepare(
`INSERT INTO 'networks' ("scope", "orgId") VALUES (?, ?)`
);
const insertSiteNetwork = db.prepare(
`INSERT INTO 'siteNetworks' ("siteId", "networkId") VALUES (?, ?)`
);
const updateSiteResource = db.prepare(
`UPDATE 'siteResources' SET "networkId" = ?, "defaultNetworkId" = ? WHERE "siteResourceId" = ?`
);
const migrateNetworks = db.transaction(() => {
for (const sr of existingSiteResourcesForNetwork) {
const result = insertNetwork.run("resource", sr.orgId);
const networkId = result.lastInsertRowid as number;
insertSiteNetwork.run(sr.siteId, networkId);
updateSiteResource.run(networkId, networkId, sr.siteResourceId);
}
});
migrateNetworks();
console.log(
`Migrated ${existingSiteResourcesForNetwork.length} siteResource(s) to networks`
);
}
// Re-insert targetHealthCheck rows with corrected IDs:
// targetHealthCheckId is set to the same integer as targetId (1:1 mapping),
// siteId and orgId are populated from the associated target and site.