在冲突上使用 ORM

问题描述 投票:0回答:1

好吧,这就是我现在所在的地方。 如果我尝试 onConflictDoNothing ,计划是将新记录插入数据库。如果已经存在具有相同userId和provider的记录,并且现有记录的apiKey不等于新记录的apiKey,则跳过插入操作,并且不会抛出错误。

  .onConflictDoNothing({
    target: [userId, newSettingInfo.provider],
    where: sql`${settingInfo.apiKey} != ${newSettingInfo.apiKey}`,
  })

我收到 500 错误代码,上面写着

NeonDbError: syntax error at or near "where"
    at execute 

我非常确定这是因为我无法在“不执行任何操作”选项中使用 where 子句。

所以我尝试使用 onConflictDoUpdate 选项在数据库中插入新记录。如果已经存在具有相同userId和provider的记录,并且现有记录的apiKey不等于新记录的apiKey,则使用新记录的apiKey更新现有记录。如果它们相等,则跳过插入操作并且不会抛出错误。

.onConflictDoUpdate({
    target: [settingInfo.userId, settingInfo.provider],
    set: {
      apiKey: newSettingInfo.apiKey,
    },
    where: sql`${settingInfo.apiKey} != ${newSettingInfo.apiKey}`,
  })

我得到的错误是

NeonDbError: there is no unique or exclusion constraint matching the ON CONFLICT specification
    at execute 
}

所以我觉得我很接近,但我显然错过了一些东西。

避免重复的 API 密钥条目

typescript next.js drizzle-orm
1个回答
0
投票
You need to create a compound unique relation in your schema
export const table = pgTable("table", {
    id: serial("id").primaryKey(),
    ...schema
}, (t) => ({
    unq: unique("unique_relation_name").on(t.column1, t.column2)
}));

I hope this will help
© www.soinside.com 2019 - 2024. All rights reserved.