Skip to content

About

A fast, strictly typed SQL ORM for Node.js and TypeScript, built on knex. Postgres, MySQL, MariaDB, SQLite. A maintained fork of objection.js.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

 
 

Repository files navigation

Tests Docs npm

@abedmurrar/objection

A fast, strictly typed SQL ORM for Node.js, built on knex. Define your models and relations once, then query them with the full power of SQL: eager loading, graph inserts and upserts, transactions, JSON columns and expressions, with types that know what each query returns.

It started as a fork of objection.js 3.1.5 and keeps its API, so objection.js code runs on it apart from the breaking changes, most of which fix queries that read or changed the wrong rows.

npm install @abedmurrar/objection knex

Why this one

  • Types that know what you loaded. Relations are inferred from relationMappings, query results only contain the relations the query fetched, and relation expressions, modifier names and Model.ref() columns are checked at compile time. See TypeScript.
  • Fast. objection's own work for a query takes 13% to 19% less time than in objection.js 3.1.5, and since 4.1.3 another 10% to 27% fewer CPU instructions; toJSON() takes 44% less, validation 55% less, and a validated insert in a new transaction 91% less, with the same SQL and results. On a real MySQL, among the ORMs we measured (objection, sequelize, typeorm, mikro-orm, drizzle-orm) it was the fastest at finding rows and eager loading, and found a row by id 8% faster than objection.js 3.1.5 (in the run of 4.7.0); drizzle-orm, typeorm and sequelize were faster at deleting a row by id. Since 4.2.2, upsertGraph() on MySQL takes half the time without a transaction, because graph writes run 4 queries at a time there again. See Performance.
  • MySQL and MariaDB as first-class databases, not only postgres: JSON field expressions, the whereJson* methods, batch inserts and an fn.* helper for every MySQL 8.4 function. MariaDB 10.6 and 11.4 are tested in CI. See MySQL and MariaDB.
  • Large results without the memory or the offset. for await (const person of Person.query().stream()) yields the models one at a time as the database sends the rows: 200,000 rows on MySQL took 10 MB of heap instead of 48 MB. See Streaming. cursorPage(20, after) pages by the sort columns instead of an offset, so the page at row 50,000 took under 1 ms where page() took 31 to 69 ms on MySQL and MariaDB. See Paging.
  • Tracing built in. Every query is published on Node's diagnostics_channel as objection:query, with its model, relation and SQL but never its values, so OpenTelemetry and APM tools can trace it without wrapping anything. See Tracing.
  • Expressions without raw SQL, like Pet.ref('age').gte(3), fn.count().filter(...), fn.case() and window functions. See Expressions.
  • Safer. JSON field keys are escaped (in objection.js 3.1.5 they allowed SQL injection), an orWhere() can no longer match the rows of other relation owners, for() is no longer silently ignored, many-to-many unrelate() and patches only touch the join rows that match their filters, patches and deletes with joins only change the rows the joins match (objection.js 3.1.5 updated every row on SQLite and postgres), and with useAfterFindInGraphs the afterFind() filters of related models apply to eager loading too. See Breaking changes.
  • Modern. Node.js 22+, ES modules and CommonJS from one package, knex 3.3, the knex methods objection didn't have, no lodash and no bluebird, and npm audit reports nothing. The source is written in strict TypeScript and compiled with TypeScript 7.

A quick look

import { Model, defineRelations } from '@abedmurrar/objection';
import { knex } from 'knex';

Model.knex(knex({ client: 'pg', connection: process.env.DATABASE_URL }));

class Pet extends Model {
  static tableName = 'pets';

  id!: number;
  name!: string;
  ownerId!: number;
}

class Person extends Model {
  static tableName = 'persons';

  id!: number;
  firstName!: string;

  static relationMappings = defineRelations(() => ({
    pets: {
      relation: Model.HasManyRelation,
      modelClass: Pet,
      join: { from: 'persons.id', to: 'pets.ownerId' },
    },
  }));
}

const people = await Person.query().where('firstName', 'like', 'J%').withGraphFetched('pets');

people[0].pets[0].name; // `pets` is in the type because the query loaded it
people[0].firstName;

// A person and their pets in one insert.
await Person.query().insertGraph({
  firstName: 'Jennifer',
  pets: [{ name: 'Doggo' }],
});

Requirements

Dependency Version
Node.js 22 or newer (22, 24 and 26 are tested)
knex 3.3 or newer
MySQL 8.0.17 or newer (tested on 8.4 with mysql2)
MariaDB 10.6 or newer (tested on 10.6 and 11.4 with mariadb)
SQLite 3.35 or newer for batch inserts

Postgres is tested on the current release.

Coming from objection.js

Install the package under the name objection, and existing import { Model } from 'objection' code keeps working:

npm install objection@npm:@abedmurrar/objection

Then read the breaking changes and the migration guide. Most changes make queries do what they look like they do. The stricter types can flag code that only compiled because the old types were loose; the TypeScript page lists an opt-out for every check.

Documentation

The approach

Like objection.js, this is less a classic ORM than a relational query builder: you work with queries, not with an object graph that hides the SQL.

  • You get a declarative way to define models and their relations, the full power of SQL to fetch and change rows, eager loading, graph inserts and upserts, transactions, optional JSON schema validation, and a way to store documents in JSON columns.
  • You don't get a query language of its own (the query builder is knex, and raw() is there for anything it can't express), or a schema generated from the models: knex migrations do that job.

Credits

This project is built on objection.js by Sami Koskimäki and its many contributors, maintained at Vincit. Its design, its API, most of its code and much of the documentation come from there. Thank you.

Many fixes, and options like snakeCaseMappers({ preserveJsonKeys: true }), are ported from ditojs/objection by Jürg Lehni and its contributors, with credit in each commit. Ported from ditojs/objection lists them.

Released under the MIT license, like objection.js.

About

A fast, strictly typed SQL ORM for Node.js and TypeScript, built on knex. Postgres, MySQL, MariaDB, SQLite. A maintained fork of objection.js.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages