joist-orm 2.4.0 → 2.5.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.
Files changed (58) hide show
  1. package/build/drivers/PostgreJsDriver.cjs +216 -0
  2. package/build/drivers/PostgreJsDriver.cjs.map +1 -0
  3. package/build/drivers/PostgreJsDriver.d.cts +87 -0
  4. package/build/drivers/PostgreJsDriver.d.cts.map +1 -0
  5. package/build/drivers/PostgreJsDriver.d.mts +87 -0
  6. package/build/drivers/PostgreJsDriver.d.mts.map +1 -0
  7. package/build/drivers/PostgreJsDriver.js +212 -0
  8. package/build/drivers/PostgreJsDriver.js.map +1 -0
  9. package/build/drivers/PostgresDriver.cjs +165 -196
  10. package/build/drivers/PostgresDriver.cjs.map +1 -1
  11. package/build/drivers/PostgresDriver.d.cts +71 -47
  12. package/build/drivers/PostgresDriver.d.cts.map +1 -1
  13. package/build/drivers/PostgresDriver.d.mts +71 -47
  14. package/build/drivers/PostgresDriver.d.mts.map +1 -1
  15. package/build/drivers/PostgresDriver.js +164 -197
  16. package/build/drivers/PostgresDriver.js.map +1 -1
  17. package/build/drivers/WireRowData.cjs +26 -130
  18. package/build/drivers/WireRowData.cjs.map +1 -1
  19. package/build/drivers/WireRowData.d.cts +26 -33
  20. package/build/drivers/WireRowData.d.cts.map +1 -1
  21. package/build/drivers/WireRowData.d.mts +26 -33
  22. package/build/drivers/WireRowData.d.mts.map +1 -1
  23. package/build/drivers/WireRowData.js +27 -128
  24. package/build/drivers/WireRowData.js.map +1 -1
  25. package/build/drivers/binaryParsers.cjs +21 -13
  26. package/build/drivers/binaryParsers.cjs.map +1 -1
  27. package/build/drivers/binaryParsers.d.cts +16 -18
  28. package/build/drivers/binaryParsers.d.cts.map +1 -1
  29. package/build/drivers/binaryParsers.d.mts +16 -18
  30. package/build/drivers/binaryParsers.d.mts.map +1 -1
  31. package/build/drivers/binaryParsers.js +21 -13
  32. package/build/drivers/binaryParsers.js.map +1 -1
  33. package/build/drivers/patchPgProtocol.cjs.map +1 -1
  34. package/build/drivers/patchPgProtocol.d.cts +2 -3
  35. package/build/drivers/patchPgProtocol.d.cts.map +1 -1
  36. package/build/drivers/patchPgProtocol.d.mts +2 -3
  37. package/build/drivers/patchPgProtocol.d.mts.map +1 -1
  38. package/build/drivers/patchPgProtocol.js.map +1 -1
  39. package/build/drivers/postgresSql.cjs +145 -0
  40. package/build/drivers/postgresSql.cjs.map +1 -0
  41. package/build/drivers/postgresSql.d.cts +19 -0
  42. package/build/drivers/postgresSql.d.cts.map +1 -0
  43. package/build/drivers/postgresSql.d.mts +19 -0
  44. package/build/drivers/postgresSql.d.mts.map +1 -0
  45. package/build/drivers/postgresSql.js +143 -0
  46. package/build/drivers/postgresSql.js.map +1 -0
  47. package/build/index.js +1 -2
  48. package/build/pg-export.d.cts +1 -1
  49. package/build/pg-export.d.mts +1 -1
  50. package/build/postgrejs-export.cjs +3 -0
  51. package/build/postgrejs-export.d.cts +2 -0
  52. package/build/postgrejs-export.d.mts +2 -0
  53. package/build/postgrejs-export.js +1 -0
  54. package/build/seed.d.cts +1 -2
  55. package/build/seed.d.cts.map +1 -1
  56. package/build/seed.d.mts +1 -2
  57. package/build/seed.d.mts.map +1 -1
  58. package/package.json +38 -11
@@ -0,0 +1,216 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
3
+ const require_drivers_postgresSql = require("./postgresSql.cjs");
4
+ const require_drivers_WireRowData = require("./WireRowData.cjs");
5
+ let joist_core = require("joist-core");
6
+ let postgrejs = require("postgrejs");
7
+ postgrejs = require_runtime.__toESM(postgrejs, 1);
8
+ //#region src/drivers/PostgreJsDriver.ts
9
+ /** PostgreSQL over native PostgreJS pools and transaction connections. */
10
+ var PostgreJsDriver = class {
11
+ pool;
12
+ #idAssigner;
13
+ #preloadPlugin;
14
+ onQuery;
15
+ constructor(pool, opts) {
16
+ this.pool = pool;
17
+ this.onQuery = opts?.onQuery;
18
+ this.#preloadPlugin = opts?.preloadPlugin;
19
+ this.#idAssigner = opts?.idAssigner ?? new joist_core.SequenceIdAssigner(async (sql) => (await this.query(void 0, sql, [])).rows);
20
+ }
21
+ /** Executes through the native pool or the transaction's native connection. */
22
+ query(txn, sql, bindings) {
23
+ this.onQuery?.(sql);
24
+ return executeNativeQuery(txn ?? this.pool, sql, bindings);
25
+ }
26
+ /** Executes an entity find with the EntityManager's default limit. */
27
+ async executeFind(em, parsed, settings) {
28
+ const { sql, bindings } = (0, joist_core.buildRawQuery)(parsed, {
29
+ limit: em.entityLimit,
30
+ ...settings
31
+ });
32
+ return (await this.executeQuery(em, sql, bindings)).rows;
33
+ }
34
+ /** Returns PostgreJS command counts and rows through Joist's query boundary. */
35
+ executeQuery(em, sql, bindings) {
36
+ return this.query(em.txn, require_drivers_postgresSql.toPgParams(sql), bindings);
37
+ }
38
+ /** Assigns identifiers with the configured strategy before dependent writes. */
39
+ async assignNewIds(_, todos) {
40
+ await this.#idAssigner.assignNewIds(todos);
41
+ }
42
+ /** Flushes PostgreSQL operations on the active native PostgreJS transaction. */
43
+ async flush(em, entityTodos, joinRows) {
44
+ const txn = em.txn ?? (0, joist_core.fail)("Expected EntityManager.txn to be set");
45
+ await this.#idAssigner.assignNewIds(entityTodos);
46
+ await require_drivers_postgresSql.flushPostgres((sql, bindings) => this.query(txn, sql, bindings), entityTodos, joinRows);
47
+ }
48
+ get defaultPlugins() {
49
+ return { preloadPlugin: this.#preloadPlugin };
50
+ }
51
+ /**
52
+ * Supplies lazy entity rows through PostgreJS's native decoder hook.
53
+ *
54
+ * EntityManager uses this for finds, loads and o2m/o2o/recursive loads.
55
+ * M2m join-table rows, lazy columns and id/count queries use eager results.
56
+ * Deferred parser errors surface on field access.
57
+ */
58
+ async executeFindRowData(em, parsed, settings) {
59
+ const { sql, bindings } = (0, joist_core.buildRawQuery)(parsed, {
60
+ limit: em.entityLimit,
61
+ ...settings
62
+ });
63
+ const pgSql = require_drivers_postgresSql.toPgParams(sql);
64
+ this.onQuery?.(pgSql);
65
+ const decoder = new PostgreJsRowDecoder();
66
+ await (em.txn ?? this.pool).query(pgSql, {
67
+ ...mappingOptions(true),
68
+ params: bindings,
69
+ rowDecoder: decoder
70
+ });
71
+ return decoder.rows;
72
+ }
73
+ /**
74
+ * Preserves transaction hooks and rollback on a dedicated native connection.
75
+ *
76
+ * The callback and all ORM queries share this Connection; close returns it to its pool.
77
+ */
78
+ async transaction(em, fn) {
79
+ if (em.txn) return fn(em.txn);
80
+ const client = await this.pool.acquire();
81
+ let result;
82
+ try {
83
+ await (0, joist_core.driverBeforeBegin)(em, client);
84
+ this.onQuery?.("BEGIN;");
85
+ await executeNativeQuery(client, "BEGIN", []);
86
+ em.txn = client;
87
+ try {
88
+ await (0, joist_core.driverAfterBegin)(em, client);
89
+ result = await fn(client);
90
+ await (0, joist_core.driverBeforeCommit)(em, client);
91
+ this.onQuery?.("COMMIT;");
92
+ await executeNativeQuery(client, "COMMIT", []);
93
+ } catch (error) {
94
+ await executeNativeQuery(client, "ROLLBACK", []);
95
+ throw error;
96
+ } finally {
97
+ em.txn = void 0;
98
+ }
99
+ await (0, joist_core.driverAfterCommit)(em, client);
100
+ } finally {
101
+ await client.close();
102
+ }
103
+ return result;
104
+ }
105
+ };
106
+ /** Records immutable raw rows, leaving all value construction to field access. */
107
+ var PostgreJsRowDecoder = class extends postgrejs.RowDecoder {
108
+ rows = new require_drivers_WireRowData.WireRowData(0);
109
+ #chunk;
110
+ /**
111
+ * Records a row when PostgreJS supplies its payload as a Buffer slice.
112
+ *
113
+ * PostgreJS calls this on paths that collect raw DataRow messages before decoding them.
114
+ * For example, if a query needs the server's money format, it buffers the rows, finishes
115
+ * the SQL response, obtains that format, and then calls decode for each buffered row
116
+ * before resolving the query. These paths call decode even when decodeAt is implemented.
117
+ *
118
+ * `data` is a view of one row's payload within a larger backing ArrayBuffer, not a copy.
119
+ * We reuse one Buffer spanning that backing allocation and forward the row's offset and
120
+ * length to decodeAt. Neither method parses field values; WireRowData does that later
121
+ * when Joist accesses an entity field.
122
+ */
123
+ decode(parsers, data, count, options, fields) {
124
+ if (this.#chunk?.buffer !== data.buffer) this.#chunk = Buffer.from(data.buffer);
125
+ return this.decodeAt(parsers, this.#chunk, data.byteOffset, data.byteLength, count, options, fields);
126
+ }
127
+ /**
128
+ * Records a row directly from PostgreJS's incoming socket buffer.
129
+ *
130
+ * On the streaming query path, PostgreJS first receives RowDescription and resolves the
131
+ * column metadata and parsers. As each subsequent DataRow arrives, it prefers decodeAt
132
+ * over decode when this method exists, passing the socket buffer plus the row payload's
133
+ * offset and length. This avoids allocating a separate Buffer slice for every row.
134
+ *
135
+ * The first row installs column decoders; every call retains the raw row bytes. PostgreJS
136
+ * stores our undefined return value in its ordinary result.rows, which Joist ignores.
137
+ * Once the query completes, executeFindRowData returns this decoder's WireRowData for
138
+ * entity hydration. Actual field parsing remains deferred until a field is accessed.
139
+ */
140
+ decodeAt(parsers, buffer, offset, length, _count, options, fields) {
141
+ if (this.rows.rowCount === 0) this.rows.setColumnDecoders(columnDecoders(parsers, fields, decodingOptions(options)));
142
+ this.rows.addRow(buffer, offset, length);
143
+ }
144
+ };
145
+ /** Selects the options used to decode field values. */
146
+ function decodingOptions(options) {
147
+ return {
148
+ decimalAsString: options.decimalAsString,
149
+ temporalTypes: options.temporalTypes,
150
+ timeZone: options.timeZone,
151
+ dateStyle: options.dateStyle,
152
+ moneyFormat: options.moneyFormat,
153
+ utcDates: options.utcDates,
154
+ fetchAsString: options.fetchAsString,
155
+ unknownTypesAsString: options.unknownTypesAsString
156
+ };
157
+ }
158
+ /** Adapts native parsers to Joist's column decoders without changing their values. */
159
+ function columnDecoders(parsers, fields, options) {
160
+ return fields.map((field, index) => ({
161
+ name: field.fieldName,
162
+ decode: (chunk, start, len) => parsers[index](chunk, start, len, options)
163
+ }));
164
+ }
165
+ let lazyMappingOptions;
166
+ let eagerMappingOptions;
167
+ /** Lazily captures application-wide mapping settings after generated metadata initializes them. */
168
+ function mappingOptions(lazy = false) {
169
+ if (!lazyMappingOptions || !eagerMappingOptions) {
170
+ const temporal = (0, joist_core.getRuntimeConfig)().temporal;
171
+ if (temporal) (0, joist_core.requireTemporal)();
172
+ lazyMappingOptions = {
173
+ rowDecoder: "object",
174
+ fetchCount: 0,
175
+ rollbackOnError: false,
176
+ unknownTypesAsString: true,
177
+ temporalTypes: temporal ? [
178
+ 1082,
179
+ 1083,
180
+ 1114,
181
+ 1184
182
+ ] : false,
183
+ fetchAsString: temporal ? [] : [1083]
184
+ };
185
+ eagerMappingOptions = {
186
+ ...lazyMappingOptions,
187
+ fetchAsString: temporal ? [
188
+ 1082,
189
+ 1083,
190
+ 1114,
191
+ 1184
192
+ ] : [1083]
193
+ };
194
+ }
195
+ return lazy ? lazyMappingOptions : eagerMappingOptions;
196
+ }
197
+ /** Executes with Joist's value representations without changing the caller's pool configuration. */
198
+ async function executeNativeQuery(client, sql, params) {
199
+ return client.query(sql, {
200
+ ...mappingOptions(),
201
+ params
202
+ }).then(toDriverResult);
203
+ }
204
+ /** Uses rowsAffected for writes and rows.length for SELECTs, which PostgreJS does not count in rowsAffected. */
205
+ function toDriverResult(result) {
206
+ const rows = result.rows ?? [];
207
+ return {
208
+ rowCount: result.rowsAffected ?? (result.command === "SELECT" ? rows.length : null),
209
+ rows
210
+ };
211
+ }
212
+ //#endregion
213
+ exports.PostgreJsDriver = PostgreJsDriver;
214
+ exports.PostgreJsRowDecoder = PostgreJsRowDecoder;
215
+
216
+ //# sourceMappingURL=PostgreJsDriver.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PostgreJsDriver.cjs","names":["SequenceIdAssigner","buildRawQuery","toPgParams","fail","flushPostgres","driverBeforeBegin","driverAfterBegin","driverBeforeCommit","driverAfterCommit","native","WireRowData","getRuntimeConfig"],"sources":["../../src/drivers/PostgreJsDriver.ts"],"sourcesContent":["import {\n type Driver,\n type DriverQueryResult,\n type EntityManager,\n type IdAssigner,\n type JoinRowTodo,\n type ParsedFindQuery,\n type PreloadPlugin,\n type RowData,\n SequenceIdAssigner,\n type Todo,\n buildRawQuery,\n driverAfterBegin,\n driverAfterCommit,\n driverBeforeBegin,\n driverBeforeCommit,\n fail,\n getRuntimeConfig,\n requireTemporal,\n} from \"joist-core\";\nimport * as native from \"postgrejs\";\nimport type {\n AnyParseFunction,\n Connection,\n DataMappingOptions,\n FieldInfo,\n Pool,\n QueryOptions,\n QueryResult,\n} from \"postgrejs\";\n\nimport { flushPostgres, toPgParams } from \"./postgresSql.ts\";\nimport { WireRowData } from \"./WireRowData.ts\";\n\nexport interface PostgreJsDriverOpts {\n idAssigner?: IdAssigner;\n /** Sets a default `PreloadPlugin` for any `EntityManager` that uses this driver. */\n preloadPlugin?: PreloadPlugin;\n /** Observes SQL before submission to PostgreJS. */\n onQuery?: (sql: string) => void;\n}\n\n/** PostgreSQL over native PostgreJS pools and transaction connections. */\nexport class PostgreJsDriver implements Driver<Connection> {\n readonly #idAssigner: IdAssigner;\n readonly #preloadPlugin: PreloadPlugin | undefined;\n private readonly onQuery: PostgreJsDriverOpts[\"onQuery\"];\n\n constructor(\n readonly pool: Pool,\n opts?: PostgreJsDriverOpts,\n ) {\n this.onQuery = opts?.onQuery;\n this.#preloadPlugin = opts?.preloadPlugin;\n\n this.#idAssigner =\n opts?.idAssigner ?? new SequenceIdAssigner(async (sql) => (await this.query(undefined, sql, [])).rows);\n }\n\n /** Executes through the native pool or the transaction's native connection. */\n private query(txn: Connection | undefined, sql: string, bindings: readonly unknown[]): Promise<DriverQueryResult> {\n this.onQuery?.(sql);\n return executeNativeQuery(txn ?? this.pool, sql, bindings);\n }\n\n /** Executes an entity find with the EntityManager's default limit. */\n async executeFind(\n em: EntityManager,\n parsed: ParsedFindQuery,\n settings: { limit?: number; offset?: number },\n ): Promise<any[]> {\n const { sql, bindings } = buildRawQuery(parsed, { limit: em.entityLimit, ...settings });\n return (await this.executeQuery(em, sql, bindings)).rows;\n }\n\n /** Returns PostgreJS command counts and rows through Joist's query boundary. */\n executeQuery(em: EntityManager, sql: string, bindings: readonly unknown[]): Promise<DriverQueryResult> {\n return this.query(em.txn as Connection | undefined, toPgParams(sql), bindings);\n }\n\n /** Assigns identifiers with the configured strategy before dependent writes. */\n async assignNewIds(_: EntityManager, todos: Record<string, Todo>): Promise<void> {\n await this.#idAssigner.assignNewIds(todos);\n }\n\n /** Flushes PostgreSQL operations on the active native PostgreJS transaction. */\n async flush(\n em: EntityManager,\n entityTodos: Record<string, Todo>,\n joinRows: Record<string, JoinRowTodo>,\n ): Promise<void> {\n const txn = (em.txn ?? fail(\"Expected EntityManager.txn to be set\")) as Connection;\n await this.#idAssigner.assignNewIds(entityTodos);\n await flushPostgres((sql, bindings) => this.query(txn, sql, bindings), entityTodos, joinRows);\n }\n\n get defaultPlugins() {\n return { preloadPlugin: this.#preloadPlugin };\n }\n\n /**\n * Supplies lazy entity rows through PostgreJS's native decoder hook.\n *\n * EntityManager uses this for finds, loads and o2m/o2o/recursive loads.\n * M2m join-table rows, lazy columns and id/count queries use eager results.\n * Deferred parser errors surface on field access.\n */\n async executeFindRowData(\n em: EntityManager,\n parsed: ParsedFindQuery,\n settings: { limit?: number; offset?: number },\n ): Promise<RowData> {\n const { sql, bindings } = buildRawQuery(parsed, { limit: em.entityLimit, ...settings });\n const pgSql = toPgParams(sql);\n this.onQuery?.(pgSql);\n const decoder = new PostgreJsRowDecoder();\n const client = (em.txn as Connection | undefined) ?? this.pool;\n await client.query(pgSql, {\n ...mappingOptions(true),\n params: bindings as unknown[],\n rowDecoder: decoder,\n });\n return decoder.rows;\n }\n\n /**\n * Preserves transaction hooks and rollback on a dedicated native connection.\n *\n * The callback and all ORM queries share this Connection; close returns it to its pool.\n */\n async transaction<T>(em: EntityManager, fn: (txn: Connection) => Promise<T>): Promise<T> {\n if (em.txn) return fn(em.txn as Connection);\n const client = await this.pool.acquire();\n let result: T;\n try {\n await driverBeforeBegin(em, client);\n this.onQuery?.(\"BEGIN;\");\n await executeNativeQuery(client, \"BEGIN\", []);\n em.txn = client;\n try {\n await driverAfterBegin(em, client);\n result = await fn(client);\n await driverBeforeCommit(em, client);\n this.onQuery?.(\"COMMIT;\");\n await executeNativeQuery(client, \"COMMIT\", []);\n } catch (error) {\n await executeNativeQuery(client, \"ROLLBACK\", []);\n throw error;\n } finally {\n em.txn = undefined;\n }\n await driverAfterCommit(em, client);\n } finally {\n await client.close();\n }\n return result;\n }\n}\n\n/** Records immutable raw rows, leaving all value construction to field access. */\nexport class PostgreJsRowDecoder extends native.RowDecoder {\n readonly rows = new WireRowData(0);\n #chunk: Buffer | undefined;\n\n /**\n * Records a row when PostgreJS supplies its payload as a Buffer slice.\n *\n * PostgreJS calls this on paths that collect raw DataRow messages before decoding them.\n * For example, if a query needs the server's money format, it buffers the rows, finishes\n * the SQL response, obtains that format, and then calls decode for each buffered row\n * before resolving the query. These paths call decode even when decodeAt is implemented.\n *\n * `data` is a view of one row's payload within a larger backing ArrayBuffer, not a copy.\n * We reuse one Buffer spanning that backing allocation and forward the row's offset and\n * length to decodeAt. Neither method parses field values; WireRowData does that later\n * when Joist accesses an entity field.\n */\n decode(parsers: AnyParseFunction[], data: Buffer, count: number, options: DataMappingOptions, fields: FieldInfo[]) {\n if (this.#chunk?.buffer !== data.buffer) this.#chunk = Buffer.from(data.buffer);\n return this.decodeAt(parsers, this.#chunk!, data.byteOffset, data.byteLength, count, options, fields);\n }\n\n /**\n * Records a row directly from PostgreJS's incoming socket buffer.\n *\n * On the streaming query path, PostgreJS first receives RowDescription and resolves the\n * column metadata and parsers. As each subsequent DataRow arrives, it prefers decodeAt\n * over decode when this method exists, passing the socket buffer plus the row payload's\n * offset and length. This avoids allocating a separate Buffer slice for every row.\n *\n * The first row installs column decoders; every call retains the raw row bytes. PostgreJS\n * stores our undefined return value in its ordinary result.rows, which Joist ignores.\n * Once the query completes, executeFindRowData returns this decoder's WireRowData for\n * entity hydration. Actual field parsing remains deferred until a field is accessed.\n */\n override decodeAt(\n parsers: AnyParseFunction[],\n buffer: Buffer,\n offset: number,\n length: number,\n _count: number,\n options: DataMappingOptions,\n fields: FieldInfo[],\n ) {\n if (this.rows.rowCount === 0) {\n // Use separate function scopes and copy only decoding options so the stored closures cannot\n // capture decodeAt's socket buffer or the original query options, which also hold params.\n this.rows.setColumnDecoders(columnDecoders(parsers, fields, decodingOptions(options)));\n }\n this.rows.addRow(buffer, offset, length);\n return undefined;\n }\n}\n\n/** Selects the options used to decode field values. */\nfunction decodingOptions(options: DataMappingOptions): DataMappingOptions {\n return {\n decimalAsString: options.decimalAsString,\n temporalTypes: options.temporalTypes,\n timeZone: options.timeZone,\n dateStyle: options.dateStyle,\n moneyFormat: options.moneyFormat,\n utcDates: options.utcDates,\n fetchAsString: options.fetchAsString,\n unknownTypesAsString: options.unknownTypesAsString,\n };\n}\n\n/** Adapts native parsers to Joist's column decoders without changing their values. */\nfunction columnDecoders(parsers: AnyParseFunction[], fields: FieldInfo[], options: DataMappingOptions) {\n return fields.map((field, index) => ({\n name: field.fieldName,\n decode: (chunk: Buffer, start: number, len: number) => parsers[index](chunk, start, len, options),\n }));\n}\n\nlet lazyMappingOptions: QueryOptions | undefined;\nlet eagerMappingOptions: QueryOptions | undefined;\n\n/** Lazily captures application-wide mapping settings after generated metadata initializes them. */\nfunction mappingOptions(lazy = false): QueryOptions {\n if (!lazyMappingOptions || !eagerMappingOptions) {\n const temporal = getRuntimeConfig().temporal;\n if (temporal) requireTemporal();\n lazyMappingOptions = {\n rowDecoder: \"object\",\n fetchCount: 0,\n rollbackOnError: false,\n unknownTypesAsString: true,\n temporalTypes: temporal ? [1082, 1083, 1114, 1184] : false,\n fetchAsString: temporal ? [] : [1083],\n };\n // Accept Temporal parameters on both paths, but return strings for raw queries to preserve\n // Joist's node-pg-compatible result types. Parsing through Date would lose microseconds;\n // returning Temporal objects would change the values callers receive when switching drivers.\n eagerMappingOptions = { ...lazyMappingOptions, fetchAsString: temporal ? [1082, 1083, 1114, 1184] : [1083] };\n }\n return lazy ? lazyMappingOptions : eagerMappingOptions;\n}\n\n/** Executes with Joist's value representations without changing the caller's pool configuration. */\nasync function executeNativeQuery(\n client: Pool | Connection,\n sql: string,\n params: readonly unknown[],\n): Promise<DriverQueryResult> {\n return client\n .query(sql, {\n ...mappingOptions(),\n params: params as unknown[],\n })\n .then(toDriverResult);\n}\n\n/** Uses rowsAffected for writes and rows.length for SELECTs, which PostgreJS does not count in rowsAffected. */\nfunction toDriverResult(result: QueryResult): DriverQueryResult {\n const rows = result.rows ?? [];\n return {\n rowCount: result.rowsAffected ?? (result.command === \"SELECT\" ? rows.length : null),\n rows,\n };\n}\n"],"mappings":"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"}
@@ -0,0 +1,87 @@
1
+ import { WireRowData } from "./WireRowData.cjs";
2
+ import { Driver, DriverQueryResult, EntityManager, IdAssigner, JoinRowTodo, ParsedFindQuery, PreloadPlugin, RowData, Todo } from "joist-core";
3
+ import * as native from "postgrejs";
4
+ import { AnyParseFunction, Connection, DataMappingOptions, FieldInfo, Pool } from "postgrejs";
5
+ //#region src/drivers/PostgreJsDriver.d.ts
6
+ export interface PostgreJsDriverOpts {
7
+ idAssigner?: IdAssigner;
8
+ /** Sets a default `PreloadPlugin` for any `EntityManager` that uses this driver. */
9
+ preloadPlugin?: PreloadPlugin;
10
+ /** Observes SQL before submission to PostgreJS. */
11
+ onQuery?: (sql: string) => void;
12
+ }
13
+ /** PostgreSQL over native PostgreJS pools and transaction connections. */
14
+ export declare class PostgreJsDriver implements Driver<Connection> {
15
+ #private;
16
+ readonly pool: Pool;
17
+ private readonly onQuery;
18
+ constructor(pool: Pool, opts?: PostgreJsDriverOpts);
19
+ /** Executes through the native pool or the transaction's native connection. */
20
+ private query;
21
+ /** Executes an entity find with the EntityManager's default limit. */
22
+ executeFind(em: EntityManager, parsed: ParsedFindQuery, settings: {
23
+ limit?: number;
24
+ offset?: number;
25
+ }): Promise<any[]>;
26
+ /** Returns PostgreJS command counts and rows through Joist's query boundary. */
27
+ executeQuery(em: EntityManager, sql: string, bindings: readonly unknown[]): Promise<DriverQueryResult>;
28
+ /** Assigns identifiers with the configured strategy before dependent writes. */
29
+ assignNewIds(_: EntityManager, todos: Record<string, Todo>): Promise<void>;
30
+ /** Flushes PostgreSQL operations on the active native PostgreJS transaction. */
31
+ flush(em: EntityManager, entityTodos: Record<string, Todo>, joinRows: Record<string, JoinRowTodo>): Promise<void>;
32
+ get defaultPlugins(): {
33
+ preloadPlugin: any;
34
+ };
35
+ /**
36
+ * Supplies lazy entity rows through PostgreJS's native decoder hook.
37
+ *
38
+ * EntityManager uses this for finds, loads and o2m/o2o/recursive loads.
39
+ * M2m join-table rows, lazy columns and id/count queries use eager results.
40
+ * Deferred parser errors surface on field access.
41
+ */
42
+ executeFindRowData(em: EntityManager, parsed: ParsedFindQuery, settings: {
43
+ limit?: number;
44
+ offset?: number;
45
+ }): Promise<RowData>;
46
+ /**
47
+ * Preserves transaction hooks and rollback on a dedicated native connection.
48
+ *
49
+ * The callback and all ORM queries share this Connection; close returns it to its pool.
50
+ */
51
+ transaction<T>(em: EntityManager, fn: (txn: Connection) => Promise<T>): Promise<T>;
52
+ }
53
+ /** Records immutable raw rows, leaving all value construction to field access. */
54
+ export declare class PostgreJsRowDecoder extends native.RowDecoder {
55
+ #private;
56
+ readonly rows: WireRowData;
57
+ /**
58
+ * Records a row when PostgreJS supplies its payload as a Buffer slice.
59
+ *
60
+ * PostgreJS calls this on paths that collect raw DataRow messages before decoding them.
61
+ * For example, if a query needs the server's money format, it buffers the rows, finishes
62
+ * the SQL response, obtains that format, and then calls decode for each buffered row
63
+ * before resolving the query. These paths call decode even when decodeAt is implemented.
64
+ *
65
+ * `data` is a view of one row's payload within a larger backing ArrayBuffer, not a copy.
66
+ * We reuse one Buffer spanning that backing allocation and forward the row's offset and
67
+ * length to decodeAt. Neither method parses field values; WireRowData does that later
68
+ * when Joist accesses an entity field.
69
+ */
70
+ decode(parsers: AnyParseFunction[], data: Buffer, count: number, options: DataMappingOptions, fields: FieldInfo[]): undefined;
71
+ /**
72
+ * Records a row directly from PostgreJS's incoming socket buffer.
73
+ *
74
+ * On the streaming query path, PostgreJS first receives RowDescription and resolves the
75
+ * column metadata and parsers. As each subsequent DataRow arrives, it prefers decodeAt
76
+ * over decode when this method exists, passing the socket buffer plus the row payload's
77
+ * offset and length. This avoids allocating a separate Buffer slice for every row.
78
+ *
79
+ * The first row installs column decoders; every call retains the raw row bytes. PostgreJS
80
+ * stores our undefined return value in its ordinary result.rows, which Joist ignores.
81
+ * Once the query completes, executeFindRowData returns this decoder's WireRowData for
82
+ * entity hydration. Actual field parsing remains deferred until a field is accessed.
83
+ */
84
+ decodeAt(parsers: AnyParseFunction[], buffer: Buffer, offset: number, length: number, _count: number, options: DataMappingOptions, fields: FieldInfo[]): undefined;
85
+ }
86
+ //#endregion
87
+ //# sourceMappingURL=PostgreJsDriver.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PostgreJsDriver.d.cts","names":[],"sources":["../../src/drivers/PostgreJsDriver.ts"],"mappings":";;;;;iBAkCiB;EACf,aAAa;;EAEb,gBAAgB;;EAEhB,WAAW;;;qBAIA,2BAA2B,OAAO;;WAMlC,MAAM;mBAHA;EAEjB,YACW,MAAM,MACf,OAAO;;UAUD;;EAMF,YACJ,IAAI,eACJ,QAAQ,iBACR;IAAY;IAAgB;MAC3B;;EAMH,aAAa,IAAI,eAAe,aAAa,+BAA+B,QAAQ;;EAK9E,aAAa,GAAG,eAAe,OAAO,eAAe,QAAQ;;EAK7D,MACJ,IAAI,eACJ,aAAa,eAAe,OAC5B,UAAU,eAAe,eACxB;MAMC;IACO;;;;;;;;;EAUL,mBACJ,IAAI,eACJ,QAAQ,iBACR;IAAY;IAAgB;MAC3B,QAAQ;;;;;;EAmBL,YAAY,GAAG,IAAI,eAAe,KAAK,KAAK,eAAe,QAAQ,KAAK,QAAQ;;;qBA8B3E,4BAA4B,OAAO;;WACrC,MAAI;;;;;;;;;;;;;;EAgBb,OAAO,SAAS,oBAAoB,MAAM,QAAQ,eAAe,SAAS,oBAAoB,QAAQ;;;;;;;;;;;;;;EAkB7F,SACP,SAAS,oBACT,QAAQ,QACR,gBACA,gBACA,gBACA,SAAS,oBACT,QAAQ"}
@@ -0,0 +1,87 @@
1
+ import { WireRowData } from "./WireRowData.mjs";
2
+ import { Driver, DriverQueryResult, EntityManager, IdAssigner, JoinRowTodo, ParsedFindQuery, PreloadPlugin, RowData, Todo } from "joist-core";
3
+ import * as native from "postgrejs";
4
+ import { AnyParseFunction, Connection, DataMappingOptions, FieldInfo, Pool } from "postgrejs";
5
+ //#region src/drivers/PostgreJsDriver.d.ts
6
+ export interface PostgreJsDriverOpts {
7
+ idAssigner?: IdAssigner;
8
+ /** Sets a default `PreloadPlugin` for any `EntityManager` that uses this driver. */
9
+ preloadPlugin?: PreloadPlugin;
10
+ /** Observes SQL before submission to PostgreJS. */
11
+ onQuery?: (sql: string) => void;
12
+ }
13
+ /** PostgreSQL over native PostgreJS pools and transaction connections. */
14
+ export declare class PostgreJsDriver implements Driver<Connection> {
15
+ #private;
16
+ readonly pool: Pool;
17
+ private readonly onQuery;
18
+ constructor(pool: Pool, opts?: PostgreJsDriverOpts);
19
+ /** Executes through the native pool or the transaction's native connection. */
20
+ private query;
21
+ /** Executes an entity find with the EntityManager's default limit. */
22
+ executeFind(em: EntityManager, parsed: ParsedFindQuery, settings: {
23
+ limit?: number;
24
+ offset?: number;
25
+ }): Promise<any[]>;
26
+ /** Returns PostgreJS command counts and rows through Joist's query boundary. */
27
+ executeQuery(em: EntityManager, sql: string, bindings: readonly unknown[]): Promise<DriverQueryResult>;
28
+ /** Assigns identifiers with the configured strategy before dependent writes. */
29
+ assignNewIds(_: EntityManager, todos: Record<string, Todo>): Promise<void>;
30
+ /** Flushes PostgreSQL operations on the active native PostgreJS transaction. */
31
+ flush(em: EntityManager, entityTodos: Record<string, Todo>, joinRows: Record<string, JoinRowTodo>): Promise<void>;
32
+ get defaultPlugins(): {
33
+ preloadPlugin: any;
34
+ };
35
+ /**
36
+ * Supplies lazy entity rows through PostgreJS's native decoder hook.
37
+ *
38
+ * EntityManager uses this for finds, loads and o2m/o2o/recursive loads.
39
+ * M2m join-table rows, lazy columns and id/count queries use eager results.
40
+ * Deferred parser errors surface on field access.
41
+ */
42
+ executeFindRowData(em: EntityManager, parsed: ParsedFindQuery, settings: {
43
+ limit?: number;
44
+ offset?: number;
45
+ }): Promise<RowData>;
46
+ /**
47
+ * Preserves transaction hooks and rollback on a dedicated native connection.
48
+ *
49
+ * The callback and all ORM queries share this Connection; close returns it to its pool.
50
+ */
51
+ transaction<T>(em: EntityManager, fn: (txn: Connection) => Promise<T>): Promise<T>;
52
+ }
53
+ /** Records immutable raw rows, leaving all value construction to field access. */
54
+ export declare class PostgreJsRowDecoder extends native.RowDecoder {
55
+ #private;
56
+ readonly rows: WireRowData;
57
+ /**
58
+ * Records a row when PostgreJS supplies its payload as a Buffer slice.
59
+ *
60
+ * PostgreJS calls this on paths that collect raw DataRow messages before decoding them.
61
+ * For example, if a query needs the server's money format, it buffers the rows, finishes
62
+ * the SQL response, obtains that format, and then calls decode for each buffered row
63
+ * before resolving the query. These paths call decode even when decodeAt is implemented.
64
+ *
65
+ * `data` is a view of one row's payload within a larger backing ArrayBuffer, not a copy.
66
+ * We reuse one Buffer spanning that backing allocation and forward the row's offset and
67
+ * length to decodeAt. Neither method parses field values; WireRowData does that later
68
+ * when Joist accesses an entity field.
69
+ */
70
+ decode(parsers: AnyParseFunction[], data: Buffer, count: number, options: DataMappingOptions, fields: FieldInfo[]): undefined;
71
+ /**
72
+ * Records a row directly from PostgreJS's incoming socket buffer.
73
+ *
74
+ * On the streaming query path, PostgreJS first receives RowDescription and resolves the
75
+ * column metadata and parsers. As each subsequent DataRow arrives, it prefers decodeAt
76
+ * over decode when this method exists, passing the socket buffer plus the row payload's
77
+ * offset and length. This avoids allocating a separate Buffer slice for every row.
78
+ *
79
+ * The first row installs column decoders; every call retains the raw row bytes. PostgreJS
80
+ * stores our undefined return value in its ordinary result.rows, which Joist ignores.
81
+ * Once the query completes, executeFindRowData returns this decoder's WireRowData for
82
+ * entity hydration. Actual field parsing remains deferred until a field is accessed.
83
+ */
84
+ decodeAt(parsers: AnyParseFunction[], buffer: Buffer, offset: number, length: number, _count: number, options: DataMappingOptions, fields: FieldInfo[]): undefined;
85
+ }
86
+ //#endregion
87
+ //# sourceMappingURL=PostgreJsDriver.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PostgreJsDriver.d.mts","names":[],"sources":["../../src/drivers/PostgreJsDriver.ts"],"mappings":";;;;;iBAkCiB;EACf,aAAa;;EAEb,gBAAgB;;EAEhB,WAAW;;;qBAIA,2BAA2B,OAAO;;WAMlC,MAAM;mBAHA;EAEjB,YACW,MAAM,MACf,OAAO;;UAUD;;EAMF,YACJ,IAAI,eACJ,QAAQ,iBACR;IAAY;IAAgB;MAC3B;;EAMH,aAAa,IAAI,eAAe,aAAa,+BAA+B,QAAQ;;EAK9E,aAAa,GAAG,eAAe,OAAO,eAAe,QAAQ;;EAK7D,MACJ,IAAI,eACJ,aAAa,eAAe,OAC5B,UAAU,eAAe,eACxB;MAMC;IACO;;;;;;;;;EAUL,mBACJ,IAAI,eACJ,QAAQ,iBACR;IAAY;IAAgB;MAC3B,QAAQ;;;;;;EAmBL,YAAY,GAAG,IAAI,eAAe,KAAK,KAAK,eAAe,QAAQ,KAAK,QAAQ;;;qBA8B3E,4BAA4B,OAAO;;WACrC,MAAI;;;;;;;;;;;;;;EAgBb,OAAO,SAAS,oBAAoB,MAAM,QAAQ,eAAe,SAAS,oBAAoB,QAAQ;;;;;;;;;;;;;;EAkB7F,SACP,SAAS,oBACT,QAAQ,QACR,gBACA,gBACA,gBACA,SAAS,oBACT,QAAQ"}
@@ -0,0 +1,212 @@
1
+ import { flushPostgres, toPgParams } from "./postgresSql.js";
2
+ import { WireRowData } from "./WireRowData.js";
3
+ import { SequenceIdAssigner, buildRawQuery, driverAfterBegin, driverAfterCommit, driverBeforeBegin, driverBeforeCommit, fail, getRuntimeConfig, requireTemporal } from "joist-core";
4
+ import * as native from "postgrejs";
5
+ //#region src/drivers/PostgreJsDriver.ts
6
+ /** PostgreSQL over native PostgreJS pools and transaction connections. */
7
+ var PostgreJsDriver = class {
8
+ pool;
9
+ #idAssigner;
10
+ #preloadPlugin;
11
+ onQuery;
12
+ constructor(pool, opts) {
13
+ this.pool = pool;
14
+ this.onQuery = opts?.onQuery;
15
+ this.#preloadPlugin = opts?.preloadPlugin;
16
+ this.#idAssigner = opts?.idAssigner ?? new SequenceIdAssigner(async (sql) => (await this.query(void 0, sql, [])).rows);
17
+ }
18
+ /** Executes through the native pool or the transaction's native connection. */
19
+ query(txn, sql, bindings) {
20
+ this.onQuery?.(sql);
21
+ return executeNativeQuery(txn ?? this.pool, sql, bindings);
22
+ }
23
+ /** Executes an entity find with the EntityManager's default limit. */
24
+ async executeFind(em, parsed, settings) {
25
+ const { sql, bindings } = buildRawQuery(parsed, {
26
+ limit: em.entityLimit,
27
+ ...settings
28
+ });
29
+ return (await this.executeQuery(em, sql, bindings)).rows;
30
+ }
31
+ /** Returns PostgreJS command counts and rows through Joist's query boundary. */
32
+ executeQuery(em, sql, bindings) {
33
+ return this.query(em.txn, toPgParams(sql), bindings);
34
+ }
35
+ /** Assigns identifiers with the configured strategy before dependent writes. */
36
+ async assignNewIds(_, todos) {
37
+ await this.#idAssigner.assignNewIds(todos);
38
+ }
39
+ /** Flushes PostgreSQL operations on the active native PostgreJS transaction. */
40
+ async flush(em, entityTodos, joinRows) {
41
+ const txn = em.txn ?? fail("Expected EntityManager.txn to be set");
42
+ await this.#idAssigner.assignNewIds(entityTodos);
43
+ await flushPostgres((sql, bindings) => this.query(txn, sql, bindings), entityTodos, joinRows);
44
+ }
45
+ get defaultPlugins() {
46
+ return { preloadPlugin: this.#preloadPlugin };
47
+ }
48
+ /**
49
+ * Supplies lazy entity rows through PostgreJS's native decoder hook.
50
+ *
51
+ * EntityManager uses this for finds, loads and o2m/o2o/recursive loads.
52
+ * M2m join-table rows, lazy columns and id/count queries use eager results.
53
+ * Deferred parser errors surface on field access.
54
+ */
55
+ async executeFindRowData(em, parsed, settings) {
56
+ const { sql, bindings } = buildRawQuery(parsed, {
57
+ limit: em.entityLimit,
58
+ ...settings
59
+ });
60
+ const pgSql = toPgParams(sql);
61
+ this.onQuery?.(pgSql);
62
+ const decoder = new PostgreJsRowDecoder();
63
+ await (em.txn ?? this.pool).query(pgSql, {
64
+ ...mappingOptions(true),
65
+ params: bindings,
66
+ rowDecoder: decoder
67
+ });
68
+ return decoder.rows;
69
+ }
70
+ /**
71
+ * Preserves transaction hooks and rollback on a dedicated native connection.
72
+ *
73
+ * The callback and all ORM queries share this Connection; close returns it to its pool.
74
+ */
75
+ async transaction(em, fn) {
76
+ if (em.txn) return fn(em.txn);
77
+ const client = await this.pool.acquire();
78
+ let result;
79
+ try {
80
+ await driverBeforeBegin(em, client);
81
+ this.onQuery?.("BEGIN;");
82
+ await executeNativeQuery(client, "BEGIN", []);
83
+ em.txn = client;
84
+ try {
85
+ await driverAfterBegin(em, client);
86
+ result = await fn(client);
87
+ await driverBeforeCommit(em, client);
88
+ this.onQuery?.("COMMIT;");
89
+ await executeNativeQuery(client, "COMMIT", []);
90
+ } catch (error) {
91
+ await executeNativeQuery(client, "ROLLBACK", []);
92
+ throw error;
93
+ } finally {
94
+ em.txn = void 0;
95
+ }
96
+ await driverAfterCommit(em, client);
97
+ } finally {
98
+ await client.close();
99
+ }
100
+ return result;
101
+ }
102
+ };
103
+ /** Records immutable raw rows, leaving all value construction to field access. */
104
+ var PostgreJsRowDecoder = class extends native.RowDecoder {
105
+ rows = new WireRowData(0);
106
+ #chunk;
107
+ /**
108
+ * Records a row when PostgreJS supplies its payload as a Buffer slice.
109
+ *
110
+ * PostgreJS calls this on paths that collect raw DataRow messages before decoding them.
111
+ * For example, if a query needs the server's money format, it buffers the rows, finishes
112
+ * the SQL response, obtains that format, and then calls decode for each buffered row
113
+ * before resolving the query. These paths call decode even when decodeAt is implemented.
114
+ *
115
+ * `data` is a view of one row's payload within a larger backing ArrayBuffer, not a copy.
116
+ * We reuse one Buffer spanning that backing allocation and forward the row's offset and
117
+ * length to decodeAt. Neither method parses field values; WireRowData does that later
118
+ * when Joist accesses an entity field.
119
+ */
120
+ decode(parsers, data, count, options, fields) {
121
+ if (this.#chunk?.buffer !== data.buffer) this.#chunk = Buffer.from(data.buffer);
122
+ return this.decodeAt(parsers, this.#chunk, data.byteOffset, data.byteLength, count, options, fields);
123
+ }
124
+ /**
125
+ * Records a row directly from PostgreJS's incoming socket buffer.
126
+ *
127
+ * On the streaming query path, PostgreJS first receives RowDescription and resolves the
128
+ * column metadata and parsers. As each subsequent DataRow arrives, it prefers decodeAt
129
+ * over decode when this method exists, passing the socket buffer plus the row payload's
130
+ * offset and length. This avoids allocating a separate Buffer slice for every row.
131
+ *
132
+ * The first row installs column decoders; every call retains the raw row bytes. PostgreJS
133
+ * stores our undefined return value in its ordinary result.rows, which Joist ignores.
134
+ * Once the query completes, executeFindRowData returns this decoder's WireRowData for
135
+ * entity hydration. Actual field parsing remains deferred until a field is accessed.
136
+ */
137
+ decodeAt(parsers, buffer, offset, length, _count, options, fields) {
138
+ if (this.rows.rowCount === 0) this.rows.setColumnDecoders(columnDecoders(parsers, fields, decodingOptions(options)));
139
+ this.rows.addRow(buffer, offset, length);
140
+ }
141
+ };
142
+ /** Selects the options used to decode field values. */
143
+ function decodingOptions(options) {
144
+ return {
145
+ decimalAsString: options.decimalAsString,
146
+ temporalTypes: options.temporalTypes,
147
+ timeZone: options.timeZone,
148
+ dateStyle: options.dateStyle,
149
+ moneyFormat: options.moneyFormat,
150
+ utcDates: options.utcDates,
151
+ fetchAsString: options.fetchAsString,
152
+ unknownTypesAsString: options.unknownTypesAsString
153
+ };
154
+ }
155
+ /** Adapts native parsers to Joist's column decoders without changing their values. */
156
+ function columnDecoders(parsers, fields, options) {
157
+ return fields.map((field, index) => ({
158
+ name: field.fieldName,
159
+ decode: (chunk, start, len) => parsers[index](chunk, start, len, options)
160
+ }));
161
+ }
162
+ let lazyMappingOptions;
163
+ let eagerMappingOptions;
164
+ /** Lazily captures application-wide mapping settings after generated metadata initializes them. */
165
+ function mappingOptions(lazy = false) {
166
+ if (!lazyMappingOptions || !eagerMappingOptions) {
167
+ const temporal = getRuntimeConfig().temporal;
168
+ if (temporal) requireTemporal();
169
+ lazyMappingOptions = {
170
+ rowDecoder: "object",
171
+ fetchCount: 0,
172
+ rollbackOnError: false,
173
+ unknownTypesAsString: true,
174
+ temporalTypes: temporal ? [
175
+ 1082,
176
+ 1083,
177
+ 1114,
178
+ 1184
179
+ ] : false,
180
+ fetchAsString: temporal ? [] : [1083]
181
+ };
182
+ eagerMappingOptions = {
183
+ ...lazyMappingOptions,
184
+ fetchAsString: temporal ? [
185
+ 1082,
186
+ 1083,
187
+ 1114,
188
+ 1184
189
+ ] : [1083]
190
+ };
191
+ }
192
+ return lazy ? lazyMappingOptions : eagerMappingOptions;
193
+ }
194
+ /** Executes with Joist's value representations without changing the caller's pool configuration. */
195
+ async function executeNativeQuery(client, sql, params) {
196
+ return client.query(sql, {
197
+ ...mappingOptions(),
198
+ params
199
+ }).then(toDriverResult);
200
+ }
201
+ /** Uses rowsAffected for writes and rows.length for SELECTs, which PostgreJS does not count in rowsAffected. */
202
+ function toDriverResult(result) {
203
+ const rows = result.rows ?? [];
204
+ return {
205
+ rowCount: result.rowsAffected ?? (result.command === "SELECT" ? rows.length : null),
206
+ rows
207
+ };
208
+ }
209
+ //#endregion
210
+ export { PostgreJsDriver, PostgreJsRowDecoder };
211
+
212
+ //# sourceMappingURL=PostgreJsDriver.js.map