Is there a way to insert data from one table into a MySQL Table in Drizzle and update the entry if it already exists?

My goal is to utilize Drizzle for inserting data into a table and updating it if the key already exists. In MySQL, the code would look like this:

INSERT INTO myTable1(field1,field2,field3,field4)
SELECT fieldOne,fieldTwo,fieldThree,fieldFour
FROM myTable2
  ON DUPLICATE KEY UPDATE 
    field3 = VALUES(field3),
    field4 = VALUES(field4);

For Drizzle-ORM, I expected something similar:

const insertUpdateTable = async (
    db: DBType,
    sourceTable: number, 
    targetTable: number,
) => {
    const sourceRecords = db.select({
        fieldOne: myTable2.fieldOne,
        fieldTwo: myTable2.fieldTwo,
        fieldThree: myTable2.fieldThree,
        fieldFour: myTable2.fieldFour
    })
    .from(myTable2);

    return await db.insert(myTable1)
        .values(sourceRecords)
        .onDuplicateKeyUpdate({
           set: {
                 field1: sourceRecords.fieldOne,
                 field2: sourceRecords.fieldTwo
           }
        })
}

However, WebStorm is indicating errors with my values(sourceRecords) statement and the onDuplicateKeyUpdate fields. My aim is to maintain type safety by using Drizzle rather than resorting to the Magic SQL operator. Any suggestions or advice?

Answer №1

Suddenly, the perfect resolution appeared before me.

await db.insert(newTable)
    .values(dataFromSource)
    .onDuplicateKeyUpdate({
       set: {
             column1: sql`VALUES(column1)`,
             column2: sql`column2`
       }
    })

While I'm accepting the incoming values for column 1, I'm maintaining the original value in column 2 of the final table.

There is a certain level of risk involved since the sql magic might not provide the type-safety measures that I desire.

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

Accessing and refining information stored locally

I have an array of phrases that I store in local storage. Upon page load, I perform filtering on this array. The issue arises when I reload the page and encounter a ReferenceError: localStorage is not defined. I attempted to address this problem by introd ...

I am looking for a way to convert the date format from "yyyy-MM-dd" to "dd-MM-yyyy" in NestJs

I need help with changing the date format from "yyyy-MM-dd" to "dd-MM-yyyy". Currently, my entity code looks like this: @IsOptional() @ApiProperty({ example: '1999-12-12', nullable: true }) @Column({ type: 'date', nullable: true } ...

What steps can I take to resolve this issue I'm encountering while using mongoose?

I'm currently in the process of creating a basic blog application to familiarize myself with next.js and mongoose. However, I've encountered an error message that reads as follows: "TypeError: mongoose__WEBPACK_IMPORTED_MODULE_0__.models is undef ...

next js element is automatically styled by default

I inserted my logo into the navbar and noticed that Next.js is automatically applying CSS to that element Upon inspecting the element, this is what I found: element.style { position: absolute; width: 0px; display: block; margin: auto; ...

How can Next.js 14 implement sending fingerprint data from the client to the server with every request?

I am capturing a user's fingerprint in the browser using the following code: "use client" import FingerprintJS from "@fingerprintjs/fingerprintjs" import { useCookies } from "next-client-cookies" import React from " ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

having difficulty configuring drizzle on express

When configuring the database connection with MySQL using drizzle, I encountered a puzzling situation. I am utilizing express and top-level await without async, but I'm unsure of how it all fits together. import { drizzle } from "drizzle-orm/mysq ...

Enhancing Navigation in NextJS with an Active Navbar

Attempting to apply a style to the active Navbar on NextJs, I have experimented with various approaches. I imported useRouter() from next/navigation It appears that this method is somewhat outdated. <li className='font-medium py-1 my-2&apo ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Is there a way to retrieve the number of swipe up interactions from Instagram story insights using the graph API

Is there a way to retrieve the swipe up count displayed in Instagram insights? Since Facebook does not provide this data through their Graph API, how can I access it? I have already tried scraping without success and I am looking for a solution using eith ...

Issue with MUI v5 Zoom transition causing transform to malfunction on :hover

While utilizing MUI transitions, specifically Zoom in my scenario, I noticed that the child element's on hover transform no longer takes effect. The '&:hover' property still functions as expected when changing the backgroundColor, howeve ...

Transforming the shopping cart with redux-saga

Hey there! I've been working on implementing a shopping cart feature using redux-saga. The current code seems to be functioning properly, but I have some concerns about the way I'm handling the cart state. It looks like I might be mutating the ca ...

How can a child value be transferred from a client component to a parent component on the server side?

I am facing a situation where a client-side component needs to send a value to its parent component which is server-side. I have tried using useState and other hooks, but so far it has been unsuccessful. Can anyone provide guidance on how to achieve this? ...

How can one implement closure in Angular 4?

I am looking to implement a nested function within another function in Angular 4 for closure. However, when attempting the code below, I encounter an error stating "cannot find name innerFn" outerFn(){ let a = "hello"; innerFn(){ console.log(a ...

The NgModule recognition system does not detect my library module

My AccordionModule within my Angular 2 library initially encountered a problem of not being recognized as an NgModule during the first compilation by angular-cli. However, it automatically reloaded after the error and was then successfully compiled with th ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

What could be the reason behind the absence of this.props.onLayout in my React Native component?

In my React Native app, I have the below class implemented with Typescript: class Component1 extends React.Component<IntroProps, {}> { constructor(props){ super(props) console.log(props.onLayout) } ... } The documentation for the View ...

Asynchronous waiting waits not for async await

I'm currently working on a function that loops through an array and updates the model for each ID, then adds the result to another array. This is the code snippet I have: async function getSortedAnimals() { var i = 0; var sortedAnimals = []; id ...

Nextjs: Issues with Dropdown functionality when using group and group-focus with TailwindCSS

My goal is to make an array visible once a button is clicked. By default, the array should be invisible, similar to drop-down menus in menu bars. I am utilizing the group and group-focus classes. While the array disappears as expected, it does not reappear ...