Insert
This page shows how to insert records: with all the properties of the entity or only some of them, together with related entities (include), and how to insert or update in one step (upsert). To insert many records at once, see Bulk Insert. The SQL shown is the one generated for MySQL, unless stated otherwise.
A query is based on both the expression and the schema. If you do not specify the properties to insert, all the properties of the entity are inserted. How each property is stored in each source (table and column names) is resolved by the mapping of that source in the schema.
Insert all the properties
When the properties are not specified, the data passed must be an object with the properties of the entity.
Lambda:
Categories.insert()
SQL Result:
INSERT INTO Categories(CategoryName,Description) VALUES(?,?)
The primary key id is not inserted because it is auto-increment: the database generates it.
Insert some properties
Only the properties specified are inserted. Here, name is a variable of the data passed to the query.
Lambda:
Categories.insert({ name: name })
SQL Result:
INSERT INTO Categories(CategoryName) VALUES(?)
Insert with include
To insert an object together with its related objects, include the relation. This example inserts an order and its details; the key of the new order is assigned to each detail.
Lambda:
Orders.insert().include(p => p.details)
SQL Result:
-- the order
INSERT INTO Orders(CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)
-- each detail of the order
INSERT INTO `Order Details`(OrderID,ProductID,UnitPrice,Quantity,Discount)
VALUES(?,?,?,?,?)
Upsert
upsert() inserts the record or, if a record with the same primary key already exists, updates it. It is written like an insert: upsert() with all the properties, or with the properties specified. The entity needs a primary key, and the data must include it (so an auto-increment key is of little use here).
Lambda:
// inserts the country, or updates it when one with the same iso3 exists
Countries.upsert()
await orm.execute('Countries.upsert()', { iso3: 'ARG', name: 'Argentine' }) // inserted
await orm.execute('Countries.upsert()', { iso3: 'ARG', name: 'Argentina' }) // updated: the same row
SQL Result:
-- MySQL / MariaDB
INSERT INTO Countries(iso3,name) VALUES(?,?) ON DUPLICATE KEY UPDATE name = VALUES(name)
-- PostgreSQL
INSERT INTO Countries(iso3,name) VALUES($1,$2)
ON CONFLICT (iso3) DO UPDATE SET name = EXCLUDED.name
-- SQL Server
MERGE INTO Countries WITH (HOLDLOCK) AS t
USING (SELECT 1 AS x) AS s
ON t.iso3 = @iso3
WHEN MATCHED THEN UPDATE SET name = @name
WHEN NOT MATCHED THEN INSERT (iso3,name) VALUES (@iso3,@name);
-- Oracle
MERGE INTO Countries t
USING (SELECT 1 FROM DUAL) s
ON (t.iso3 = :iso3)
WHEN MATCHED THEN UPDATE SET name = :name
WHEN NOT MATCHED THEN INSERT (iso3,name) VALUES (:iso3,:name)
Upsert is supported on PostgreSQL, MySQL, MariaDB, SQL Server and Oracle (these two with MERGE, from @lambdaorm/lib 3.5.0).
Warning
On MongoDB, upsert fails with a "not supported yet" error. SQLite (SQL.js) does not support it either.
When the key is generated (auto-increment) and not sent, the upsert inserts. On SQL Server the identity column is never inserted (the database generates it) and OUTPUT INSERTED returns it; Oracle's MERGE cannot return values, so it returns the key that was sent.
Upsert is also what an update with include of a composite relation uses to save the children.
Code example
Inserts an order with two details and prints the id of the new order.
import { orm } from '@lambdaorm/lib'
import { Orders } from './domain/model' // model generated by `lambdaorm build`
(async () => {
try {
await orm.init('./lambdaORM.yaml')
const order = {
customerId: 'VINET',
employeeId: 5,
orderDate: '1996-07-03T22:00:00.000Z',
requiredDate: '1996-07-31T22:00:00.000Z',
shippedDate: '1996-07-15T22:00:00.000Z',
shipViaId: 3,
freight: 32.38,
name: 'Vins et alcools Chevalier',
address: '59 rue de l-Abbaye',
city: 'Reims',
postalCode: '51100',
country: 'France',
// orderId is assigned from the new order
details: [
{ productId: 11, unitPrice: 14, quantity: 12, discount: 10 },
{ productId: 42, unitPrice: 9.8, quantity: 10, discount: 10 }
]
}
const query = () => Orders.insert().include(p => p.details)
// returns the id of the order created
const result = await orm.execute(query, order)
console.log(JSON.stringify(result))
} catch (error: any) {
console.error(error.stack)
} finally {
// releases the connections
await orm.end()
}
})()