mikro-orm-postgrejs 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,30 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026 Panates
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice,
10
+ this list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright
13
+ notice, this list of conditions and the following disclaimer in the
14
+ documentation and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # mikro-orm-postgrejs
2
+
3
+ [![NPM Version][npm-image]][npm-url]
4
+ [![NPM Downloads][downloads-image]][downloads-url]
5
+ [![CI Tests][ci-test-image]][ci-test-url]
6
+ [![Test Coverage][coveralls-image]][coveralls-url]
7
+
8
+ A [MikroORM](https://mikro-orm.io) 7 driver for [PostgreJS](https://github.com/panates/postgrejs), a
9
+ PostgreSQL client written from the wire protocol up in TypeScript.
10
+
11
+ Your entities, repositories, migrations and queries stay as they are. Only the connection under
12
+ them changes.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ npm install mikro-orm-postgrejs @mikro-orm/core @mikro-orm/postgresql postgrejs
18
+ ```
19
+
20
+ `@mikro-orm/core` and `@mikro-orm/postgresql` (>=7.2.13 <7.3), `postgrejs` (>=3.15 <4) and `kysely`
21
+ (>=0.29.9 <0.31, which `@mikro-orm/postgresql` already installs) are peer dependencies. Node
22
+ >=22.17, as for MikroORM 7.
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { MikroORM } from 'mikro-orm-postgrejs';
28
+
29
+ const orm = await MikroORM.init({
30
+ clientUrl: 'postgresql://app@localhost:5432/mydb',
31
+ entities: [User, Article],
32
+ });
33
+ ```
34
+
35
+ The package exports everything `@mikro-orm/postgresql` does, with its own `MikroORM`, `defineConfig`
36
+ and `EntityManager` in their place, so an import can switch from one to the other. The driver class
37
+ on its own is `PostgrejsDriver`:
38
+
39
+ ```ts
40
+ import { defineConfig, PostgrejsDriver } from 'mikro-orm-postgrejs';
41
+
42
+ export default defineConfig({
43
+ driver: PostgrejsDriver, // already the default here
44
+ dbName: 'mydb',
45
+ entities: [User, Article],
46
+ });
47
+ ```
48
+
49
+ ## How it works
50
+
51
+ MikroORM 7 runs every statement through [Kysely](https://kysely.dev), and its PostgreSQL connection
52
+ builds a Kysely dialect over a `pg` pool. This driver extends that connection and builds
53
+ [`kysely-postgrejs`](https://github.com/panates/postgrejs-kysely)'s dialect over a PostgreJS pool
54
+ instead. The platform, the query builder, the schema generator, the migrator and the entity manager
55
+ are `@mikro-orm/postgresql`'s own and keep tracking its releases.
56
+
57
+ ## Values
58
+
59
+ Entity properties come out the same as on `@mikro-orm/postgresql`. MikroORM's PostgreSQL platform
60
+ reads a few types from strings and parses them itself - `date`, `time`, `timestamp`, `timestamptz`,
61
+ `interval` and `numeric` - so the driver asks the server to send those as text. Every other type is
62
+ decoded by PostgreJS.
63
+
64
+ That shows in raw results. `em.execute('select count(*) as n ...')` answers `n` as a number, where
65
+ `pg` answers a string; an `int8` past 2^53 is a `BigInt`, ranges are `Range` objects and geometric
66
+ types are classes. Code that reads raw rows the way `pg` shapes them can ask for that:
67
+
68
+ ```ts
69
+ MikroORM.init({
70
+ // ...
71
+ driverOptions: { decoding: 'pg' },
72
+ });
73
+ ```
74
+
75
+ Types PostgreJS has no binary decoder for - `citext`, `hstore`, native enums, `regclass` and other
76
+ extension types - come back as the text PostgreSQL prints, as they do on `pg`.
77
+
78
+ ## Options
79
+
80
+ `driverOptions` takes a PostgreJS pool configuration, which wins over what the driver derives from
81
+ MikroORM's own settings, plus:
82
+
83
+ | Option | Default | What it does |
84
+ | --------------- | ---------- | -------------------------------------------------------------------- |
85
+ | `decoding` | `'native'` | `'pg'` makes raw rows carry the values `@mikro-orm/postgresql` gives |
86
+ | `onPoolCreated` | | Called with the PostgreJS pool once it exists |
87
+ | `fetchAsString` | | More OIDs to receive as text, on top of the ones the driver asks for |
88
+
89
+ MikroORM's `host`, `port`, `user`, `password`, `dbName`, `clientUrl` (including `sslmode` and
90
+ `application_name` in its query string), `pool.min`, `pool.max`, `pool.idleTimeoutMillis`,
91
+ `onCreateConnection`, `onReserveConnection` and `sessionContext` all work as they do on
92
+ `@mikro-orm/postgresql`, and so does the `{ max: Infinity, maxUses: 1 }` pool setting from
93
+ MikroORM's Cloudflare Workers guide (PostgreJS 3.16 or later). `em.getConnection().getNativeClient()` answers the PostgreJS `Pool`.
94
+
95
+ ## Tests
96
+
97
+ `pnpm test` runs the unit tests, the live tests and a differential suite that sends the same calls
98
+ through `@mikro-orm/postgresql`'s `pg` driver and through this one and compares the answers, against
99
+ PostgreSQL on `127.0.0.1:5432`.
100
+
101
+ `pnpm run test:mikro-orm-suite` runs MikroORM's own PostgreSQL tests on this driver, with a control
102
+ run on `pg` in the same invocation. It needs Docker: the tests run in containers of their own, so a
103
+ PostgreSQL on the host is never touched.
104
+
105
+ ## License
106
+
107
+ [BSD-3-Clause](LICENSE)
108
+
109
+ [npm-image]: https://img.shields.io/npm/v/mikro-orm-postgrejs
110
+ [npm-url]: https://npmjs.org/package/mikro-orm-postgrejs
111
+ [downloads-image]: https://img.shields.io/npm/dm/mikro-orm-postgrejs.svg
112
+ [downloads-url]: https://npmjs.org/package/mikro-orm-postgrejs
113
+ [ci-test-image]: https://github.com/panates/postgrejs-mikro-orm/actions/workflows/test.yml/badge.svg
114
+ [ci-test-url]: https://github.com/panates/postgrejs-mikro-orm/actions/workflows/test.yml
115
+ [coveralls-image]: https://img.shields.io/coveralls/panates/postgrejs-mikro-orm/main.svg
116
+ [coveralls-url]: https://coveralls.io/r/panates/postgrejs-mikro-orm
@@ -0,0 +1,51 @@
1
+ import { AbstractSqlConnection, PostgreSqlConnection } from '@mikro-orm/postgresql';
2
+ import type { DatabaseConnection, Dialect } from 'kysely';
3
+ import { type FetchAsStringItem, Pool, type PoolConfiguration } from 'postgrejs';
4
+ import type { PostgrejsDecoding, PostgrejsDriverOptions } from './options.js';
5
+ type ReserveHook = (connection: DatabaseConnection) => Promise<void>;
6
+ /**
7
+ * The members of `PostgreSqlConnection` this class reaches at runtime but
8
+ * MikroORM declares `private`. They are plain prototype methods in the
9
+ * published JavaScript; the interface only lets TypeScript see them.
10
+ */
11
+ interface PostgreSqlConnectionInternals {
12
+ composeSessionContextOnReserve(userHook?: ReserveHook): ReserveHook;
13
+ }
14
+ declare const PostgreSqlConnectionBase: abstract new (...args: ConstructorParameters<typeof PostgreSqlConnection>) => AbstractSqlConnection & Pick<PostgreSqlConnection, "callRoutine"> & PostgreSqlConnectionInternals;
15
+ /**
16
+ * MikroORM's PostgreSQL connection, running on PostgreJS.
17
+ *
18
+ * Everything but the pool is `@mikro-orm/postgresql`'s own: this class
19
+ * extends its `PostgreSqlConnection` and replaces only the Kysely dialect,
20
+ * which MikroORM runs every statement through. The dialect is
21
+ * `kysely-postgrejs`'s.
22
+ */
23
+ export declare class PostgrejsConnection extends PostgreSqlConnectionBase {
24
+ protected _pool?: Pool;
25
+ /**
26
+ * Builds the PostgreJS pool and the Kysely dialect over it.
27
+ *
28
+ * @param overrides `driverOptions` from the MikroORM configuration.
29
+ */
30
+ createKyselyDialect(overrides?: PostgrejsDriverOptions): Dialect;
31
+ /** Returns the PostgreJS pool backing this connection. */
32
+ getNativeClient(): Promise<Pool>;
33
+ /**
34
+ * Translates MikroORM's connection settings into a PostgreJS pool
35
+ * configuration.
36
+ *
37
+ * @param overrides Pool options from `driverOptions`; they win over
38
+ * anything derived here.
39
+ */
40
+ mapOptions(overrides?: PostgrejsDriverOptions): PoolConfiguration;
41
+ /**
42
+ * Creates the PostgreJS pool. A seam for tests, which substitute a fake.
43
+ */
44
+ protected createPool(config: PoolConfiguration): Pool;
45
+ }
46
+ /**
47
+ * The `fetchAsString` list for a decoding mode, with whatever the
48
+ * application added through `driverOptions` after it.
49
+ */
50
+ export declare function textTypes(decoding?: PostgrejsDecoding, extra?: FetchAsStringItem[]): FetchAsStringItem[];
51
+ export {};
package/connection.js ADDED
@@ -0,0 +1,138 @@
1
+ import { AbstractSqlConnection, PostgreSqlConnection, Utils, } from '@mikro-orm/postgresql';
2
+ import { PostgrejsDialect } from 'kysely-postgrejs';
3
+ import { parseConnectionString, Pool, } from 'postgrejs';
4
+ import { MIKRO_ORM_TEXT_TYPES, PG_TEXT_TYPES } from './constants.js';
5
+ /*
6
+ * `PostgreSqlConnection` declares `createKyselyDialect`, `getNativeClient`
7
+ * and `mapOptions` with `pg`'s types, which no PostgreJS override can
8
+ * satisfy. Its constructor is re-typed here as producing a plain
9
+ * `AbstractSqlConnection`, so this class inherits everything else at
10
+ * runtime - `callRoutine` and its refcursor handling, the session-context
11
+ * statements - and declares those three members with its own types.
12
+ */
13
+ const PostgreSqlConnectionBase = PostgreSqlConnection;
14
+ /**
15
+ * MikroORM's PostgreSQL connection, running on PostgreJS.
16
+ *
17
+ * Everything but the pool is `@mikro-orm/postgresql`'s own: this class
18
+ * extends its `PostgreSqlConnection` and replaces only the Kysely dialect,
19
+ * which MikroORM runs every statement through. The dialect is
20
+ * `kysely-postgrejs`'s.
21
+ */
22
+ export class PostgrejsConnection extends PostgreSqlConnectionBase {
23
+ _pool;
24
+ /**
25
+ * Builds the PostgreJS pool and the Kysely dialect over it.
26
+ *
27
+ * @param overrides `driverOptions` from the MikroORM configuration.
28
+ */
29
+ createKyselyDialect(overrides) {
30
+ const { onPoolCreated, ...poolOverrides } = overrides ?? {};
31
+ const pool = this.createPool(this.mapOptions(poolOverrides));
32
+ this._pool = pool;
33
+ pool.on('error', (e) => this.logger.warn('info', `PostgreSQL pool error: ${e.message}`));
34
+ void onPoolCreated?.(pool);
35
+ const userOnReserve = this.options.onReserveConnection ??
36
+ this.config.get('onReserveConnection');
37
+ return new PostgrejsDialect({
38
+ pool,
39
+ onCreateConnection: this.options.onCreateConnection ??
40
+ this.config.get('onCreateConnection'),
41
+ onReserveConnection: this.config.get('sessionContext') === 'connection'
42
+ ? this.composeSessionContextOnReserve(userOnReserve)
43
+ : userOnReserve,
44
+ });
45
+ }
46
+ /** Returns the PostgreJS pool backing this connection. */
47
+ async getNativeClient() {
48
+ await this.ensureConnection();
49
+ return this.requireNativeClient(this._pool);
50
+ }
51
+ /**
52
+ * Translates MikroORM's connection settings into a PostgreJS pool
53
+ * configuration.
54
+ *
55
+ * @param overrides Pool options from `driverOptions`; they win over
56
+ * anything derived here.
57
+ */
58
+ mapOptions(overrides = {}) {
59
+ const { decoding, fetchAsString, ...poolOverrides } = overrides;
60
+ /*
61
+ * The URL is read twice. MikroORM's `getConnectionOptions()` already
62
+ * takes host, port, user, password and database from it, with its own
63
+ * rule that an explicit `host` (and the rest) wins over the URL - but
64
+ * it drops the query string, where `sslmode` and `application_name`
65
+ * live. PostgreJS's parser reads those, so its answer goes underneath
66
+ * and MikroORM's fields on top.
67
+ *
68
+ * `schema` is dropped from both. PostgreJS turns it into a
69
+ * `search_path` on every connection, which `pg` never does; MikroORM
70
+ * reads `?schema=` itself and qualifies table names with it.
71
+ */
72
+ const fromMikroOrm = this.getConnectionOptions();
73
+ // Never empty here: `getConnectionOptions()` has just parsed it, and
74
+ // MikroORM's configuration always carries the platform's default URL.
75
+ const url = (this.options.clientUrl ?? this.config.get('clientUrl'));
76
+ const ret = {
77
+ ...parseConnectionString(url),
78
+ ...fromMikroOrm,
79
+ };
80
+ delete ret.schema;
81
+ /*
82
+ * MikroORM answers an empty string for a password nobody gave. `pg`
83
+ * reads that as "none" and falls back to `PGPASSWORD` and `.pgpass`;
84
+ * PostgreJS would send the empty string.
85
+ */
86
+ if (ret.password === '')
87
+ delete ret.password;
88
+ /*
89
+ * Only what was set: PostgreJS's pool takes an `undefined` as a value
90
+ * rather than as "use the default".
91
+ */
92
+ const pool = this.config.get('pool');
93
+ if (pool?.min != null)
94
+ ret.min = pool.min;
95
+ if (pool?.max != null)
96
+ ret.max = pool.max;
97
+ if (pool?.idleTimeoutMillis != null)
98
+ ret.idleTimeoutMillis = pool.idleTimeoutMillis;
99
+ /*
100
+ * Set on the pool, not passed to the dialect. A list the call carries
101
+ * makes PostgreJS prepare every new statement on first sight, to learn
102
+ * its columns before asking for some of them as text - one more round
103
+ * trip and a server-side statement per distinct SQL. MikroORM inlines
104
+ * its parameters, so nearly every statement it sends is new. A list on
105
+ * the connection takes the whole first run as text instead, and moves
106
+ * to per-column formats once a statement is reused.
107
+ */
108
+ ret.fetchAsString = textTypes(decoding, fetchAsString);
109
+ /*
110
+ * A type PostgreJS has no binary decoder for - `regclass`, `citext`,
111
+ * `hstore`, an enum - otherwise arrives as a raw Buffer. MikroORM's
112
+ * schema introspection selects `indrelid::regclass` and reads it as a
113
+ * table name, and `pg` gives the server's text for all of them.
114
+ */
115
+ ret.unknownTypesAsString = true;
116
+ return Utils.mergeConfig(ret, poolOverrides);
117
+ }
118
+ /**
119
+ * Creates the PostgreJS pool. A seam for tests, which substitute a fake.
120
+ */
121
+ createPool(config) {
122
+ return new Pool(config);
123
+ }
124
+ }
125
+ /**
126
+ * The `fetchAsString` list for a decoding mode, with whatever the
127
+ * application added through `driverOptions` after it.
128
+ */
129
+ export function textTypes(decoding = 'native', extra) {
130
+ if (decoding !== 'native' && decoding !== 'pg')
131
+ throw new TypeError(`Unknown decoding "${decoding}" - expected "native" or "pg"`);
132
+ const list = decoding === 'pg'
133
+ ? [...MIKRO_ORM_TEXT_TYPES, ...PG_TEXT_TYPES]
134
+ : [...MIKRO_ORM_TEXT_TYPES];
135
+ if (extra?.length)
136
+ list.push(...extra);
137
+ return list;
138
+ }
package/constants.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { type FetchAsStringItem } from 'postgrejs';
2
+ /**
3
+ * The types MikroORM's PostgreSQL platform reads from strings, asked for
4
+ * as the text the server renders. Every decoding mode uses this list.
5
+ *
6
+ * `@mikro-orm/postgresql` installs `pg` type parsers that keep `date`,
7
+ * `timestamp`, `timestamptz` and `interval` (and their arrays) as raw
8
+ * strings, and its platform parses them itself: `parseDate` with
9
+ * `postgres-date`, `convertIntervalToJSValue` with `postgres-interval`.
10
+ * `time` and `numeric` are strings in `pg` without any parser, and
11
+ * MikroORM's `TimeType` and `DecimalType` hold exactly those strings.
12
+ *
13
+ * Measured, not read off the platform: an entity with one property of
14
+ * every built-in MikroORM type, written and read back through both
15
+ * drivers (`test/C-differential/entities.spec.ts`). Natively decoded,
16
+ * five of them come back wrong:
17
+ *
18
+ * - `date` arrives as a `Date` where `DateType` holds `'2024-03-05'`, and
19
+ * the next flush writes it back as a change.
20
+ * - `timestamp` arrives as a `Date` already placed in the process's time
21
+ * zone, so MikroORM's `timezone` option is applied a second time.
22
+ * - `interval` arrives as PostgreJS's `Interval`, which `postgres-interval`
23
+ * reads as zero.
24
+ * - `time` arrives as a `Date` on 1970-01-01 where `TimeType` holds
25
+ * `'12:30:00'`.
26
+ * - `numeric(10,2)` holding 1.50 arrives as the number 1.5, and
27
+ * `DecimalType` turns that into `'1.5'`, losing the scale.
28
+ *
29
+ * `timestamptz` decodes to the right instant either way; it is here
30
+ * because MikroORM's own driver keeps it a string, so raw results and
31
+ * `parseDate` see what they see on `pg`.
32
+ *
33
+ * Naming a scalar OID also brings that type's array columns back as an
34
+ * array of the server's strings, which is what `postgres-array` makes of
35
+ * them for MikroORM on `pg`. `numeric` is the exception: `pg` decodes a
36
+ * `numeric[]` into numbers, and so does PostgreJS, so its arrays are left
37
+ * alone.
38
+ */
39
+ export declare const MIKRO_ORM_TEXT_TYPES: readonly FetchAsStringItem[];
40
+ /**
41
+ * What `decoding: 'pg'` asks for as text on top of
42
+ * {@link MIKRO_ORM_TEXT_TYPES}: every type whose `pg` value is a string
43
+ * while PostgreJS decodes it into something else.
44
+ *
45
+ * Derived by measurement over 146 scalar and array types through
46
+ * MikroORM's own `em.execute()` on both drivers, starting from the OIDs
47
+ * PostgreJS can decode and `pg-types` has no parser for - see
48
+ * `test/C-differential/values.spec.ts`, which holds every entry to `pg`'s
49
+ * answer. Three types still differ in that mode, by design: `point`,
50
+ * `circle` and `point[]` come back as PostgreJS's `Point` and `Circle`,
51
+ * which carry the same fields `pg`'s plain objects do.
52
+ *
53
+ * Two rules decide which OID is named:
54
+ *
55
+ * - A scalar OID also selects its array columns, as an array of strings.
56
+ * That is `pg`'s answer for `int8[]` and `money[]`, so neither array is
57
+ * listed.
58
+ * - An array OID means the whole literal comes back as one string. `pg`
59
+ * answers that way for every array type it has no parser for, so those
60
+ * are listed by their array OID. `numrange[]` is not one of them: `pg`
61
+ * parses it into an array of strings.
62
+ */
63
+ export declare const PG_TEXT_TYPES: readonly FetchAsStringItem[];
package/constants.js ADDED
@@ -0,0 +1,137 @@
1
+ import { DataTypeOIDs } from 'postgrejs';
2
+ /**
3
+ * The types MikroORM's PostgreSQL platform reads from strings, asked for
4
+ * as the text the server renders. Every decoding mode uses this list.
5
+ *
6
+ * `@mikro-orm/postgresql` installs `pg` type parsers that keep `date`,
7
+ * `timestamp`, `timestamptz` and `interval` (and their arrays) as raw
8
+ * strings, and its platform parses them itself: `parseDate` with
9
+ * `postgres-date`, `convertIntervalToJSValue` with `postgres-interval`.
10
+ * `time` and `numeric` are strings in `pg` without any parser, and
11
+ * MikroORM's `TimeType` and `DecimalType` hold exactly those strings.
12
+ *
13
+ * Measured, not read off the platform: an entity with one property of
14
+ * every built-in MikroORM type, written and read back through both
15
+ * drivers (`test/C-differential/entities.spec.ts`). Natively decoded,
16
+ * five of them come back wrong:
17
+ *
18
+ * - `date` arrives as a `Date` where `DateType` holds `'2024-03-05'`, and
19
+ * the next flush writes it back as a change.
20
+ * - `timestamp` arrives as a `Date` already placed in the process's time
21
+ * zone, so MikroORM's `timezone` option is applied a second time.
22
+ * - `interval` arrives as PostgreJS's `Interval`, which `postgres-interval`
23
+ * reads as zero.
24
+ * - `time` arrives as a `Date` on 1970-01-01 where `TimeType` holds
25
+ * `'12:30:00'`.
26
+ * - `numeric(10,2)` holding 1.50 arrives as the number 1.5, and
27
+ * `DecimalType` turns that into `'1.5'`, losing the scale.
28
+ *
29
+ * `timestamptz` decodes to the right instant either way; it is here
30
+ * because MikroORM's own driver keeps it a string, so raw results and
31
+ * `parseDate` see what they see on `pg`.
32
+ *
33
+ * Naming a scalar OID also brings that type's array columns back as an
34
+ * array of the server's strings, which is what `postgres-array` makes of
35
+ * them for MikroORM on `pg`. `numeric` is the exception: `pg` decodes a
36
+ * `numeric[]` into numbers, and so does PostgreJS, so its arrays are left
37
+ * alone.
38
+ */
39
+ export const MIKRO_ORM_TEXT_TYPES = Object.freeze([
40
+ DataTypeOIDs.date,
41
+ DataTypeOIDs.time,
42
+ DataTypeOIDs.timestamp,
43
+ DataTypeOIDs.timestamptz,
44
+ DataTypeOIDs.interval,
45
+ { oid: DataTypeOIDs.numeric, arrays: false },
46
+ ]);
47
+ /**
48
+ * What `decoding: 'pg'` asks for as text on top of
49
+ * {@link MIKRO_ORM_TEXT_TYPES}: every type whose `pg` value is a string
50
+ * while PostgreJS decodes it into something else.
51
+ *
52
+ * Derived by measurement over 146 scalar and array types through
53
+ * MikroORM's own `em.execute()` on both drivers, starting from the OIDs
54
+ * PostgreJS can decode and `pg-types` has no parser for - see
55
+ * `test/C-differential/values.spec.ts`, which holds every entry to `pg`'s
56
+ * answer. Three types still differ in that mode, by design: `point`,
57
+ * `circle` and `point[]` come back as PostgreJS's `Point` and `Circle`,
58
+ * which carry the same fields `pg`'s plain objects do.
59
+ *
60
+ * Two rules decide which OID is named:
61
+ *
62
+ * - A scalar OID also selects its array columns, as an array of strings.
63
+ * That is `pg`'s answer for `int8[]` and `money[]`, so neither array is
64
+ * listed.
65
+ * - An array OID means the whole literal comes back as one string. `pg`
66
+ * answers that way for every array type it has no parser for, so those
67
+ * are listed by their array OID. `numrange[]` is not one of them: `pg`
68
+ * parses it into an array of strings.
69
+ */
70
+ export const PG_TEXT_TYPES = Object.freeze([
71
+ DataTypeOIDs.int8,
72
+ // `pg-types` has no parser for `money`, so `pg` hands back the server's
73
+ // own rendering, symbol and grouping included. PostgreJS decodes it to
74
+ // a number.
75
+ DataTypeOIDs.money,
76
+ DataTypeOIDs.line,
77
+ DataTypeOIDs.lseg,
78
+ DataTypeOIDs.box,
79
+ DataTypeOIDs.path,
80
+ DataTypeOIDs.polygon,
81
+ // System types PostgreJS decodes to numbers or arrays
82
+ DataTypeOIDs.xid,
83
+ DataTypeOIDs.cid,
84
+ DataTypeOIDs.xid8,
85
+ DataTypeOIDs.int2vector,
86
+ DataTypeOIDs.oidvector,
87
+ // Ranges and multiranges, which PostgreJS decodes to `Range`
88
+ DataTypeOIDs.int4range,
89
+ DataTypeOIDs.numrange,
90
+ DataTypeOIDs.tsrange,
91
+ DataTypeOIDs.tstzrange,
92
+ DataTypeOIDs.daterange,
93
+ DataTypeOIDs.int8range,
94
+ DataTypeOIDs.int4multirange,
95
+ DataTypeOIDs.nummultirange,
96
+ DataTypeOIDs.tsmultirange,
97
+ DataTypeOIDs.tstzmultirange,
98
+ DataTypeOIDs.datemultirange,
99
+ DataTypeOIDs.int8multirange,
100
+ // Arrays `pg` returns as the literal
101
+ DataTypeOIDs._xml,
102
+ DataTypeOIDs._xid8,
103
+ DataTypeOIDs._line,
104
+ DataTypeOIDs._circle,
105
+ DataTypeOIDs._macaddr8,
106
+ DataTypeOIDs._char,
107
+ DataTypeOIDs._name,
108
+ DataTypeOIDs._int2vector,
109
+ DataTypeOIDs._tid,
110
+ DataTypeOIDs._xid,
111
+ DataTypeOIDs._cid,
112
+ DataTypeOIDs._oidvector,
113
+ DataTypeOIDs._lseg,
114
+ DataTypeOIDs._path,
115
+ DataTypeOIDs._box,
116
+ DataTypeOIDs._polygon,
117
+ DataTypeOIDs._bit,
118
+ DataTypeOIDs._varbit,
119
+ DataTypeOIDs._refcursor,
120
+ DataTypeOIDs._txid_snapshot,
121
+ DataTypeOIDs._pg_lsn,
122
+ DataTypeOIDs._tsvector,
123
+ DataTypeOIDs._tsquery,
124
+ DataTypeOIDs._int4range,
125
+ DataTypeOIDs._tsrange,
126
+ DataTypeOIDs._tstzrange,
127
+ DataTypeOIDs._daterange,
128
+ DataTypeOIDs._int8range,
129
+ DataTypeOIDs._jsonpath,
130
+ DataTypeOIDs._pg_snapshot,
131
+ DataTypeOIDs._int4multirange,
132
+ DataTypeOIDs._nummultirange,
133
+ DataTypeOIDs._tsmultirange,
134
+ DataTypeOIDs._tstzmultirange,
135
+ DataTypeOIDs._datemultirange,
136
+ DataTypeOIDs._int8multirange,
137
+ ]);
package/driver.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { type AnyEntity, type Configuration, type Constructor, type EntityClass, type EntityManager as CoreEntityManager, EntityManagerType, type EntitySchema, type IDatabaseDriver, type MikroORM, type Options } from '@mikro-orm/core';
2
+ import { AbstractSqlDriver, BasePostgreSqlEntityManager, SqlMikroORM } from '@mikro-orm/postgresql';
3
+ import { PostgrejsConnection } from './connection.js';
4
+ /**
5
+ * MikroORM's PostgreSQL driver on PostgreJS.
6
+ *
7
+ * The platform, the schema generator and the query builder are
8
+ * `@mikro-orm/postgresql`'s; only the connection differs. The entity
9
+ * manager is the PostgreSQL one every MikroORM PostgreSQL driver shares,
10
+ * `BasePostgreSqlEntityManager`.
11
+ *
12
+ * ```ts
13
+ * import { MikroORM } from 'mikro-orm-postgrejs';
14
+ *
15
+ * const orm = await MikroORM.init({ dbName: 'app', entities: [User] });
16
+ * ```
17
+ */
18
+ export declare class PostgrejsDriver extends AbstractSqlDriver<PostgrejsConnection> {
19
+ [EntityManagerType]: BasePostgreSqlEntityManager<this>;
20
+ constructor(config: Configuration);
21
+ createEntityManager(useContext?: boolean): this[typeof EntityManagerType];
22
+ /** @inheritDoc */
23
+ getORMClass(): Constructor<PostgrejsMikroORM>;
24
+ }
25
+ /**
26
+ * The entity manager of an ORM on this driver - `@mikro-orm/postgresql`'s
27
+ * `EntityManager` under the name it has there.
28
+ */
29
+ export type EntityManager<Driver extends AbstractSqlDriver = PostgrejsDriver> = BasePostgreSqlEntityManager<Driver>;
30
+ export declare const EntityManager: typeof BasePostgreSqlEntityManager;
31
+ type EntityItem = string | EntityClass<AnyEntity> | EntitySchema;
32
+ /** MikroORM options with this driver. */
33
+ export type PostgrejsOptions<EM extends BasePostgreSqlEntityManager<PostgrejsDriver> = BasePostgreSqlEntityManager<PostgrejsDriver>, Entities extends readonly EntityItem[] = EntityItem[]> = Partial<Options<PostgrejsDriver, EM, Entities>>;
34
+ /**
35
+ * A type-safe MikroORM configuration with this driver - the counterpart
36
+ * of `@mikro-orm/postgresql`'s `defineConfig`.
37
+ */
38
+ export declare function definePostgrejsConfig<EM extends BasePostgreSqlEntityManager<PostgrejsDriver> = BasePostgreSqlEntityManager<PostgrejsDriver>, Entities extends readonly EntityItem[] = EntityItem[]>(options: PostgrejsOptions<EM, Entities>): PostgrejsOptions<EM, Entities>;
39
+ /**
40
+ * `MikroORM` with this driver preselected - the counterpart of
41
+ * `@mikro-orm/postgresql`'s `MikroORM`.
42
+ */
43
+ export declare class PostgrejsMikroORM<EM extends BasePostgreSqlEntityManager<PostgrejsDriver> = BasePostgreSqlEntityManager<PostgrejsDriver>, Entities extends readonly EntityItem[] = EntityItem[]> extends SqlMikroORM<PostgrejsDriver, EM, Entities> {
44
+ /** @inheritDoc */
45
+ static init<D extends IDatabaseDriver = PostgrejsDriver, EM extends CoreEntityManager<D> = D[typeof EntityManagerType] & CoreEntityManager<D>, Entities extends readonly EntityItem[] = EntityItem[]>(options: Partial<Options<D, EM, Entities>>): Promise<MikroORM<D, EM, Entities>>;
46
+ /** @inheritDoc */
47
+ constructor(options: PostgrejsOptions<EM, Entities>);
48
+ }
49
+ export {};
package/driver.js ADDED
@@ -0,0 +1,60 @@
1
+ import { defineConfig, EntityManagerType, } from '@mikro-orm/core';
2
+ import { AbstractSqlDriver, BasePostgreSqlEntityManager, PostgreSqlPlatform, SqlMikroORM, } from '@mikro-orm/postgresql';
3
+ import { PostgrejsConnection } from './connection.js';
4
+ /*
5
+ * The driver and the ORM class live in one file because each names the
6
+ * other: the driver answers `getORMClass()`, and the ORM's configuration
7
+ * preselects the driver.
8
+ */
9
+ /**
10
+ * MikroORM's PostgreSQL driver on PostgreJS.
11
+ *
12
+ * The platform, the schema generator and the query builder are
13
+ * `@mikro-orm/postgresql`'s; only the connection differs. The entity
14
+ * manager is the PostgreSQL one every MikroORM PostgreSQL driver shares,
15
+ * `BasePostgreSqlEntityManager`.
16
+ *
17
+ * ```ts
18
+ * import { MikroORM } from 'mikro-orm-postgrejs';
19
+ *
20
+ * const orm = await MikroORM.init({ dbName: 'app', entities: [User] });
21
+ * ```
22
+ */
23
+ export class PostgrejsDriver extends AbstractSqlDriver {
24
+ constructor(config) {
25
+ super(config, new PostgreSqlPlatform(), PostgrejsConnection, [
26
+ 'kysely',
27
+ 'postgrejs',
28
+ ]);
29
+ }
30
+ createEntityManager(useContext) {
31
+ const EntityManagerClass = this.config.get('entityManager', BasePostgreSqlEntityManager);
32
+ return new EntityManagerClass(this.config, this, this.metadata, useContext);
33
+ }
34
+ /** @inheritDoc */
35
+ getORMClass() {
36
+ return PostgrejsMikroORM;
37
+ }
38
+ }
39
+ export const EntityManager = BasePostgreSqlEntityManager;
40
+ /**
41
+ * A type-safe MikroORM configuration with this driver - the counterpart
42
+ * of `@mikro-orm/postgresql`'s `defineConfig`.
43
+ */
44
+ export function definePostgrejsConfig(options) {
45
+ return defineConfig({ driver: PostgrejsDriver, ...options });
46
+ }
47
+ /**
48
+ * `MikroORM` with this driver preselected - the counterpart of
49
+ * `@mikro-orm/postgresql`'s `MikroORM`.
50
+ */
51
+ export class PostgrejsMikroORM extends SqlMikroORM {
52
+ /** @inheritDoc */
53
+ static async init(options) {
54
+ return super.init(definePostgrejsConfig(options));
55
+ }
56
+ /** @inheritDoc */
57
+ constructor(options) {
58
+ super(definePostgrejsConfig(options));
59
+ }
60
+ }
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './connection.js';
2
+ export * from './constants.js';
3
+ export { definePostgrejsConfig as defineConfig, definePostgrejsConfig, EntityManager, PostgrejsMikroORM as MikroORM, type PostgrejsOptions as Options, PostgrejsDriver, PostgrejsMikroORM, type PostgrejsOptions, } from './driver.js';
4
+ export * from './options.js';
5
+ export * from '@mikro-orm/postgresql';
package/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /*
2
+ * Everything `@mikro-orm/postgresql` exports, so this package can replace
3
+ * it in an import. `MikroORM`, `defineConfig`, `Options` and
4
+ * `EntityManager` below are this package's own and shadow the star export.
5
+ */
6
+ export * from './connection.js';
7
+ export * from './constants.js';
8
+ export { definePostgrejsConfig as defineConfig, definePostgrejsConfig, EntityManager, PostgrejsMikroORM as MikroORM, PostgrejsDriver, PostgrejsMikroORM, } from './driver.js';
9
+ export * from './options.js';
10
+ export * from '@mikro-orm/postgresql';
package/options.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { Pool, PoolConfiguration } from 'postgrejs';
2
+ /**
3
+ * How PostgreSQL values are handed to MikroORM.
4
+ *
5
+ * - `'native'` (default): PostgreJS decodes every type itself, except the
6
+ * few MikroORM's platform reads from strings - dates, timestamps,
7
+ * intervals, `time` and `numeric` (see `MIKRO_ORM_TEXT_TYPES`). Entity
8
+ * properties come out the same as on `@mikro-orm/postgresql`; raw rows
9
+ * from `em.execute()` carry PostgreJS's values, so a `count(*)` is a
10
+ * number rather than a string.
11
+ * - `'pg'`: raw rows also carry the values `@mikro-orm/postgresql`
12
+ * gives - `int8` and `money` as strings, ranges and geometric types as
13
+ * the server's text. For code moving off `pg` that reads raw results.
14
+ */
15
+ export type PostgrejsDecoding = 'native' | 'pg';
16
+ /**
17
+ * What `driverOptions` takes with this driver: a PostgreJS pool
18
+ * configuration, plus two options of the driver's own.
19
+ *
20
+ * The connection settings MikroORM knows about (`host`, `port`, `user`,
21
+ * `password`, `dbName`, `clientUrl`, `pool.min`, `pool.max`,
22
+ * `pool.idleTimeoutMillis`) come from MikroORM's own configuration;
23
+ * anything set here wins over them.
24
+ */
25
+ export interface PostgrejsDriverOptions extends PoolConfiguration {
26
+ /** See {@link PostgrejsDecoding}. Defaults to `'native'`. */
27
+ decoding?: PostgrejsDecoding;
28
+ /**
29
+ * Called with the PostgreJS pool once it is created, before any
30
+ * connection is opened - the same hook `@mikro-orm/postgresql` offers
31
+ * for its `pg` pool.
32
+ */
33
+ onPoolCreated?: (pool: Pool) => void | Promise<void>;
34
+ }
package/options.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "mikro-orm-postgrejs",
3
+ "description": "MikroORM driver for PostgreJS - run MikroORM 7 on PostgreJS's wire-protocol client instead of pg",
4
+ "version": "1.1.0",
5
+ "author": "Panates",
6
+ "license": "BSD-3-Clause",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "kysely-postgrejs": "^1.2.4"
10
+ },
11
+ "peerDependencies": {
12
+ "@mikro-orm/core": ">=7.2.13 <7.3.0",
13
+ "@mikro-orm/postgresql": ">=7.2.13 <7.3.0",
14
+ "kysely": ">=0.29.9 <0.31.0",
15
+ "postgrejs": ">=3.15.0 <4"
16
+ },
17
+ "module": "./index.js",
18
+ "types": "./index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./index.d.ts",
22
+ "default": "./index.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "engines": {
27
+ "node": ">=22.17.0"
28
+ },
29
+ "homepage": "https://www.postgrejs.com/",
30
+ "contributors": [
31
+ "Eray Hanoglu <e.hanoglu@panates.com>",
32
+ "Ilker Gurelli <i.gurelli@panates.com>",
33
+ "Onur Tokel <o.tokel@panates.com>",
34
+ "Bircan Yuruk <b.yuruk@panates.com>"
35
+ ],
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/panates/postgrejs-mikro-orm.git"
39
+ },
40
+ "keywords": [
41
+ "mikro-orm",
42
+ "mikro-orm-driver",
43
+ "orm",
44
+ "postgrejs",
45
+ "postgresql",
46
+ "postgres",
47
+ "sql",
48
+ "kysely",
49
+ "typescript",
50
+ "wire-protocol",
51
+ "no-native-bindings"
52
+ ],
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }