Saving large amounts of data in bulk to PostgreSQL using TypeORM

I am looking to perform a bulk insert/update using TypeORM

The Test entity is defined below:

export class Test {
   @PrimaryColumn('integer')
   id: number;
 
   @Column('varchar', { length: 255 })
   testName: string;
 }

I have the following objects that I want to insert in batch:

const test1 = new Test();
script.id = 1;
script.testName = 't1';

const test2 = new Test();
test2.id = 2;
test2.testName = 't2';

const test3 = new Test();
test3.id = 3;
test3.testName = 't3';

const tests = [test1, test2, test3];

However, when I attempt to save them together like this:

const testRepository = dataSource.getRepository(Test);
await testRepository.save(tests);

It doesn't work as expected. Strangely enough, testRepository.save(test1); works fine.

Can you guide me on how to perform a batch insert, especially when dealing with thousands of rows?

Answer №1

When utilizing TypeORM, the insert method is handy for executing bulk inserts.

To perform a bulk insert, you can follow this basic syntax:

const dataRepository = dataSource.getRepository(Data);

await dataRepository.insert(dataEntries);

Some key points to keep in mind:

  • The insert method accepts an array of entity objects
  • If your database requires explicit ids (like postgres), make sure the primary keys/ids are populated for each entity
  • In databases supporting auto-increment ids (such as sqlite, mysql), omitting ids is acceptable

For instance:

const dataEntries = [
  { id: 1, entryName: 'entry1'},
  { id: 2, entryName: 'entry2'}, 
  { id: 3, entryName: 'entry3'} 
];

await dataRepository.insert(dataEntries);

This code snippet will insert all 3 data entries in one go.

Additional suggestions include:

  • You have the flexibility to mix existing and new entities within the array
  • Split huge batches into chunks to avoid hitting query size limitations
  • Employing transactions can ensure atomicity during inserts

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 is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Setting a default value for a data type within Typescript

My goal is to set default values for all properties in my custom type if they are not defined. This is what I have done: // custom type with optional properties type MyType = { // an example property: str?: string } // with numerous properties, assign ...

In TypeScript, there is a curious phenomenon where private properties seem to be mimicking the

Here is an example of an issue I encountered while working with private properties in TypeScript. I expected that only the public properties would be visible in my object output, similar to normal encapsulation. My aim here is to include the property wit ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this: articles UNIQUE_KEY title: 'Some title' validUntil: '2017-09-29T21:00:00.000Z' UNIQUE_KEY title: 'Other title' validUntil: '2017-10-29T21:00:00 ...

ngPrime table column selection and data extraction

I am looking to extract multiple columns from a table. Can anyone suggest the best approach for this? Does NGPrime offer any functionality for achieving this task? Appreciate your help! ...

How can 'this' be converted from D3 JavaScript to TypeScript?

In JavaScript, 'this' has a different meaning compared to TypeScript, as explained in this informative article 'this' in TypeScript. The JavaScript code below is used to create a thicker stroke on the selected node and give smaller stro ...

Utilizing TypeScript to invoke a method via an index signature

Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls? createFormControl(formControls: ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

Transmit information between components through a form

Is there a way to transfer data from one component to another in Angular? I have two components set up and I am currently using a selector to display the HTML content in the first component. Now, I need to figure out how to send the data entered in a form ...

Invalid sequencing of Nest.js async onModuleInit causing issues

I am dealing with a scenario where ServiceA relies on RedisService. In order for ServiceA to be fully operational, it must wait for RedisService to complete its initialization process (specifically, for RedisService.onModuleInit to be called and awaited). ...

A solution for resolving the RuntimeException in genuitec's TypeScript Editor for Eclipse Oxygen

After setting up a fresh Eclipse Oxygen and installing the Angular IDE from Genuitec, I encountered an issue on the second day when I opened a project and accessed a *.ts File. The error message displayed was: java.lang.RuntimeException: java.lang.Illegal ...

Is Angular2 detecting changes based on value equivalence or reference equality?

I am currently working with Angular2-RC.1 and I've noticed a significant decrease in performance when setting up a component with a large dataset. The component I'm using is a tabular one (which involves Handsontable) and it has an Input property ...

Adding additional properties to Material UI shadows in Typescript is a simple process that can enhance the visual

https://i.stack.imgur.com/9aI0F.pngI'm currently attempting to modify the Material UI types for shadows, but encountering the following error when implementing it in my code. There is no element at index 25 in the tuple type Shadows of length 25. I&a ...

Guide on updating a value in a Firestore document using Firebase

I am working on updating a specific portion of a document in my Firebase collections structure, specifically the phonebook(map) section. https://i.sstatic.net/UmHot.png When attempting to modify the document, I encountered an error saying Invalid documen ...

The chosen index in the Material Stepper feature is experiencing a malfunction

I've been busy working on a Mat-Stepper, actually two of them. I have a component that contains two ng-templates set up like this: Question: Why is my selected index not functioning as expected? Am I missing something? I know you can define [selected ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

Getting a string output from a Typescript promise

Here is some Typescript code that I thought would be simple. public showDialog(theNickname: string): string { var req = { method: 'POST', url: '/Q/GetUserDetails', data: { nickname ...