From 4bf174a09c8c267399a53ac330f8aa9a19b1536e Mon Sep 17 00:00:00 2001 From: Rizky Date: Wed, 9 Oct 2024 14:16:03 +0700 Subject: [PATCH] fix batch upsert --- pkgs/api/_dbs.ts | 3 ++- pkgs/index.ts | 1 + pkgs/utils/query.ts | 10 +++++++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/pkgs/api/_dbs.ts b/pkgs/api/_dbs.ts index aae6412..cdceee5 100644 --- a/pkgs/api/_dbs.ts +++ b/pkgs/api/_dbs.ts @@ -8,7 +8,8 @@ export const _ = { url: "/_dbs/*", raw: true, async api() { - const { req, res } = apiContext(this); + const ctx = apiContext(this); + const { req, res } = ctx; if (typeof g.db !== "undefined") { if (req.params._ === "check") { return { mode: "encrypted" }; diff --git a/pkgs/index.ts b/pkgs/index.ts index fa45339..b68fc42 100644 --- a/pkgs/index.ts +++ b/pkgs/index.ts @@ -11,6 +11,7 @@ import { prepareAPITypes } from "./server/prep-api-ts"; import { config } from "./utils/config"; import { g } from "./utils/global"; import { createLogger } from "./utils/logger"; +import { execQuery } from "utils/query"; if (process.argv[process.argv.length - 1] === "skip_types") { g.skip_build_types = true; diff --git a/pkgs/utils/query.ts b/pkgs/utils/query.ts index c445b41..fab9009 100644 --- a/pkgs/utils/query.ts +++ b/pkgs/utils/query.ts @@ -194,7 +194,8 @@ export const execQuery = async (args: DBArg, prisma: any) => { const marker = {} as any; for (const row of data) { - const found = existing.find((item, idx) => { + + let found = existing.find((item, idx) => { for (const pk of pks) { if (item[pk.name] !== row[pk.name]) return false; } @@ -202,6 +203,12 @@ export const execQuery = async (args: DBArg, prisma: any) => { return true; }); + if (!found) { + for (const pk of pks) { + if (row[pk.name]) found = row; + } + } + for (const [k, v] of Object.entries(row) as any) { const rel = rels[k]; if (rel) { @@ -291,6 +298,7 @@ export const execQuery = async (args: DBArg, prisma: any) => { } } + if (updates.length > 0) { for (const row of updates) { const where = {} as any;