Bulk Insert

This page shows how to insert many records at once with bulkInsert. Use it instead of Insert when you have a list of records to load, such as an import or a large dataset. The SQL shown is the one generated for MySQL.

bulkInsert receives an array of records and inserts them in chunks, with one statement per chunk instead of one statement per record. The size of the chunks depends on the connection, and you can lower it with the chunkSize option of orm.execute. This reduces the round trips between the application and the database, which makes inserting large volumes of data much faster and lightens the load on the database server.

Bulk insert into one entity

Inserts a list of categories.

Lambda:

Categories.bulkInsert()

SQL Result:

INSERT INTO Categories(CategoryName,Description) VALUES ?

Inserts a list of orders, each one with its details.

Lambda:

Orders.bulkInsert().include(p => p.details)

SQL Result:

-- the orders
INSERT INTO Orders(CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) VALUES ?

-- the details of all the orders
INSERT INTO `Order Details`(OrderID,ProductID,UnitPrice,Quantity,Discount) VALUES ?

Code example

Inserts two categories and prints the ids of the records inserted.

import { orm } from '@lambdaorm/lib'
import { Categories } from './domain/model' // model generated by `lambdaorm build`

(async () => {
    try {
        await orm.init('./lambdaORM.yaml')
        const categories = [
            { name: 'Beverages4', description: 'Soft drinks, coffees, teas, beers, and ales' },
            { name: 'Condiments4', description: 'Sweet and savory sauces, relishes, spreads, and seasonings' }
        ]
        const query = () => Categories.bulkInsert()
        // returns the ids of the records inserted
        const result = await orm.execute(query, categories)
        console.log(JSON.stringify(result, null, 2))
    } catch (error: any) {
        console.error(error.stack)
    } finally {
        // releases the connections
        await orm.end()
    }
})()