Insert a Record
Like connecting, query operations in Formn originate with a DataContext instance. (See the DataContext section.) The DataContext.insert method is used to insert a model instance into the database.
Insert a Person Instance
Back in the Migrations section we set up an example database. Then, in the Models section, we defined a Person entity class. Let’s walk through the process of inserting a Person.
First, instantiate and populate a
Person
(president
below).
const president = new Person();
president.firstName = 'Abe';
president.lastName = 'Lincoln';
Next, create an Insert instance using the DataContext.insert method. It takes two parameters.
- An EntityType, which is a Table-decorated class. (See the Models section.) We’re inserting a Person.
- An instance of that EntityType (
president
).
const query: Insert<Person> = dataContext.insert(Person, president);
Insert is a type of Query, and, like all Formn queries, you can call the toString method to see the underlying SQL associated with the Query instance. This method is useful for logging and debugging purposes.
console.log(query.toString());
Finally, execute the query
to insert the president
record.
await query.execute();
Since
Person’s
primary key is generated (an auto-incrementing int), Formn sets the generated
id
on the president
instance.
Full Example
Here’s the full example, which can be found in the formn-example
repository
under
src/create/create-person.ts.
import { inspect } from 'util';
import { MySQLDataContext, ConnectionOptions, Insert } from 'formn';
import { Person } from '../entity/person.entity';
async function main() {
const connOpts: ConnectionOptions = require('../../connections.json');
const dataContext = new MySQLDataContext();
try {
await dataContext.connect(connOpts);
// Create a new Person instance.
const president = new Person();
president.firstName = 'Abe';
president.lastName = 'Lincoln';
// Create an Insert query.
const query: Insert<Person> = dataContext.insert(Person, president);
// This is the SQL that will be executed on Query.execute();
console.log(query.toString());
// Persist the person.
await query.execute();
// The new person has the generated ID set.
console.log(inspect(president, {depth: null, compact: false}));
}
catch(err) {
console.error('Error creating user.');
console.error(err);
}
finally {
await dataContext.end();
}
}
main();
Run the example with ts-node
:
npx ts-node ./src/create/create-person.ts
The output will look similar to this.
INSERT INTO `people` (`firstName`, `lastName`)
VALUES (:firstName, :lastName)
Person {
firstName: 'Abe',
lastName: 'Lincoln',
id: 5
}