MikroORM
mikro-orm-postgrejs is a
MikroORM 7 driver for postgrejs. It is maintained alongside postgrejs
rather than by the MikroORM project — MikroORM's own extension point for this is a driver, and this
is one. Your entities, repositories, migrations and queries stay as they are; only the connection
under them changes.
MikroORM 7 runs every statement through Kysely, and its PostgreSQL connection
builds a Kysely dialect over a pg pool. This driver extends that connection and builds
kysely-postgrejs's dialect over a postgrejs Pool
instead. The platform, the query builder, the schema generator, the migrator and the entity manager
are @mikro-orm/postgresql's own, and keep tracking its releases.
Installation
npm install mikro-orm-postgrejs @mikro-orm/core @mikro-orm/postgresql postgrejs
@mikro-orm/core and @mikro-orm/postgresql (>=7.2.13 <7.3), postgrejs (>=3.15.0 <4) and
kysely (>=0.29.9 <0.31, which @mikro-orm/postgresql already installs) are peer dependencies.
Node >=22.17, as for MikroORM 7.
Quick start
import { MikroORM } from 'mikro-orm-postgrejs';
const orm = await MikroORM.init({
clientUrl: 'postgresql://app@localhost:5432/mydb',
entities: [User, Article],
});
The package exports everything @mikro-orm/postgresql does, with its own MikroORM,
defineConfig and EntityManager in their place, so switching is a change of import. The driver
class on its own is PostgrejsDriver:
import { defineConfig, PostgrejsDriver } from 'mikro-orm-postgrejs';
export default defineConfig({
driver: PostgrejsDriver, // already the default here
dbName: 'mydb',
entities: [User, Article],
});
Usage
Connecting
MikroORM's own settings work as they do on @mikro-orm/postgresql: host, port, user,
password, dbName, clientUrl (including sslmode and application_name in its query string),
pool.min, pool.max, pool.idleTimeoutMillis, onCreateConnection, onReserveConnection and
sessionContext.
A ?schema= in the URL is MikroORM's to read: it qualifies table names with it. The driver does not
pass it on to postgrejs, which would otherwise set a search_path on every connection that pg
never sets.
Options
driverOptions takes a postgrejs pool configuration,
which wins over anything the driver derives from MikroORM's settings, plus three options of the
driver's own:
| Option | Default | What it does |
|---|---|---|
decoding | 'native' | 'pg' makes raw rows carry the values @mikro-orm/postgresql gives — see Raw results |
onPoolCreated | Called with the postgrejs Pool once it exists, before any connection is opened | |
fetchAsString | More OIDs to receive as text, on top of the ones the driver asks for |
Cloudflare Workers
MikroORM's guide for Workers configures a single-use pool, so that a connection opened while serving one request is never handed to the next:
MikroORM.init({
// ...
driverOptions: { max: Infinity, maxUses: 1 },
});
That works as written on postgrejs 3.16.0 or later, where the pool's
maxUses option arrived. The peer floor stays at 3.15.0:
below 3.16 the option is ignored and nothing else changes. See
Cloudflare Workers for the rest of what differs there.
Reaching the client underneath
em.getConnection().getNativeClient() answers the postgrejs Pool, so everything MikroORM has no
way to ask for is a method call away — COPY,
LISTEN/NOTIFY,
large objects,
logical replication:
const pool = await orm.em.getConnection().getNativeClient();
// The pool keeps one notification connection of its own, apart from the ones MikroORM uses.
await pool.listen('order_placed', msg => console.log(msg.payload));
// A COPY, a large object or anything else that needs one connection throughout:
const connection = await pool.acquire();
try {
// ...
} finally {
await connection.close(); // returns it to the pool
}
Tested against MikroORM's own suite
A script runs every MikroORM test file that uses PostgreSQL against this driver, with a control run
on pg in the same invocation, in containers of their own so no PostgreSQL on the host is touched.
On MikroORM 7.2.13, 347 test files, the control run passes 1558 tests. On this driver 8 of them do
not pass, and all 8 test pg's own API rather than behaviour:
onPoolCreatedreceiving apg.Pool;- two mocks of
pg.Pool.prototype.connect; - two checks of
pg-connection-string'sssloption shape; - a reset of the
pgclient's socket; - two reads of
pg-pool'stotalCountandidleCount.
A weekly CI job runs the suite again with that count of 8 pinned, to notice a change in MikroORM rather than in this repository.
What changes when you switch
Entity values
Entity properties come out the same as on @mikro-orm/postgresql. MikroORM's PostgreSQL platform
reads a few types from strings and parses them itself — date, time, timestamp, timestamptz,
interval and numeric — so the driver asks the server to send those as text, whichever decoding
is chosen. Decoded natively instead, five built-in MikroORM types come back wrong, which is what the
list was measured against:
datearrives as aDatewhereDateTypeholds'2024-03-05', and the next flush writes it back as a change;timestamparrives as aDatealready placed in the process's time zone, so MikroORM'stimezoneoption is applied a second time;intervalarrives as anInterval, whichpostgres-intervalreads as zero;timearrives as aDateon 1970-01-01 whereTimeTypeholds'12:30:00';numeric(10,2)holding 1.50 arrives as the number 1.5, andDecimalTypeturns that into'1.5', losing the scale.
Raw results
Every other type is decoded by postgrejs, which shows in raw results.
em.execute('select count(*) as n ...') answers n as a number where pg answers a string; an
int8 past 2^53 is a BigInt, ranges are Range objects and geometric
types are classes. Code that reads raw rows the way pg shapes them can ask for that:
MikroORM.init({
// ...
driverOptions: { decoding: 'pg' },
});
That mode was checked over 146 scalar and array types through em.execute() on both drivers, and
143 come back identical. The three that do not are point, circle and point[], which stay
postgrejs classes carrying the same fields as pg's plain objects.
Types postgrejs has no binary decoder for — citext, hstore, native enums, regclass and other
extension types — come back as the text PostgreSQL prints, as they do on pg.
Full documentation
See the mikro-orm-postgrejs README and its
design notes for the
measurements behind the type lists and the suite, and mikro-orm.io for the
ORM itself — none of that is postgrejs-specific.