Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

pure-orm

> 数据库
Open source

A pure ORM for writing native SQL queries yielding pure business objects

396 stars0 likes1 views
WebsiteGitHub

About

A pure ORM for writing native SQL queries yielding pure business objects

PureORM

Installation

bash
npm install --save pure-orm

What is PureORM?

PureORM 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).

What does this mean?

This means you can just write SQL like this:

javascript
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:

javascript
[
  {
    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:

javascript
{
  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!)

How does PureORM compare with traditional ORMs?

PureORM contrasts with tradtional ORMs in two important ways:

  1. PureORM is purely the "orm" (object-relational mapping) - it has the small scope of "owning" the mapping of database driver relational result rows to properly structured business objects. This contrasts against ORMs as typically exist - where they have swelled to intertwine a huge query builder API with the ORM layer, where mapped objects are database-connected and serve as the query builder.
  2. PureORM yields pure (not database-connected) models. Queries are written in SQL (not niche library-specific ORM wrapper APIs), and the results are pure businesses objects.

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.

So I bring my own database driver?

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).

Practical Example

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:

sql
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!

Step 1: Installing PureORM and the Database Driver

For our example, we'll assume postgres database so we'll use the incredible pg-promise database driver.

bash
npm install --save pure-orm
npm install --save pg-promise

Step 2: Creating the Business Objects

Let'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.

typescript
// 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 };
…
typescript
// 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 };

Step 3: Creating our ORM

First we create our database driver:

typescript
// ./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.

typescript
// 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;

Step 4: Creating our Data Access Layer

Let's now create a data access directory with a person file for data access operations related to a person.

typescript
// 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:

  • Our data access function returns a single Person model which is properly structured from the many relational row records!
  • Our query is executed with a 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!
  • Rather than manually specifying our columns in the sql select expression, we used the orm's getter for columns. This is purely a convenience method which namespaces each column with the table name prefix to ensure column names don't collide (for example, the person, job, and employer 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:
…

Step 5: Writing the Controller Code

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.

API

create

typescript
function 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:

…

createFromDatabaseArrays

typescript
createFromDatabaseArrays(
  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:

javascript
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

Issues· 5 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptdata-access-objectdatabasejavascriptnode-postgres

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库