feat: resolved locking of membership table

This commit is contained in:
=
2025-10-24 20:38:08 +05:30
parent 3ea4ebe101
commit c33935e5e1
@@ -3,6 +3,7 @@ import { Knex } from "knex";
import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists"; import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";
import { AccessScope, TableName } from "../schemas"; import { AccessScope, TableName } from "../schemas";
import { chunkArray } from "@app/lib/fn";
export async function up(knex: Knex): Promise<void> { export async function up(knex: Knex): Promise<void> {
const hasParentOrgId = await knex.schema.hasColumn(TableName.Organization, "parentOrgId"); const hasParentOrgId = await knex.schema.hasColumn(TableName.Organization, "parentOrgId");
@@ -29,19 +30,38 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE"); t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
}); });
await knex.raw( const identityMemberships = await knex(TableName.Membership)
` .where({
UPDATE ?? AS identity scope: AccessScope.Organization
SET "orgId" = membership."scopeOrgId" })
FROM ?? AS membership .whereNotNull("actorIdentityId")
WHERE .select("actorIdentityId", "scopeOrgId");
membership."actorIdentityId" = identity."id"
AND membership."scope" = ?
`,
[TableName.Identity, TableName.Membership, AccessScope.Organization]
);
await knex.raw(`DELETE FROM ?? WHERE "orgId" IS NULL`, [TableName.Identity]); const identityToOrgMapping: Record<string, string> = {};
identityMemberships.forEach((el) => {
if (el.actorIdentityId) {
identityToOrgMapping[el.actorIdentityId] = el.scopeOrgId;
}
});
const batchMemberships = chunkArray(identityMemberships, 500);
for await (const membership of batchMemberships) {
const identityIds = membership.map((el) => el.actorIdentityId).filter(Boolean) as string[];
if (identityIds.length) {
const identities = await knex(TableName.Identity).whereIn("id", identityIds).select("*");
await knex(TableName.Identity)
.insert(
identities.map((el) => ({
...el,
orgId: identityToOrgMapping[el.id]
}))
)
.onConflict("id")
.merge();
}
}
await knex(TableName.Identity).whereNull("orgId").delete();
await knex.schema.alterTable(TableName.Identity, (t) => { await knex.schema.alterTable(TableName.Identity, (t) => {
t.uuid("orgId").notNullable().alter(); t.uuid("orgId").notNullable().alter();