Drizzle ORM does not offer support for the Insert Returning feature

I am facing a query while utilizing Drizzle ORM with MySQL.

At present, Drizzle ORM lacks an insert returning function for MySQL. Feel free to refer to this link for more information.

My platform registers users into the system and generates JWT tokens upon signup. As the JWT payload requires the user's id, it is crucial to retrieve the id of the recently added user.

In this scenario, how can I obtain the auto-incremented integer id for the newly inserted record?

Answer №1

Drizzle ORM lacks support for the returning function with MySQL, but it offers a workaround by utilizing the insertId property to obtain the auto-incremented ID.

For example:

const newUser = await db.insert(user).values({ name: "Jorge"})


const newWallet = await db.insert(wallet).values({ userId: newUser.insertId})

Answer №2

Based on information found in the Drizzle Documentation

When using the insert method with Drizzle, you can retrieve inserted rows by calling the returning() function.

// Example of retrieving all inserted rows
await db.insert(users).values({ name: "Dan" }).returning();

// Limiting return to specific data
await db.insert(users).values({ name: "Partial Dan" }).returning({ insertedId: users.id });

To access a single value from the results, you could do the following:

const newUser = await db.insert(users).values({ name: "Partial Dan" }).returning({ insertedId: users.id });

return newUser[0];

NOTE: This feature is compatible with PostgreSQL and SQLite but NOT with MySQL. Apologies for any confusion caused.

Answer №3

To effectively handle the ResultSetHeader, it is recommended to parse it as follows:

await this.db.insert(users).values({"login": "xxxx"})

This operation will yield the insertId:

[
  ResultSetHeader {
    fieldCount: 0,
    affectedRows: 1,
    insertId: 33,
    info: '',
    serverStatus: 2,
    warningStatus: 0,
    changedRows: 0
  },
  undefined
]

Note: Starting from version 0.32.0, you have the option to utilize the $returningId() method for automatically receiving individual inserted IDs:

const result = await db.insert(users).values([{ name: 'John' }, { name: 'John1' }]).$returningId(); 
//    ^? { id: number }[]

Answer №4

When the Drizzle ORM lacks a built-in insert returning function for MySQL, there are alternative methods to obtain the auto-incremented ID of a newly added user. Here are a few common solutions:

Utilize the LAST_INSERT_ID() function: After inserting the new user record into the database, you can use the LAST_INSERT_ID() function in MySQL to retrieve the auto-incremented ID of the last inserted record within the current session.

For example:

// Assuming you have a MySQL database connection or query execution method named "executeQuery" const result = await executeQuery(

INSERT INTO users (username, email, password)  VALUES ('new_user', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd1dac8e0caccdacdffdac7ded2cfd3da91dcd0d2">[email protected]</a>', 'hashed_password'); SELECT LAST_INSERT_ID() as id;
);

const newUserId = result[0][0].id; // Utilize the "newUserId" in your JWT payload or wherever needed.

Answer №5

It appears that the provided solution may not be accurate; here is an alternative way to retrieve the inserted ID in Drizzle version 0.30.7.

const updatedUser = await db.insert(schema.users).values({ email: email, username: username, password: password })
return updatedUser[0].insertId;

Answer №6

Currently utilizing drizzle version 0.30.10 in conjunction with MySql, which includes functionality for retrieving the insertId from the returned object.

const newUser = await db.insert(schema.users).values({ email: email, username: username, password: password })
return newUser[0].insertId;

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

What could be causing the Angular/TypeScript model that I imported to fail to properly map to my service within my Angular application?

Struggling with implementing a system for manual entry of mutual fund information, I am running into errors when trying to read properties from the 'fund' model in my application. The Developer Tools console is displaying the following error mess ...

Angular2 app fails to update after emitting an event

I need help with a child component responsible for updating phone numbers on a webpage. The goal is for the application to automatically display the changed phone number once the user hits the 'save' button. Here's a visual of how the appli ...

Unable to launch MySql service due to issues with ibdata1 file recovery

Following a ransomware attack by international hackers on one of our servers, we had to start over. The only untouched data we have is the ibdata1 file stored in the mysql program data folder. We are trying to restore this data onto a new instance to resu ...

Encountering an error when trying to add a new row due to a trigger in

I am facing an issue with updating the Available_Quantity column in the model_detail table based on new entries in the model_stock table. Here are the details of the two tables: `model_detail` table columns: `id`, `model_id`, `productName`, `Color`, `Ava ...

Unlocking the Secrets of Printing MySQL Data

I am currently faced with the challenge of displaying an MySQL table on screen with a border using PHP, but being new to PHP, I'm struggling. Here is what I have attempted so far: <?php ini_set("display_errors","on"); $dsn='mysql:host=localho ...

Iterate through every entry in a table and conduct calculations involving every other entry

I need to determine the value for NO_TOP_RATING in my working table To calculate NO_TOP_RATING: For each row, we need to find all other rows within the previous year based on ANNDATS_CONVERTED and with the same ESTIMID. Among those rows, identify the lo ...

Sequelize: There is no association between Model and Model2

I am currently working on a query involving multiple models in Sequelize. My models include Project and Specification. In this scenario, a Project can have many Specifications, while each Specification belongs to only one Project. Here is the table structu ...

What is the method for utilizing SHOW CREATE TABLE within a subquery?

I am attempting to achieve the following: SELECT * FROM information_schema.`tables` JOIN (SHOW CREATE TABLE) # <-- in need of assistance at this point WHERE table_schema LIKE 'tables\_%' Can this be accomplished in a single quer ...

Example of Using Bluebird in a Chain of Catch and Then Functions

I am struggling to understand how promises work in my code flow setup. I want to create a register function with multiple steps, but I'm unsure of what is achievable and what is not. Imagine I have a register function where I need to: register a u ...

In what situations might a finally block fail to execute?

Are there any circumstances where the code in a finally block may not be reached, aside from the usual suspects like process exit(), termination signal, or hardware failures? In this TypeScript code snippet that usually runs smoothly in node.js, occasiona ...

How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below? <div *ngFor="---"> <div> <span></span> <select> <option></option> <option></option> ...

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 ...

Organize results from MySql using php

Trying to retrieve table values from a MySQL database sorted has proven to be a challenge for me. While I am able to connect and update the table successfully, I struggle with displaying the messages in the HTML chat history sorted by time. Is there a mo ...

Is there a workaround for the React useContext issue in Typescript aside from using <Partial>?

I am currently working on a React app that utilizes the useContext hook, but I am facing challenges with correctly typing my context. Here is the code snippet in question: import React, { useState, createContext } from 'react'; import endpoints f ...

What is the best approach to accessing and reading a JSON file within an Angular 12 application?

I've been attempting to retrieve data from a local JSON file that holds configuration information for my application. Every time I run the ng build command in the Angular CLI, I encounter an error. The TypeScript document related to my component: my- ...

The Cloudflare KV namespace remains unbound

After running wrangler dev, it appears that Worker KV is not being bound properly: ERROR in /src/handler.ts ./src/handler.ts 16:8-17 [tsl] ERROR in /src/handler.ts(16,9) TS2304: Cannot find name 'generalKV'. This is the content of handler. ...

Using a conditional statement to generate objects within a TypeScript loop

I'm currently working on a loop within my code that involves adding dates from an array (dates) as key/value pairs ("date":"dates[i]") to objects in another array (values). values.forEach((obj, i) => obj.date = dates[i]); The issue arises when ...

Adding URL path in Angular 7's .ts file

I currently have the following code in my component's HTML file: <button mat-flat-button class="mat-flat-button mat-accent ng-star-inserted" color="accent" (click)="playVideo(video)"> <mat-icon [svgIcon]="video.type === 'external' ...

Choose to either delete the record if it exists or keep it by performing just one

In my database, I have a table named Persons. My task is to check if there are any records in the Persons table with PersonID equal to 1 and if so, delete them. I attempted the following query: DELETE FROM Persons WHERE PersonID = 1 AND EXISTS(SELECT P ...

Is it possible to execute a script from a different directory?

Currently, I am developing a nodejs package that involves executing a bash script within the program. The specific bash script, "./helpers/script.sh", needs to be run using a relative path. This means that when users install and run the package, the script ...