Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

- handle conflicts instead of deleting old mappings

Gaurav Bhatt8eaf79082f79
diff --git a/packages/database/supabase/functions/sync/index.ts b/packages/database/supabase/functions/sync/index.ts
index e80560d3f8..dca537b309 100644
--- a/packages/database/supabase/functions/sync/index.ts
+++ b/packages/database/supabase/functions/sync/index.ts
@@ -416,20 +416,7 @@ serve(async (req: Request) => {
.where("id", "=", itemId)
.execute();
- // Upsert OnShape mapping
- await trx
- .deleteFrom("externalIntegrationMapping")
- .where("entityType", "=", "item")
- .where("integration", "=", "onshapeData")
- .where("companyId", "=", companyId)
- .where((eb) =>
- eb.or([
- eb("entityId", "=", itemId),
- eb("externalId", "=", externalPartId),
- ])
- )
- .execute();
-
+ // Upsert OnShape mapping — update if this entity already has a mapping
await trx
.insertInto("externalIntegrationMapping")
.values({
@@ -441,6 +428,14 @@ serve(async (req: Request) => {
companyId,
allowDuplicateExternalId: false,
})
+ .onConflict((oc) =>
+ oc
+ .columns(["entityType", "entityId", "integration", "companyId"])
+ .doUpdateSet({
+ externalId: externalPartId,
+ metadata: data.data,
+ })
+ )
.execute();
} else {
// Check if we've already created this part in this transaction
@@ -467,17 +462,8 @@ serve(async (req: Request) => {
itemId = item?.id;
- // Create OnShape mapping for the new item
+ // Upsert OnShape mapping for the new item
if (itemId) {
- // Delete any stale mapping with the same externalId
- await trx
- .deleteFrom("externalIntegrationMapping")
- .where("integration", "=", "onshapeData")
- .where("externalId", "=", externalPartId)
- .where("entityType", "=", "item")
- .where("companyId", "=", companyId)
- .execute();
-
await trx
.insertInto("externalIntegrationMapping")
.values({
@@ -489,6 +475,14 @@ serve(async (req: Request) => {
companyId,
allowDuplicateExternalId: false,
})
+ .onConflict((oc) =>
+ oc
+ .columns(["integration", "externalId", "entityType", "companyId"])
+ .doUpdateSet({
+ entityId: itemId,
+ metadata: data.data,
+ })
+ )
.execute();
}