A pure ORM for writing native SQL queries yielding pure business objects
A pure ORM for writing native SQL queries yielding pure business objects
npm install --save pure-ormPureORM is a lightweight ORM for mapping the relational result rows of a database driver query to properly structured (nested) pure instances of your business object classes.
It's purpose - and guiding principle - is to allow you to write native, unobstructed SQL (not niche library-specific ORM wrapper APIs) and receive back properly structured/nested pure business objects (not database-connected stateful objects).
This means you can just write SQL like this:
SELECT *
FROM person
LEFT JOIN job on person.id = job.person_id
LEFT JOIN employer on job.employer_id = employer.id
WHERE person.id = 55...And for the result data
| id | name | id | personId | employerId | startDate | endDate | id | name |
|---|---|---|---|---|---|---|---|---|
| 55 | John Doe | 277 | 55 | 17 | 2020-01-01 | 2020-12-31 | 17 | Good Corp |
| 55 | John Doe | 278 | 55 | 26 | 2021-01-01 | 2021-12-31 | 26 | Better Corp |
...Rather than getting flat, collided result objects:
[
{
id: 17, // from employer which collided with job.id and person.id :(
name: 'Good Corp', // from employer which collided with person.name :(
person_id: 55,
employer_id: 17,
start_date: 2020-01-01T05:00:00.000Z,
end_date: 2020-12-31T05:00:00.000Z
},
{
id: 26, // from employer which collided with job.id and person.id :(
name: 'Better Corp', // from employer which collided with person.name :(
person_id: 55,
employer_id: 26,
start_date: 2021-01-01T05:00:00.000Z,
end_date: 2021-12-31T05:00:00.000Z
}
]...You get properly structured/nested, pure objects like this:
{
id: 55,
name: "John Doe",
jobs: {
models: [
{
id: 277,
personId: 55,
employerId: 17,
employer: {
id: 17,
name: "Good Corp"
},
startDate: "2020-01-01",
endDate: "2020-12-31"
},
{
id: 278,
personId: 55,
employerId: 26,
employer: {
id: 26,
name: "Better Corp"
},
startDate: "2021-01-01",
endDate: "2021-12-31"
}
]
}
};...Where these objects are instantiations of classes you define. So the above is our (not shown) Person class, which has a jobs field pointing to our (not shown) Jobs collection class, which has individual (not shown) Job classes, which have a employer field pointing to our (not shown) Employer classes. Each of these classes is defined by us, and can contain custom business logic. (Check out the full example lower down to see these!)
PureORM contrasts with tradtional ORMs in two important ways:
PureORM thus contrasts against traditional ORMs which use query builders (rather than raw SQL) to return database-connected (rather than pure) objects. The name pureORM reflects both of these points - that it is pure ORM (there is no query builder dimension) as well as the purity of the mapped models.
Yep! PureORM is the top layer for interfacing with your database. You bring your own database driver (eg node-postgres/pg-promise, mysql, node-sqlite3, node-mssql, node-oracledb, etc), and PureORM works on top of it to perform the Object-Relational Mapping (ORM).
Lets take a practical example to see all this in action. Lets fill in the backend for a tiny rest server for a person.
Lets say we have a database with three tables: person, job, and employer. We want our rest server to return an payload like this for requests which the get method receive.
…Based on the tables with this data:
Person
| id | name |
|---|---|
| 55 | John Doe |
Employer
| id | name |
|---|---|
| 17 | Good Corp |
| 26 | Better Corp |
Job
| id | personId | employerId | startDate | endDate |
|---|---|---|---|---|
| 277 | 55 | 17 | 2020-01-01 | 2020-12-31 |
| 278 | 55 | 26 | 2021-01-01 | 2021-12-31 |
I know exactly how I want to query for it:
SELECT *
FROM person
LEFT JOIN job on person.id = job.person_id
LEFT JOIN employer on job.employer_id = employer.id
WHERE person.id = 55;I already know how SQL, and don't want to spend the time mapping what I already know how to do onto a huge, niche, library-specific API.
However, using this query with a database driver would give me a bunch of flat result records (not one object that is properly structed/nested) and with collided fields (id from all three tables, name from person and employer, etc).
So, lets install PureORM and the database driver and get started!
For our example, we'll assume postgres database so we'll use the incredible pg-promise database driver.
npm install --save pure-orm
npm install --save pg-promiseLet's create a /models directory, with a file corresponding to each table. These modules contain the model and (optionally) collection classes we want to use when mapping our flat results to business objects, as well as the tableName and columns fields. We'll end up passing all this to the PureORM factory later.
// models/person.ts
import { IModel, ICollection, IColumns, IEntity } from 'pure-orm';
export const tableName: string = 'person';
export const columns: IColumns = ['id', 'name'];
export class Person implements IModel {
id: number;
name: string;
constructor(props) {
this.id = props.id;
this.name = props.name;
}
// any business methods...
}
export const personEntity: IEntity = { tableName, columns, Model: Person };…// models/employer.ts
import { IModel, ICollection, IColumns, IEntity } from 'pure-orm';
export const tableName: string = 'employer';
export const columns: IColumns = ['id', 'name'];
export class Employer implements IModel {
id: number;
name: string;
constructor(props: IEmployerProps) {
this.id = props.id;
this.name = props.name;
}
// any business methods...
}
export const EmployerEntity: IEntity = { tableName, columns, Model: Employer };First we create our database driver:
// ./factories/db.ts
import pgPromise from 'pg-promise';
const pgp = pgPromise();
const connectionObject = {
host: process.env.DB_HOSTNAME,
port: process.env.DB_PORT,
database: process.env.DB_NAME,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
};
export const db = pgp(connectionObject);We can now create our ORM, which layers atop the database driver to do the object relational mapping of raw sql row data to nest objects. (Besides using the db instance directly, the orm also offers access to the db directly (orm.db) for anytime this object relational mapping isn't desired.
// factories/orm.ts
import { create } from 'pure-orm';
import { db } from './db';
import { personEntity } from '../models/person';
import { jobEntity } from '../models/job';
import { employerEntity } from '../models/employer';
const orm = create({
entities: [personEntity, jobEntity, employerEntity],
db
});
export default orm;Let's now create a data access directory with a person file for data access operations related to a person.
// data-access/person.ts
import orm from '../factories/orm';
import { Person } from '../models/person';
export const getPerson = (id: number): Person => {
const query = `
SELECT
${orm.tables.person.columns},
${orm.tables.job.columns},
${orm.tables.employer.columns}
FROM person
LEFT JOIN job on person.id = job.person_id
LEFT JOIN employer on job.employer_id = employer.id
WHERE id = $(id)
`;
return orm.one(query, { id });
};Some things to note:
one method. The ORM methods for one, oneOrNone, many, any ensure their count against the number of generated top level models - not the number of relational row records the sql expression returns!ids would collide if not namespaced, as would person and employer names). You are welcome to do this by hand instead of using this convenience if you don't mind the tedium:…We can now return to our controller code, and use our data access function.
…That's it! This controller code now works! The getPerson function returns a properly structured business object as we desire.
createfunction create(options: {
entities: Array;
db: DataBaseDriver;
}): PureORM;The factory function for creating your ORM.
Parameters
entities: Array - An array of all the business object class entity configuration objects.…db: - A database driver instance.Return Value
Your PureORM instance, which is of this interface:
…createFromDatabaseArrayscreateFromDatabaseArrays(
rows: Array>,
fields: Array,
parseKinds?: Array any)>
): T;The positional twin of createFromDatabase, on the core (createCore)
instance: rows arrive as arrays of cells in field order - the shape a
driver's array mode returns - and build exactly the graph object rows
would. For wide joined queries this is dramatically faster end to end,
because the driver never materializes a row object per row (at 68+ columns
those objects live in V8 dictionary mode, and building them dwarfs the
mapping itself). With node-postgres:
const result = await client.query({
text: `SELECT ${orm.tables.order.columns}, ${orm.tables.lineItem.columns}
FROM ...`,
rowMode: 'array'
});
const orders = core.createFromDatabaseArrays(result.rows, result.fields);fields may be the driver's field descriptors (anything carrying a
name) or plain strings; reusing one fields array across calls makes
plan lookup a single WeakMap probe. An explicit shape also makes an empty
result set valid - it returns an empty collection, no rootKey needed.
parseKinds (optional) moves the driver's per-cell type parsing into the
row processor, where it only runs for cells of models actually being
created. On a joined result set the same parent cells repeat on every child
row - 70-95% of all cells on captured production pages - and pa
No open issues yet, or sync has not completed.