Applying ORM Drizzle in cases of conflict

Here's where I'm currently at: If I use onConflictDoNothing, the plan is to insert a new record into the database. However, if a record with the same userId and provider already exists, and the apiKey of the existing record is not equal to the apiKey of the new record, the insert operation is skipped without throwing an error.

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

I encountered a 500 error code that reads:

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

I suspect this error occurs because a where clause cannot be used in the do nothing option.

So, I tried using the onConflictDoUpdate option to insert a new record in the database. If a record with the same userId and provider already exists, and the apiKey of the existing record is not equal to the apiKey of the new record, then the existing record is updated with the new apiKey. If they are equal, the insert operation is skipped without any errors being thrown.

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

The error message I received for this attempt was:

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

It seems like I am close to the solution but missing something crucial. My goal is to avoid having duplicate entries for api keys.

Answer №1

To ensure data integrity, it is imperative to establish a compound unique relationship within your database schema:

export const table = pgTable("table", {
    id: serial("id").primaryKey(),
    ...schema
}, (t) => ({
    unq: unique("compound_unique_relation_name").on(t.column1, t.column2)
}));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The call in TypeScript React does not match any overload

Encountering an error with a React component that I wrote and seeking assistance. The primary component code snippet: export interface ICode { code: (code: string) => void; } export default class UserCode extends React.Component{ state = { formFil ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

When trying to debug the client of a NextJS 12 app in VSCode, breakpoints refuse to be hit

Having trouble debugging NextJS 12 apps in VSCode. Breakpoints not triggering upon browser reload. To create a default NextJS 12 app, use: $ npx create-next-app@latest. Create the launch.json using https://nextjs.org/docs/advanced-features/debugging: { ...

Why are my class data types not aligning with JSON objects?

In my Node.js project using TypeScript, I have defined the Tariff and Tariffs classes. I also generated fake data in JSON format that should align with these Classes. However, I encountered an error in the resolve() method stating: Argument of type &apo ...

Reimagine server-side storage options as an alternative to remixing JavaScript local storage

My remix application is designed to serve as a frontend. I retrieve data from the backend and sometimes need to load specific data only once and reuse it across multiple pages. In our previous frontend setup, we utilized localstorage; however, with the cur ...

The term 'Pick' is typically used to identify a specific type, however, in this particular situation, it appears to be functioning as a value while attempting to expand the Pick

I'm attempting to selectively expose certain properties from an ancestor class on my descendant class. My approach involves using the Pick utility in TypeScript. export class Base { public a; public b; public c; } export class PartialDes ...

Triggering a class in Angular when another class is activated through JavaScript

My goal is to apply the class "xyz" when the class "xy" is activated using ngClass. I am looking to achieve the following scenario: If the class "xyz" is present in the tag, then activate the class "xy" Using ngClass="'xyz', 'xy'" ...

Is there a way to retrieve the date of the most recent occurrence of a specific "day" in TypeScript?

Looking to retrieve the date (in YYYY-MM-DD format) for the most recent "Wednesday", "Saturday", or any user-specified day. This date could be from either this week or last week, with the most recent occurrence of that particular day. For instance, if toda ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

What are the issues causing trouble for my modules, services, and more in Angular ^17?

As I was going through the themes, I couldn't find a similar question. My issue revolves around Angular's inability to locate modules and services that are created using "ng g". Everything seems to be correctly set up, but errors or warnings keep ...

Exposing the method to the outside world by making it public in

I have a situation where I have a base class with a protected method called foo, and a child class that needs to make this method publicly accessible. Since this method will be called frequently, I am looking for a more efficient solution to avoid unnecess ...

I encountered a permission denied error while attempting to execute the command npm install -g tsc

My main objective is to convert TypeScript code to JavaScript. However, when I attempted to install the TypeScript compiler globally using 'npm install -g tsc', I encountered the following error: npm ERR! Error: EACCES: permission denied, rename ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

How come TypeScript does not generate an error when attempting to import a default export that does not exist?

As I work on converting my code from non-TypeScript CommonJS files to TypeScript ES6 modules, I encountered an issue with the import statements. Specifically, I needed to use import * as x instead of import x: The original snippet looked like this: const ...

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

Nginx Experiencing Persistent Failures Due to 'Signal' Issue

Currently, we have a DigitalOcean machine running on 5.15.0-100-generic #110-Ubuntu, hosting multiple NextJS frontends and a NodeJS backend through PM2 on various localhost ports. These projects are accessible via different subdomains of the main domain wi ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

What causes the oninput event to act differently in Angular as opposed to regular JavaScript?

As I delve into learning Angular with TypeScript, I've encountered some inconsistencies compared to JavaScript that are puzzling me. Take for example this function that works flawlessly with pure JavaScript, where it dynamically sets the min and max a ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...

The Node.js application successfully operates on a local environment, however encounters issues when attempting to run on docker resulting in an error message stating "sh

Despite successfully building the docker image, I am facing difficulties getting the container to run. Below is the content of the package.json file: { "name": "linked-versions-viewer", "version": "1.0.0", &quo ...