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
@@ -1,51 +1,40 @@
1
- import { registerDatabaseBinaryParsers, registerTemporalBinaryParsers } from "./binaryParsers.js";
1
+ import { getBinaryTypeParser, registerDatabaseBinaryParsers, registerTemporalBinaryParsers } from "./binaryParsers.js";
2
2
  import { ensureLazyDataRows } from "./patchPgProtocol.js";
3
- import { executeRowDataQuery, isRowDataCapableClient } from "./WireRowData.js";
4
- import { JoinRowOperation, PojoRowData, SequenceIdAssigner, buildRawQuery, cleanSql, driverAfterBegin, driverAfterCommit, driverBeforeBegin, driverBeforeCommit, ensureRectangularArraySizes, fail, generateOps, getRuntimeConfig, kq, kqDot, partition } from "joist-core";
3
+ import { flushPostgres, toPgParams } from "./postgresSql.js";
4
+ import { WireRowData } from "./WireRowData.js";
5
+ import { createRequire } from "node:module";
6
+ import { PojoRowData, SequenceIdAssigner, buildRawQuery, driverAfterBegin, driverAfterCommit, driverBeforeBegin, driverBeforeCommit, fail, getRuntimeConfig } from "joist-core";
5
7
  import pg from "pg";
6
8
  import { builtins, getTypeParser } from "pg-types";
7
9
  import array from "postgres-array";
8
10
  //#region src/drivers/PostgresDriver.ts
9
- /**
10
- * Implements the `Driver` interface for Postgres.
11
- *
12
- * This is the canonical driver implementation and leverages several aspects of
13
- * Postgres for the best performance, i.e.:
14
- *
15
- * - Deferred foreign key constraints are used to allow bulk inserting/updating
16
- * all entities without any topographic sorting/ordering issues.
17
- *
18
- * - Sequences are used to bulk-assign + then bulk-insert all entities, to again
19
- * avoid issues with ordering issues (cannot bulk insert A w/o knowing the id of B).
20
- *
21
- * - We use a pg-specific bulk update syntax.
22
- *
23
- * Query pipelining is enabled for clients created after driver construction unless the pool was
24
- * configured with `pipeline: false`.
25
- */
11
+ /** PostgreSQL over node-pg, with optional patched lazy row decoding. */
26
12
  var PostgresDriver = class {
27
13
  pool;
14
+ #databaseBinaryParsers;
28
15
  #idAssigner;
29
16
  #preloadPlugin;
30
- #onQuery;
17
+ onQuery;
31
18
  lazyRows;
32
- /** Defined only when `lazyRows` is enabled; its presence is the capability signal the EM checks. */
19
+ /** Its presence is the lazy-read capability signal checked by EntityManager. */
33
20
  executeFindRowData;
34
- #databaseBinaryParsers = void 0;
35
21
  constructor(pool, opts) {
36
22
  this.pool = pool;
37
- pool.options.pipeline ??= true;
38
- this.#idAssigner = opts?.idAssigner ?? new SequenceIdAssigner(async (sql) => {
39
- this.#onQuery?.(sql);
40
- return (await pool.query(sql)).rows;
41
- });
23
+ this.onQuery = opts?.onQuery;
42
24
  this.#preloadPlugin = opts?.preloadPlugin;
43
- this.#onQuery = opts?.onQuery;
44
- this.lazyRows = (opts?.lazyRows ?? false) && ensureLazyDataRows();
25
+ this.#idAssigner = opts?.idAssigner ?? new SequenceIdAssigner(async (sql) => (await this.query(void 0, sql, [])).rows);
26
+ this.lazyRows = !!opts?.lazyRows && ensureLazyDataRows();
27
+ this.executeFindRowData = this.lazyRows ? (em, parsed, settings) => this.findRowData(em, parsed, settings) : void 0;
28
+ pool.options.pipeline ??= true;
45
29
  if (opts?.lazyRows && !this.lazyRows) console.warn("joist-orm: lazyRows was requested, but patching pg-protocol failed; using classic rows.");
46
- this.executeFindRowData = this.lazyRows ? (em, parsed, settings) => this.#executeFindRowData(em, parsed, settings) : void 0;
47
30
  setupLatestPgTypes(getRuntimeConfig().temporal);
48
31
  }
32
+ /** Uses the transaction's socket when a transaction is active. */
33
+ query(txn, sql, bindings) {
34
+ this.onQuery?.(sql);
35
+ return (txn ?? this.pool).query(sql, bindings);
36
+ }
37
+ /** Executes an entity find with the EntityManager's default limit. */
49
38
  async executeFind(em, parsed, settings) {
50
39
  const { sql, bindings } = buildRawQuery(parsed, {
51
40
  limit: em.entityLimit,
@@ -53,7 +42,29 @@ var PostgresDriver = class {
53
42
  });
54
43
  return (await this.executeQuery(em, sql, bindings)).rows;
55
44
  }
56
- async #executeFindRowData(em, parsed, settings) {
45
+ /** Returns native command counts and rows, including null counts for DDL. */
46
+ async executeQuery(em, sql, bindings) {
47
+ const { rowCount, rows } = await this.query(em.txn, toPgParams(sql), bindings);
48
+ return {
49
+ rowCount,
50
+ rows
51
+ };
52
+ }
53
+ /** Assigns identifiers with the configured strategy before dependent writes. */
54
+ async assignNewIds(_, todos) {
55
+ await this.#idAssigner.assignNewIds(todos);
56
+ }
57
+ /** Flushes PostgreSQL operations on the active node-pg transaction. */
58
+ async flush(em, entityTodos, joinRows) {
59
+ const txn = em.txn ?? fail("Expected EntityManager.txn to be set");
60
+ await this.#idAssigner.assignNewIds(entityTodos);
61
+ await flushPostgres((sql, bindings) => this.query(txn, sql, bindings), entityTodos, joinRows);
62
+ }
63
+ get defaultPlugins() {
64
+ return { preloadPlugin: this.#preloadPlugin };
65
+ }
66
+ /** Decodes immutable pg-protocol rows, falling back only for known unsupported clients. */
67
+ async findRowData(em, parsed, settings) {
57
68
  await (this.#databaseBinaryParsers ??= registerDatabaseBinaryParsers(this.pool).catch((err) => {
58
69
  this.#databaseBinaryParsers = void 0;
59
70
  throw err;
@@ -63,9 +74,9 @@ var PostgresDriver = class {
63
74
  ...settings
64
75
  });
65
76
  const pgSql = toPgParams(sql);
66
- this.#onQuery?.(pgSql);
67
- const txnClient = em.txn;
68
- const client = txnClient ?? await this.pool.connect();
77
+ this.onQuery?.(pgSql);
78
+ const txn = em.txn;
79
+ const client = txn ?? await this.pool.connect();
69
80
  try {
70
81
  if (!isRowDataCapableClient(client)) {
71
82
  warnUnsupportedClientOnce();
@@ -73,33 +84,28 @@ var PostgresDriver = class {
73
84
  }
74
85
  return await executeRowDataQuery(client, pgSql, bindings);
75
86
  } finally {
76
- if (!txnClient) client.release();
87
+ if (!txn) client.release();
77
88
  }
78
89
  }
79
- /** Returns PostgreSQL's native command count and raw rows, including null counts for DDL. */
80
- async executeQuery(em, sql, bindings) {
81
- const pgSql = toPgParams(sql);
82
- this.#onQuery?.(pgSql);
83
- const { rowCount, rows } = await this.getMaybeInTxnClient(em).query(pgSql, bindings);
84
- return {
85
- rowCount,
86
- rows
87
- };
88
- }
90
+ /**
91
+ * Runs hooks and SQL on one checked-out native pg client.
92
+ *
93
+ * Nested calls reuse the active transaction rather than starting a second one.
94
+ */
89
95
  async transaction(em, fn) {
90
96
  if (em.txn) return fn(em.txn);
91
97
  const client = await this.pool.connect();
92
98
  let result;
93
99
  try {
94
100
  await driverBeforeBegin(em, client);
95
- this.#onQuery?.("BEGIN;");
101
+ this.onQuery?.("BEGIN;");
96
102
  await client.query("BEGIN");
97
103
  em.txn = client;
98
104
  try {
99
105
  await driverAfterBegin(em, client);
100
106
  result = await fn(client);
101
107
  await driverBeforeCommit(em, client);
102
- this.#onQuery?.("COMMIT;");
108
+ this.onQuery?.("COMMIT;");
103
109
  await client.query("COMMIT");
104
110
  } catch (e) {
105
111
  await client.query("ROLLBACK");
@@ -113,155 +119,21 @@ var PostgresDriver = class {
113
119
  }
114
120
  return result;
115
121
  }
116
- async assignNewIds(_, todos) {
117
- return this.#idAssigner.assignNewIds(todos);
118
- }
119
- async flush(em, entityTodos, joinRows) {
120
- const client = em.txn ?? fail("Expected EntityManager.txn to be set");
121
- await this.#idAssigner.assignNewIds(entityTodos);
122
- const ops = generateOps(entityTodos);
123
- const onQuery = this.#onQuery;
124
- await Promise.all([
125
- ...ops.inserts.map((op) => batchInsert(client, op, onQuery)),
126
- ...ops.updates.map((op) => batchUpdate(client, op, onQuery)),
127
- ...ops.deletes.map((op) => batchDelete(client, op, onQuery)),
128
- ...Object.entries(joinRows).flatMap(([joinTableName, todo]) => {
129
- return [m2mBatchInsert(client, joinTableName, todo, onQuery), m2mBatchDelete(client, joinTableName, todo, onQuery)];
130
- })
131
- ]);
132
- }
133
- get defaultPlugins() {
134
- return { preloadPlugin: this.#preloadPlugin };
135
- }
136
- getMaybeInTxnClient(em) {
137
- return em.txn || this.pool;
138
- }
139
122
  };
140
- async function batchInsert(client, op, onQuery) {
141
- const { tableName, columns, columnValues } = op;
142
- const [cte, bindings] = buildUnnestCte("data", columns, columnValues);
143
- const pgSql = toPgParams(cleanSql(`
144
- ${cte}
145
- INSERT INTO ${kq(tableName)} (${columns.map((c) => kq(c.columnName)).join(", ")})
146
- SELECT * FROM data
147
- `));
148
- onQuery?.(pgSql);
149
- return client.query(pgSql, bindings);
150
- }
151
- async function batchUpdate(client, op, onQuery) {
152
- const { tableName, columns, columnValues, updatedAt } = op;
153
- const [cte, bindings] = buildUnnestCte("data", columns, columnValues);
154
- const truncateToMills = !getRuntimeConfig().temporal;
155
- const maybeUpdatedAt = updatedAt && truncateToMills ? ` AND date_trunc('milliseconds', ${kqDot(tableName, updatedAt)}) = data.__original_updated_at` : updatedAt ? ` AND ${kqDot(tableName, updatedAt)} = data.__original_updated_at` : "";
156
- const sql = `
157
- ${cte}
158
- UPDATE ${kq(tableName)}
159
- SET ${columns.filter((c) => c.columnName !== "id" && c.columnName !== "__original_updated_at").map((c) => `${kq(c.columnName)} = data.${kq(c.columnName)}`).join(", ")}
160
- FROM data
161
- WHERE ${kq(tableName)}.id = data.id ${maybeUpdatedAt}
162
- RETURNING ${kq(tableName)}.id
163
- `;
164
- const pgSql = toPgParams(cleanSql(sql));
165
- onQuery?.(pgSql);
166
- const results = (await client.query(pgSql, bindings)).rows;
167
- const ids = columnValues[0];
168
- if (results.length !== ids.length) {
169
- const updated = new Set(results.map((r) => r.id));
170
- const missing = ids.filter((id) => !updated.has(id));
171
- throw new Error(`Oplock failure for ${tableName} rows ${missing.join(", ")}`);
172
- }
173
- }
174
- async function batchDelete(client, op, onQuery) {
175
- const { tableName, ids } = op;
176
- const pgSql = toPgParams(`DELETE FROM ${kq(tableName)} WHERE id = ANY(?)`);
177
- onQuery?.(pgSql);
178
- await client.query(pgSql, [ids]);
179
- }
180
- /** Creates a CTE named `tableName` that bulk-injects the `columnValues` into a SQL query. */
181
- function buildUnnestCte(tableName, columns, columnValues) {
182
- ensureRectangularArraySizes(columns, columnValues);
183
- return [`WITH ${tableName} AS (SELECT ${columns.map((c) => {
184
- if (c.dbType.endsWith("[]")) {
185
- if (c.isNullableArray) return `unnest_arrays(?::${c.dbType}[], true) as ${kq(c.columnName)}`;
186
- else return `unnest_arrays(?::${c.dbType}[]) as ${kq(c.columnName)}`;
187
- } else return `unnest(?::${c.dbType}[]) as ${kq(c.columnName)}`;
188
- }).join(", ")})`, columnValues];
189
- }
190
- async function m2mBatchInsert(client, joinTableName, todo, onQuery) {
191
- const { m2m, newRows } = todo;
192
- if (newRows.length === 0) return;
193
- const col1Values = newRows.map((row) => todo.dbValue(row, m2m.columnName));
194
- const col2Values = newRows.map((row) => todo.dbValue(row, m2m.otherColumnName));
195
- if (m2m.hasJoinTableId) {
196
- const pgSql = toPgParams(cleanSql(`
197
- WITH data AS (SELECT unnest(?::int[]) as ${kq(m2m.columnName)}, unnest(?::int[]) as ${kq(m2m.otherColumnName)})
198
- INSERT INTO ${kq(joinTableName)} (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)})
199
- SELECT * FROM data
200
- ON CONFLICT (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) DO UPDATE SET id = ${kq(joinTableName)}.id
201
- RETURNING id;
202
- `));
203
- onQuery?.(pgSql);
204
- const { rows } = await client.query(pgSql, [col1Values, col2Values]);
205
- for (let i = 0; i < rows.length; i++) {
206
- newRows[i].id = rows[i].id;
207
- newRows[i].op = JoinRowOperation.Flushed;
208
- newRows[i].persisted = true;
209
- }
210
- } else {
211
- const pgSql = toPgParams(cleanSql(`
212
- WITH data AS (SELECT unnest(?::int[]) as ${kq(m2m.columnName)}, unnest(?::int[]) as ${kq(m2m.otherColumnName)})
213
- INSERT INTO ${kq(joinTableName)} (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)})
214
- SELECT * FROM data
215
- ON CONFLICT (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) DO NOTHING;
216
- `));
217
- onQuery?.(pgSql);
218
- await client.query(pgSql, [col1Values, col2Values]);
219
- for (const row of newRows) {
220
- row.op = JoinRowOperation.Flushed;
221
- row.persisted = true;
222
- }
223
- }
224
- }
225
- async function m2mBatchDelete(client, joinTableName, todo, onQuery) {
226
- const { m2m, deletedRows } = todo;
227
- if (deletedRows.length === 0) return;
228
- const [haveIds, noIds] = partition(deletedRows, (r) => {
229
- return r.id !== void 0 && r.id !== -1;
230
- });
231
- if (haveIds.length > 0) {
232
- const pgSql = toPgParams(`DELETE FROM ${kq(joinTableName)} WHERE id = ANY(?)`);
233
- onQuery?.(pgSql);
234
- await client.query(pgSql, [haveIds.map((r) => r.id)]);
235
- }
236
- if (noIds.length > 0) {
237
- const data = noIds.filter((row) => !todo.isNew(row, m2m.columnName) && !todo.isNew(row, m2m.otherColumnName)).map((row) => [todo.dbValue(row, m2m.columnName), todo.dbValue(row, m2m.otherColumnName)]);
238
- if (data.length > 0) {
239
- const pgSql = toPgParams(`
240
- DELETE FROM ${kq(joinTableName)}
241
- WHERE (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) IN (
242
- SELECT (data->>0)::int, (data->>1)::int FROM jsonb_array_elements(?) data
243
- )`);
244
- onQuery?.(pgSql);
245
- await client.query(pgSql, [JSON.stringify(data)]);
246
- }
247
- }
248
- deletedRows.forEach((row) => {
249
- row.id = void 0;
250
- row.persisted = false;
251
- row.op = JoinRowOperation.Flushed;
252
- });
253
- }
254
123
  /**
255
124
  * Configures the `pg` driver with the best type parsers.
256
125
  *
257
126
  * In particular, pg's default `TIMESTAMPTZ` parser is very inefficient, and even just
258
- * pulling in the latest `pg-types` and installing the fixed parser makes a noticable
259
- * difference.
127
+ * pulling in the latest `pg-types` and installing the fixed parser makes a noticeable difference.
260
128
  */
261
129
  function setupLatestPgTypes(temporal) {
262
130
  if (temporal) {
263
- const noop = (s) => s;
264
- const noopArray = (s) => array.parse(s, noop);
131
+ function noop(s) {
132
+ return s;
133
+ }
134
+ function noopArray(s) {
135
+ return array.parse(s, noop);
136
+ }
265
137
  const { TIMESTAMP, TIMESTAMPTZ, DATE } = pg.types.builtins;
266
138
  pg.types.setTypeParser(DATE, noop);
267
139
  pg.types.setTypeParser(TIMESTAMP, noop);
@@ -272,16 +144,111 @@ function setupLatestPgTypes(temporal) {
272
144
  registerTemporalBinaryParsers();
273
145
  } else pg.types.setTypeParser(pg.types.builtins.TIMESTAMPTZ, getTypeParser(builtins.TIMESTAMPTZ));
274
146
  }
275
- const questionMarks = /(?<!@)\?/g;
147
+ let warnedUnsupportedClient = false;
148
+ const PgQuery = createRequire(import.meta.url)("pg/lib/query");
149
+ const BINARY_BY_DEFAULT = process.env.JOIST_LAZY_BINARY !== "0";
150
+ /** A pg Query that diverts DataRows into a {@link WireRowData} instead of a `Result`. */
151
+ var RowDataQuery = class extends PgQuery {
152
+ #wire = new WireRowData();
153
+ constructor(config, callback) {
154
+ super(config, void 0, callback);
155
+ }
156
+ /**
157
+ * The query's result rows, i.e. once our callback has fired.
158
+ *
159
+ * If a small-result materialization threshold ever seems attractive, this is where it would
160
+ * go — but see the "Small results deliberately stay lazy" note on WireRowData: lazy
161
+ * won the measured comparison at every row count for sparse access, so no threshold exists.
162
+ */
163
+ get rowData() {
164
+ return this.#wire;
165
+ }
166
+ handleRowDescription(msg) {
167
+ if (this._canceledDueToError) return;
168
+ try {
169
+ super.handleRowDescription(msg);
170
+ const types = this._result?._types;
171
+ this.#wire.setColumnDecoders(pgColumnDecoders(msg.fields, types && ((oid) => types.getTypeParser(oid, "text"))));
172
+ } catch (err) {
173
+ this._canceledDueToError = err;
174
+ }
175
+ }
176
+ handleDataRow(msg) {
177
+ if (this._canceledDueToError) return;
178
+ try {
179
+ if (msg.bytes === void 0) throw new Error("joist-orm: lazyRows is enabled, but this connection's pg-protocol emits classic DataRows (likely a duplicate pg install); fix the install or disable lazyRows.");
180
+ this.#wire.addRow(msg.bytes, msg.offset, msg.length - 4);
181
+ } catch (err) {
182
+ this._canceledDueToError = err;
183
+ }
184
+ }
185
+ };
186
+ /**
187
+ * Executes `sql` on an already-checked-out client, returning a {@link RowData} instead of
188
+ * materialized POJO rows.
189
+ *
190
+ * Uses a `pg` Query subclass that records each DataRow's raw payload bytes into the result
191
+ * (via the lazy DataRow message from `patchPgProtocol`) and never materializes per-cell
192
+ * strings or per-row objects. If the client's connection turns out to use an unpatched
193
+ * pg-protocol copy (i.e. the app's pool was built from a different `pg` install than the one
194
+ * joist-orm patched), the query fails with a descriptive error — a misconfiguration any CI
195
+ * build/smoketest will surface immediately, so we fail loudly rather than silently degrade.
196
+ * The rows already streamed are discarded; the connection itself stays usable.
197
+ *
198
+ * By default the query requests binary result format via the extended protocol.
199
+ * Pass `binary: false` for classic text-format results, or set `JOIST_LAZY_BINARY=0`
200
+ * for A/B benchmarking or as an escape hatch.
201
+ */
202
+ function executeRowDataQuery(client, sql, bindings, opts) {
203
+ const binary = opts?.binary ?? BINARY_BY_DEFAULT;
204
+ return new Promise((resolve, reject) => {
205
+ const query = new RowDataQuery(binary ? {
206
+ text: sql,
207
+ values: bindings,
208
+ binary: true,
209
+ queryMode: "extended"
210
+ } : {
211
+ text: sql,
212
+ values: bindings
213
+ }, (err) => {
214
+ if (err) reject(err);
215
+ else resolve(query.rowData);
216
+ });
217
+ client.query(query);
218
+ });
219
+ }
220
+ /** Returns whether `client` supports the lazy row-data query path, before submitting anything. */
221
+ function isRowDataCapableClient(client) {
222
+ return typeof client === "object" && client !== null && typeof client.query === "function" && client.connection !== void 0 && client.native === void 0;
223
+ }
276
224
  /**
277
- * Converts our knex-style `?` placeholders to pg-native `$1, $2, ...` numbered parameters.
225
+ * Resolves each column's decoder from the query's RowDescription.
278
226
  *
279
- * We skipping postgres operators like `@?`. */
280
- function toPgParams(sql) {
281
- let i = 0;
282
- return sql.replace(questionMarks, () => `$${++i}`);
227
+ * Binary-format fields decode through Joist's own binary registry only (see
228
+ * `setBinaryTypeParser`) — `pg.types`/`TypeOverrides` are never consulted, and a column whose
229
+ * oid has no registered binary parser fails the query here, before any rows arrive, rather
230
+ * than guessing at a lossy decoding. Text-format fields (the `binary: false` escape hatch)
231
+ * decode by utf8-slicing the cell into the active text parser, resolved via `getTypeParser`
232
+ * (i.e. the pool/client `TypeOverrides` chain) or the global registry.
233
+ */
234
+ function pgColumnDecoders(fields, getTypeParser) {
235
+ return fields.map((field) => {
236
+ const { name, dataTypeID, format } = field;
237
+ let decode;
238
+ if (format === "binary") {
239
+ decode = getBinaryTypeParser(dataTypeID);
240
+ if (decode === void 0) throw new Error(`joist-orm: no binary type parser registered for oid ${dataTypeID} (column "${name}"); register one with setBinaryTypeParser (i.e. binaryTextParser for text-like types)`);
241
+ } else decode = textCellDecoder(getTypeParser?.(dataTypeID) ?? pg.types.getTypeParser(dataTypeID, "text"));
242
+ return {
243
+ name,
244
+ decode
245
+ };
246
+ });
247
+ }
248
+ /** Builds a text-format cell decoder: utf8-slice the cell bytes into the active text parser. */
249
+ function textCellDecoder(parse) {
250
+ return (chunk, start, length) => parse(chunk.toString("utf8", start, start + length));
283
251
  }
284
- let warnedUnsupportedClient = false;
285
252
  /** Warns once when lazyRows degrades to classic rows for an unsupported client, i.e. pg-native. */
286
253
  function warnUnsupportedClientOnce() {
287
254
  if (warnedUnsupportedClient) return;
@@ -289,6 +256,6 @@ function warnUnsupportedClientOnce() {
289
256
  console.warn("joist-orm: lazyRows is enabled, but this client does not support it; using classic rows.");
290
257
  }
291
258
  //#endregion
292
- export { PostgresDriver, setupLatestPgTypes };
259
+ export { PostgresDriver, executeRowDataQuery, pgColumnDecoders, setupLatestPgTypes };
293
260
 
294
261
  //# sourceMappingURL=PostgresDriver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PostgresDriver.js","names":["#idAssigner","#preloadPlugin","#onQuery","#executeFindRowData","#databaseBinaryParsers"],"sources":["../../src/drivers/PostgresDriver.ts"],"sourcesContent":["import {\n type DeleteOp,\n type Driver,\n type DriverQueryResult,\n type EntityManager,\n type IdAssigner,\n type InsertOp,\n JoinRowOperation,\n type JoinRowTodo,\n type OpColumn,\n type ParsedFindQuery,\n PojoRowData,\n type PreloadPlugin,\n type RowData,\n type RuntimeConfig,\n SequenceIdAssigner,\n type Todo,\n type UpdateOp,\n buildRawQuery,\n cleanSql,\n driverAfterBegin,\n driverAfterCommit,\n driverBeforeBegin,\n driverBeforeCommit,\n ensureRectangularArraySizes,\n fail,\n generateOps,\n getRuntimeConfig,\n kq,\n kqDot,\n partition,\n} from \"joist-core\";\nimport pg from \"pg\";\nimport { builtins, getTypeParser } from \"pg-types\";\nimport array from \"postgres-array\";\n\nimport { registerDatabaseBinaryParsers, registerTemporalBinaryParsers } from \"./binaryParsers.ts\";\nimport { ensureLazyDataRows } from \"./patchPgProtocol.ts\";\nimport { executeRowDataQuery, isRowDataCapableClient } from \"./WireRowData.ts\";\n\nexport interface PostgresDriverOpts {\n idAssigner?: IdAssigner;\n /** Sets a default `PreloadPlugin` for any `EntityManager` that uses this driver. */\n preloadPlugin?: PreloadPlugin;\n /** Called after each query is executed, useful for testing/debugging. */\n onQuery?: (sql: string) => void;\n /**\n * Experimental: keeps entity find results as raw wire bytes and decodes each row/column cell\n * lazily on field access, instead of eagerly materializing POJO rows.\n *\n * Applies to unpaginated `em.find`, `em.load`, and o2m/o2o/recursive relation loads against\n * the pure-JS pg client. Other loaders deliberately stay classic: paginated finds (small\n * pages, measured neutral), m2m join-table rows (narrow + fully read, where materialized rows\n * measured faster, and `JoinRows` owns/mutates them), lazy columns, and id/count loaders.\n *\n * Lazy queries also request *binary* result format (prototype), decoding int/bool/float/text\n * cells — and, via the fast paths `setupLatestPgTypes` registers, date/timestamptz cells —\n * wire-bytes -> value with no intermediate strings; numeric/exotic cells render to pg's\n * canonical text and reuse the active text parsers for parity. `JOIST_LAZY_BINARY=0`\n * reverts lazy queries to text-format results. It\n * uses classic rows when the choice is knowable up-front (patching pg-protocol failed, or the\n * client is unsupported, i.e. pg-native — both warn once). If a connection turns out\n * mid-query to use an unpatched pg-protocol copy (a duplicate `pg` install), the query fails\n * with a descriptive error — a misconfiguration CI builds/smoketests will catch immediately.\n * Note deferred decoding also defers custom-parser errors from `await em.find` to first field\n * access. See JS-ROW-STORE-DESIGN.md.\n */\n lazyRows?: boolean;\n}\n\n/**\n * Provides a callback for tests/debugging.\n *\n * We used to get this for-free from knex, but node-pg does not have a `query` event.\n */\ntype OnQuery = ((sql: string) => void) | undefined;\n\n/**\n * Implements the `Driver` interface for Postgres.\n *\n * This is the canonical driver implementation and leverages several aspects of\n * Postgres for the best performance, i.e.:\n *\n * - Deferred foreign key constraints are used to allow bulk inserting/updating\n * all entities without any topographic sorting/ordering issues.\n *\n * - Sequences are used to bulk-assign + then bulk-insert all entities, to again\n * avoid issues with ordering issues (cannot bulk insert A w/o knowing the id of B).\n *\n * - We use a pg-specific bulk update syntax.\n *\n * Query pipelining is enabled for clients created after driver construction unless the pool was\n * configured with `pipeline: false`.\n */\nexport class PostgresDriver implements Driver<pg.PoolClient> {\n readonly #idAssigner: IdAssigner;\n readonly #preloadPlugin: PreloadPlugin | undefined;\n readonly #onQuery: OnQuery;\n readonly lazyRows: boolean;\n /** Defined only when `lazyRows` is enabled; its presence is the capability signal the EM checks. */\n readonly executeFindRowData: Driver[\"executeFindRowData\"];\n #databaseBinaryParsers: Promise<void> | undefined = undefined;\n\n constructor(\n readonly pool: pg.Pool,\n opts?: PostgresDriverOpts,\n ) {\n // Set the option before pg creates clients, but preserve an explicit consumer opt-out.\n pool.options.pipeline ??= true;\n this.#idAssigner =\n opts?.idAssigner ??\n new SequenceIdAssigner(async (sql: string) => {\n this.#onQuery?.(sql);\n return (await pool.query(sql)).rows;\n });\n this.#preloadPlugin = opts?.preloadPlugin;\n this.#onQuery = opts?.onQuery;\n // Lazy rows require pg-protocol to emit lazy DataRows, which we patch in at runtime; if the\n // patch cannot be applied/verified (i.e. future pg-protocol internals changed), stay classic\n this.lazyRows = (opts?.lazyRows ?? false) && ensureLazyDataRows();\n if (opts?.lazyRows && !this.lazyRows) {\n console.warn(\"joist-orm: lazyRows was requested, but patching pg-protocol failed; using classic rows.\");\n }\n this.executeFindRowData = this.lazyRows\n ? (em, parsed, settings) => this.#executeFindRowData(em, parsed, settings)\n : undefined;\n setupLatestPgTypes(getRuntimeConfig().temporal);\n }\n\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 async #executeFindRowData(\n em: EntityManager,\n parsed: ParsedFindQuery,\n settings: { limit?: number; offset?: number },\n ): Promise<RowData> {\n // Auto-register binary parsers for the db's dynamic-oid text-likes (native enums, citext)\n // once, before our first lazy query; on failure, reset so the next query retries\n await (this.#databaseBinaryParsers ??= registerDatabaseBinaryParsers(this.pool).catch((err) => {\n this.#databaseBinaryParsers = undefined;\n throw err;\n }));\n const { sql, bindings } = buildRawQuery(parsed, { limit: em.entityLimit, ...settings });\n const pgSql = toPgParams(sql);\n this.#onQuery?.(pgSql);\n // Centralize client checkout here (pg-pool rejects Submittables in pool.query), and decide\n // classic-vs-lazy *before* submitting anything, i.e. unsupported clients like pg-native fall\n // back to classic rows rather than failing mid-query\n const txnClient = em.txn as pg.PoolClient | undefined;\n const client = txnClient ?? (await this.pool.connect());\n try {\n if (!isRowDataCapableClient(client)) {\n warnUnsupportedClientOnce();\n return new PojoRowData((await (client as pg.PoolClient).query(pgSql, bindings as any[])).rows);\n }\n return await executeRowDataQuery(client, pgSql, bindings);\n } finally {\n if (!txnClient) client.release();\n }\n }\n\n /** Returns PostgreSQL's native command count and raw rows, including null counts for DDL. */\n async executeQuery(em: EntityManager, sql: string, bindings: readonly any[]): Promise<DriverQueryResult> {\n const pgSql = toPgParams(sql);\n this.#onQuery?.(pgSql);\n const client = this.getMaybeInTxnClient(em);\n const { rowCount, rows } = await client.query(pgSql, bindings as any[]);\n return { rowCount, rows };\n }\n\n async transaction<T>(em: EntityManager, fn: (txn: pg.PoolClient) => Promise<T>): Promise<T> {\n if (em.txn) {\n return fn(em.txn as pg.PoolClient);\n }\n const client = await this.pool.connect();\n let result: T;\n try {\n await driverBeforeBegin(em, client);\n this.#onQuery?.(\"BEGIN;\");\n await client.query(\"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 client.query(\"COMMIT\");\n } catch (e) {\n await client.query(\"ROLLBACK\");\n throw e;\n } finally {\n em.txn = undefined;\n }\n await driverAfterCommit(em, client);\n } finally {\n client.release();\n }\n return result;\n }\n\n async assignNewIds(_: EntityManager, todos: Record<string, Todo>): Promise<void> {\n return this.#idAssigner.assignNewIds(todos);\n }\n\n async flush(\n em: EntityManager,\n entityTodos: Record<string, Todo>,\n joinRows: Record<string, JoinRowTodo>,\n ): Promise<void> {\n const client = (em.txn ?? fail(\"Expected EntityManager.txn to be set\")) as pg.PoolClient;\n await this.#idAssigner.assignNewIds(entityTodos);\n const ops = generateOps(entityTodos);\n const onQuery = this.#onQuery;\n // Do INSERTs+UPDATEs first so that we avoid DELETE cascades invalidating oplocks\n // See https://github.com/joist-orm/joist-orm/issues/591\n await Promise.all([\n ...ops.inserts.map((op) => batchInsert(client, op, onQuery)),\n ...ops.updates.map((op) => batchUpdate(client, op, onQuery)),\n ...ops.deletes.map((op) => batchDelete(client, op, onQuery)),\n ...Object.entries(joinRows).flatMap(([joinTableName, todo]) => {\n return [\n m2mBatchInsert(client, joinTableName, todo, onQuery),\n m2mBatchDelete(client, joinTableName, todo, onQuery),\n ];\n }),\n ]);\n }\n\n get defaultPlugins() {\n return { preloadPlugin: this.#preloadPlugin };\n }\n\n private getMaybeInTxnClient(em: EntityManager): pg.PoolClient | pg.Pool {\n return (em.txn as pg.PoolClient) || this.pool;\n }\n}\n\nasync function batchInsert(client: pg.PoolClient, op: InsertOp, onQuery: OnQuery): Promise<unknown> {\n const { tableName, columns, columnValues } = op;\n const [cte, bindings] = buildUnnestCte(\"data\", columns, columnValues);\n const sql = cleanSql(`\n ${cte}\n INSERT INTO ${kq(tableName)} (${columns.map((c) => kq(c.columnName)).join(\", \")})\n SELECT * FROM data\n `);\n const pgSql = toPgParams(sql);\n onQuery?.(pgSql);\n return client.query(pgSql, bindings);\n}\n\nasync function batchUpdate(client: pg.PoolClient, op: UpdateOp, onQuery: OnQuery): Promise<void> {\n const { tableName, columns, columnValues, updatedAt } = op;\n\n const [cte, bindings] = buildUnnestCte(\"data\", columns, columnValues);\n\n // JS Dates only have millisecond-level precision, so we may have dropped/lost accuracy when\n // reading Postgres's microsecond-level `timestamptz` values; using `date_trunc` \"downgrades\"\n // the pg data to match what we have in the JS Date.\n //\n // ...but Temporal's types don't have this flaw.\n const truncateToMills = !getRuntimeConfig().temporal;\n const maybeUpdatedAt =\n updatedAt && truncateToMills\n ? ` AND date_trunc('milliseconds', ${kqDot(tableName, updatedAt)}) = data.__original_updated_at`\n : updatedAt\n ? ` AND ${kqDot(tableName, updatedAt)} = data.__original_updated_at`\n : \"\";\n\n const sql = `\n ${cte}\n UPDATE ${kq(tableName)}\n SET ${columns\n .filter((c) => c.columnName !== \"id\" && c.columnName !== \"__original_updated_at\")\n .map((c) => `${kq(c.columnName)} = data.${kq(c.columnName)}`)\n .join(\", \")}\n FROM data\n WHERE ${kq(tableName)}.id = data.id ${maybeUpdatedAt}\n RETURNING ${kq(tableName)}.id\n `;\n\n const pgSql = toPgParams(cleanSql(sql));\n onQuery?.(pgSql);\n const result = await client.query(pgSql, bindings);\n const results = result.rows;\n\n const ids = columnValues[0]; // assume id is the 1st column\n if (results.length !== ids.length) {\n const updated = new Set(results.map((r: any) => r.id));\n const missing = ids.filter((id) => !updated.has(id));\n throw new Error(`Oplock failure for ${tableName} rows ${missing.join(\", \")}`);\n }\n}\n\nasync function batchDelete(client: pg.PoolClient, op: DeleteOp, onQuery: OnQuery): Promise<void> {\n const { tableName, ids } = op;\n const pgSql = toPgParams(`DELETE FROM ${kq(tableName)} WHERE id = ANY(?)`);\n onQuery?.(pgSql);\n await client.query(pgSql, [ids]);\n}\n\n/** Creates a CTE named `tableName` that bulk-injects the `columnValues` into a SQL query. */\nfunction buildUnnestCte(tableName: string, columns: OpColumn[], columnValues: any[][]): [string, any[][]] {\n ensureRectangularArraySizes(columns, columnValues);\n const selects = columns.map((c) => {\n if (c.dbType.endsWith(\"[]\")) {\n if (c.isNullableArray) {\n return `unnest_arrays(?::${c.dbType}[], true) as ${kq(c.columnName)}`;\n } else {\n return `unnest_arrays(?::${c.dbType}[]) as ${kq(c.columnName)}`;\n }\n } else {\n return `unnest(?::${c.dbType}[]) as ${kq(c.columnName)}`;\n }\n });\n const sql = `WITH ${tableName} AS (SELECT ${selects.join(\", \")})`;\n return [sql, columnValues];\n}\n\nasync function m2mBatchInsert(client: pg.PoolClient, joinTableName: string, todo: JoinRowTodo, onQuery: OnQuery) {\n const { m2m, newRows } = todo;\n if (newRows.length === 0) return;\n const col1Values = newRows.map((row) => todo.dbValue(row, m2m.columnName));\n const col2Values = newRows.map((row) => todo.dbValue(row, m2m.otherColumnName));\n if (m2m.hasJoinTableId) {\n const sql = cleanSql(`\n WITH data AS (SELECT unnest(?::int[]) as ${kq(m2m.columnName)}, unnest(?::int[]) as ${kq(m2m.otherColumnName)})\n INSERT INTO ${kq(joinTableName)} (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)})\n SELECT * FROM data\n ON CONFLICT (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) DO UPDATE SET id = ${kq(joinTableName)}.id\n RETURNING id;\n `);\n const pgSql = toPgParams(sql);\n onQuery?.(pgSql);\n const { rows } = await client.query(pgSql, [col1Values, col2Values]);\n for (let i = 0; i < rows.length; i++) {\n newRows[i].id = rows[i].id;\n newRows[i].op = JoinRowOperation.Flushed;\n newRows[i].persisted = true;\n }\n } else {\n // Id-less join tables have no surrogate id to return; the FK pair is the PK, so just\n // insert and let any duplicate be a no-op.\n const sql = cleanSql(`\n WITH data AS (SELECT unnest(?::int[]) as ${kq(m2m.columnName)}, unnest(?::int[]) as ${kq(m2m.otherColumnName)})\n INSERT INTO ${kq(joinTableName)} (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)})\n SELECT * FROM data\n ON CONFLICT (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) DO NOTHING;\n `);\n const pgSql = toPgParams(sql);\n onQuery?.(pgSql);\n await client.query(pgSql, [col1Values, col2Values]);\n for (const row of newRows) {\n row.op = JoinRowOperation.Flushed;\n row.persisted = true;\n }\n }\n}\n\nasync function m2mBatchDelete(client: pg.PoolClient, joinTableName: string, todo: JoinRowTodo, onQuery: OnQuery) {\n const { m2m, deletedRows } = todo;\n if (deletedRows.length === 0) return;\n // Rows with a surrogate id are deleted by id; rows without one — id-less tables, or `remove`s\n // done against an unloaded ManyToManyCollection — are deleted by their (col1, col2) composite.\n const [haveIds, noIds] = partition(deletedRows, (r) => {\n // We used to use `id !== -1` as a marker for \"row is/is-not persisted in the db\" -- but when adding support\n // for id-column-less m2m tables, we couldn't use `id === -1` as this marker anymore, so now rely on a dedicated\n // `persisted` key instead.\n //\n // So, ideally, this `id !== -1` could go away _except_ that our internal verisoning plugin leverages this \"m2m rows\n // with an id=-1 delete by their FK values\" to handle our versioned m2m tables. And for now it's easier to\n // keep/restore this `id !== -1` than refactor that.\n return r.id !== undefined && r.id !== -1;\n });\n if (haveIds.length > 0) {\n const pgSql = toPgParams(`DELETE FROM ${kq(joinTableName)} WHERE id = ANY(?)`);\n onQuery?.(pgSql);\n await client.query(pgSql, [haveIds.map((r) => r.id!)]);\n }\n if (noIds.length > 0) {\n const data = noIds\n // Watch for m2m rows that got added-then-removed to entities that were themselves added-then-removed,\n // as the deTagId will be undefined for those, as we're skipping adding them to the database.\n .filter((row) => !todo.isNew(row, m2m.columnName) && !todo.isNew(row, m2m.otherColumnName))\n .map((row) => [todo.dbValue(row, m2m.columnName), todo.dbValue(row, m2m.otherColumnName)] as any);\n if (data.length > 0) {\n const pgSql = toPgParams(`\n DELETE FROM ${kq(joinTableName)}\n WHERE (${kq(m2m.columnName)}, ${kq(m2m.otherColumnName)}) IN (\n SELECT (data->>0)::int, (data->>1)::int FROM jsonb_array_elements(?) data\n )`);\n onQuery?.(pgSql);\n await client.query(pgSql, [JSON.stringify(data)]);\n }\n }\n deletedRows.forEach((row) => {\n row.id = undefined;\n row.persisted = false;\n row.op = JoinRowOperation.Flushed;\n });\n}\n\n/**\n * Configures the `pg` driver with the best type parsers.\n *\n * In particular, pg's default `TIMESTAMPTZ` parser is very inefficient, and even just\n * pulling in the latest `pg-types` and installing the fixed parser makes a noticable\n * difference.\n */\nexport function setupLatestPgTypes(temporal: RuntimeConfig[\"temporal\"]): void {\n if (temporal) {\n // Don't eagerly parse the strings, instead defer to the serde logic. This only governs\n // classic *text* results (knex, pool.query, non-lazy drivers); binary lazy cells construct\n // Temporal values directly, with no strings involved (see registerTemporalBinaryParsers).\n const noop = (s: string) => s;\n const noopArray = (s: string) => array.parse(s, noop);\n\n const { TIMESTAMP, TIMESTAMPTZ, DATE } = pg.types.builtins;\n pg.types.setTypeParser(DATE, noop);\n pg.types.setTypeParser(TIMESTAMP, noop);\n pg.types.setTypeParser(TIMESTAMPTZ, noop);\n\n // Use `as number` b/c the typings of shadowed pg-types from `pg` and `pg-types` top-level don't line up\n pg.types.setTypeParser(1182 as number, noopArray); // date[]\n pg.types.setTypeParser(1115 as number, noopArray); // timestamp[]\n pg.types.setTypeParser(1185 as number, noopArray); // timestamptz[]\n\n registerTemporalBinaryParsers();\n } else {\n pg.types.setTypeParser(pg.types.builtins.TIMESTAMPTZ, getTypeParser(builtins.TIMESTAMPTZ));\n // The binary registry's date/timestamp/timestamptz builtins already decode to Dates\n }\n}\n\nconst questionMarks = /(?<!@)\\?/g;\n\n/**\n * Converts our knex-style `?` placeholders to pg-native `$1, $2, ...` numbered parameters.\n *\n * We skipping postgres operators like `@?`. */\nfunction toPgParams(sql: string): string {\n let i = 0;\n return sql.replace(questionMarks, () => `$${++i}`);\n}\n\nlet warnedUnsupportedClient = false;\n\n/** Warns once when lazyRows degrades to classic rows for an unsupported client, i.e. pg-native. */\nfunction warnUnsupportedClientOnce(): void {\n if (warnedUnsupportedClient) return;\n warnedUnsupportedClient = true;\n console.warn(\"joist-orm: lazyRows is enabled, but this client does not support it; using classic rows.\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,IAAa,iBAAb,MAA6D;CAUhD;CATX;CACA;CACA;CACA;;CAEA;CACA,yBAAoD,KAAA;CAEpD,YACE,MACA,MACA;EAFS,KAAA,OAAA;EAIT,KAAK,QAAQ,aAAa;EAC1B,KAAKA,cACH,MAAM,cACN,IAAI,mBAAmB,OAAO,QAAgB;GAC5C,KAAKE,WAAW,GAAG;GACnB,QAAQ,MAAM,KAAK,MAAM,GAAG,EAAA,CAAG;EACjC,CAAC;EACH,KAAKD,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AAgB,SAAS;EAChD,GAAG,MAAM,cAAc,MAAgB,SAAS;EAEhD,8BAA8B;CAChC,OACE,GAAG,MAAM,cAAc,GAAG,MAAM,SAAS,aAAa,cAAc,SAAS,WAAW,CAAC;AAG7F;AAEA,MAAM,gBAAgB;;;;;AAMtB,SAAS,WAAW,KAAqB;CACvC,IAAI,IAAI;CACR,OAAO,IAAI,QAAQ,qBAAqB,IAAI,EAAE,GAAG;AACnD;AAEA,IAAI,0BAA0B;;AAG9B,SAAS,4BAAkC;CACzC,IAAI,yBAAyB;CAC7B,0BAA0B;CAC1B,QAAQ,KAAK,0FAA0F;AACzG"}
1
+ {"version":3,"file":"PostgresDriver.js","names":[],"sources":["../../src/drivers/PostgresDriver.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\nimport {\n type Driver,\n type DriverQueryResult,\n type EntityManager,\n type IdAssigner,\n type JoinRowTodo,\n type ParsedFindQuery,\n PojoRowData,\n type PreloadPlugin,\n type RowData,\n type RuntimeConfig,\n SequenceIdAssigner,\n type Todo,\n buildRawQuery,\n driverAfterBegin,\n driverAfterCommit,\n driverBeforeBegin,\n driverBeforeCommit,\n fail,\n getRuntimeConfig,\n} from \"joist-core\";\nimport pg from \"pg\";\nimport { builtins, getTypeParser } from \"pg-types\";\nimport array from \"postgres-array\";\n\nimport { getBinaryTypeParser, registerDatabaseBinaryParsers, registerTemporalBinaryParsers } from \"./binaryParsers.ts\";\nimport { ensureLazyDataRows } from \"./patchPgProtocol.ts\";\nimport { flushPostgres, toPgParams } from \"./postgresSql.ts\";\nimport { WireRowData } from \"./WireRowData.ts\";\n\nexport interface PostgresDriverOpts {\n idAssigner?: IdAssigner;\n /** Sets a default `PreloadPlugin` for any `EntityManager` that uses this driver. */\n preloadPlugin?: PreloadPlugin;\n /** Observes SQL before submission; node-pg does not expose a query event. */\n onQuery?: (sql: string) => void;\n /**\n * Keeps entity find results as raw wire bytes and decodes cells on field access. Defaults to false.\n *\n * Applies to em.find, em.load and o2m/o2o/recursive relation loads.\n * Other loaders deliberately stay classic: m2m join-table\n * rows (narrow, fully read and mutated by JoinRows), lazy columns, and id/count loaders.\n *\n * Binary cells use Joist's parser registry; JOIST_LAZY_BINARY=0 requests text results instead.\n * If patching pg-protocol fails or the client is unsupported (i.e. pg-native), we warn and\n * use classic rows. An unpatched duplicate pg-protocol discovered mid-query fails loudly\n * rather than silently degrading. Deferred parsing also defers custom-parser errors from\n * await em.find to field access. See JS-ROW-STORE-DESIGN.md.\n */\n lazyRows?: boolean;\n}\n\n/** PostgreSQL over node-pg, with optional patched lazy row decoding. */\nexport class PostgresDriver implements Driver<pg.PoolClient> {\n #databaseBinaryParsers: Promise<void> | undefined;\n readonly #idAssigner: IdAssigner;\n readonly #preloadPlugin: PreloadPlugin | undefined;\n private readonly onQuery: PostgresDriverOpts[\"onQuery\"];\n readonly lazyRows: boolean;\n /** Its presence is the lazy-read capability signal checked by EntityManager. */\n readonly executeFindRowData: Driver[\"executeFindRowData\"];\n\n constructor(\n readonly pool: pg.Pool,\n opts?: PostgresDriverOpts,\n ) {\n this.onQuery = opts?.onQuery;\n this.#preloadPlugin = opts?.preloadPlugin;\n\n // Sequences assign IDs before bulk insertion, including mutually dependent new entities.\n this.#idAssigner =\n opts?.idAssigner ?? new SequenceIdAssigner(async (sql) => (await this.query(undefined, sql, [])).rows);\n\n this.lazyRows = !!opts?.lazyRows && ensureLazyDataRows();\n this.executeFindRowData = this.lazyRows\n ? (em, parsed, settings) => this.findRowData(em, parsed, settings)\n : undefined;\n\n // Set the option before pg creates clients, but preserve an explicit consumer opt-out.\n pool.options.pipeline ??= true;\n if (opts?.lazyRows && !this.lazyRows) {\n console.warn(\"joist-orm: lazyRows was requested, but patching pg-protocol failed; using classic rows.\");\n }\n setupLatestPgTypes(getRuntimeConfig().temporal);\n }\n\n /** Uses the transaction's socket when a transaction is active. */\n private query(txn: pg.PoolClient | undefined, sql: string, bindings: readonly unknown[]) {\n this.onQuery?.(sql);\n return (txn ?? this.pool).query(sql, bindings as unknown[]);\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 native command counts and rows, including null counts for DDL. */\n async executeQuery(em: EntityManager, sql: string, bindings: readonly unknown[]): Promise<DriverQueryResult> {\n const { rowCount, rows } = await this.query(em.txn as pg.PoolClient | undefined, toPgParams(sql), bindings);\n return { rowCount, rows };\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 node-pg 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 pg.PoolClient;\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 /** Decodes immutable pg-protocol rows, falling back only for known unsupported clients. */\n private async findRowData(\n em: EntityManager,\n parsed: ParsedFindQuery,\n settings: { limit?: number; offset?: number },\n ): Promise<RowData> {\n // Auto-register binary parsers for the db's dynamic-oid text-likes (native enums, citext)\n // once, before our first lazy query; on failure, reset so the next query retries.\n await (this.#databaseBinaryParsers ??= registerDatabaseBinaryParsers(this.pool).catch((err) => {\n this.#databaseBinaryParsers = undefined;\n throw err;\n }));\n const { sql, bindings } = buildRawQuery(parsed, { limit: em.entityLimit, ...settings });\n const pgSql = toPgParams(sql);\n this.onQuery?.(pgSql);\n // pg-pool rejects Submittables in pool.query; choose classic-vs-lazy before submitting.\n const txn = em.txn as pg.PoolClient | undefined;\n const client = txn ?? (await this.pool.connect());\n try {\n if (!isRowDataCapableClient(client)) {\n warnUnsupportedClientOnce();\n return new PojoRowData((await (client as pg.PoolClient).query(pgSql, bindings as unknown[])).rows);\n }\n return await executeRowDataQuery(client, pgSql, bindings);\n } finally {\n if (!txn) client.release();\n }\n }\n\n /**\n * Runs hooks and SQL on one checked-out native pg client.\n *\n * Nested calls reuse the active transaction rather than starting a second one.\n */\n async transaction<T>(em: EntityManager, fn: (txn: pg.PoolClient) => Promise<T>): Promise<T> {\n if (em.txn) return fn(em.txn as pg.PoolClient);\n const client = await this.pool.connect();\n let result: T;\n try {\n await driverBeforeBegin(em, client);\n this.onQuery?.(\"BEGIN;\");\n await client.query(\"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 client.query(\"COMMIT\");\n } catch (e) {\n await client.query(\"ROLLBACK\");\n throw e;\n } finally {\n em.txn = undefined;\n }\n await driverAfterCommit(em, client);\n } finally {\n client.release();\n }\n return result;\n }\n}\n\n/**\n * Configures the `pg` driver with the best type parsers.\n *\n * In particular, pg's default `TIMESTAMPTZ` parser is very inefficient, and even just\n * pulling in the latest `pg-types` and installing the fixed parser makes a noticeable difference.\n */\nexport function setupLatestPgTypes(temporal: RuntimeConfig[\"temporal\"]): void {\n if (temporal) {\n // Don't eagerly parse the strings, instead defer to the serde logic. This only governs\n // classic *text* results (knex, pool.query, non-lazy drivers); binary lazy cells construct\n // Temporal values directly, with no strings involved (see registerTemporalBinaryParsers).\n function noop(s: string) {\n return s;\n }\n function noopArray(s: string) {\n return array.parse(s, noop);\n }\n const { TIMESTAMP, TIMESTAMPTZ, DATE } = pg.types.builtins;\n pg.types.setTypeParser(DATE, noop);\n pg.types.setTypeParser(TIMESTAMP, noop);\n pg.types.setTypeParser(TIMESTAMPTZ, noop);\n // Use `as number` b/c the typings of shadowed pg-types from `pg` and `pg-types` top-level don't line up.\n pg.types.setTypeParser(1182 as number, noopArray); // date[]\n pg.types.setTypeParser(1115 as number, noopArray); // timestamp[]\n pg.types.setTypeParser(1185 as number, noopArray); // timestamptz[]\n registerTemporalBinaryParsers();\n } else {\n pg.types.setTypeParser(pg.types.builtins.TIMESTAMPTZ, getTypeParser(builtins.TIMESTAMPTZ));\n // The binary registry's date/timestamp/timestamptz builtins already decode to Dates.\n }\n}\n\nlet warnedUnsupportedClient = false;\n\nconst runtimeRequire = createRequire(import.meta.url);\n\n// pg's internal-but-exported Query class; subclassing it reuses its extended-protocol\n// submit/bind logic while letting us intercept row handling (the same seam pg-cursor uses).\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst PgQuery: any = runtimeRequire(\"pg/lib/query\");\n\n// The prototype escape hatch for binary results, i.e. for A/B benchmarking; read once at load.\nconst BINARY_BY_DEFAULT = process.env.JOIST_LAZY_BINARY !== \"0\";\n\n/** A pg Query that diverts DataRows into a {@link WireRowData} instead of a `Result`. */\nclass RowDataQuery extends PgQuery {\n #wire = new WireRowData();\n\n constructor(\n config: { text: string; values: any[]; binary?: boolean; queryMode?: string },\n callback: (err: unknown) => void,\n ) {\n super(config, undefined, callback);\n }\n\n /**\n * The query's result rows, i.e. once our callback has fired.\n *\n * If a small-result materialization threshold ever seems attractive, this is where it would\n * go — but see the \"Small results deliberately stay lazy\" note on WireRowData: lazy\n * won the measured comparison at every row count for sparse access, so no threshold exists.\n */\n get rowData(): RowData {\n return this.#wire;\n }\n\n handleRowDescription(msg: any): void {\n if (this._canceledDueToError) return;\n try {\n super.handleRowDescription(msg);\n // Resolve active text parsers through the client's TypeOverrides chain (client.js\n // injects `_types` at submit time). Binary fields use Joist's binary registry instead\n // of pg's broken binary parsing of UTF-8 strings.\n const types = this._result?._types;\n this.#wire.setColumnDecoders(\n pgColumnDecoders(msg.fields, types && ((oid: number) => types.getTypeParser(oid, \"text\"))),\n );\n } catch (err) {\n // Mirror pg's Query error containment: record + reject at ReadyForQuery, keeping the\n // connection's protocol state intact.\n this._canceledDueToError = err;\n }\n }\n\n handleDataRow(msg: any): void {\n if (this._canceledDueToError) return;\n try {\n if (msg.bytes === undefined) {\n // This connection's pg-protocol copy is unpatched (i.e. the pool came from a different\n // `pg` install than the one joist-orm patched), so lazyRows cannot work — fail loudly\n // rather than silently degrade; any CI build/smoketest will surface this immediately.\n throw new Error(\n \"joist-orm: lazyRows is enabled, but this connection's pg-protocol emits classic\" +\n \" DataRows (likely a duplicate pg install); fix the install or disable lazyRows.\",\n );\n }\n // `msg.length` includes the int32 length field itself, so the payload is `length - 4`;\n // our patched message carries the real length from `handlePacket`'s argument.\n this.#wire.addRow(msg.bytes, msg.offset, msg.length - 4);\n } catch (err) {\n this._canceledDueToError = err;\n }\n }\n}\n\n/**\n * Executes `sql` on an already-checked-out client, returning a {@link RowData} instead of\n * materialized POJO rows.\n *\n * Uses a `pg` Query subclass that records each DataRow's raw payload bytes into the result\n * (via the lazy DataRow message from `patchPgProtocol`) and never materializes per-cell\n * strings or per-row objects. If the client's connection turns out to use an unpatched\n * pg-protocol copy (i.e. the app's pool was built from a different `pg` install than the one\n * joist-orm patched), the query fails with a descriptive error — a misconfiguration any CI\n * build/smoketest will surface immediately, so we fail loudly rather than silently degrade.\n * The rows already streamed are discarded; the connection itself stays usable.\n *\n * By default the query requests binary result format via the extended protocol.\n * Pass `binary: false` for classic text-format results, or set `JOIST_LAZY_BINARY=0`\n * for A/B benchmarking or as an escape hatch.\n */\nexport function executeRowDataQuery(\n client: pg.PoolClient,\n sql: string,\n bindings: readonly any[],\n opts?: { binary?: boolean },\n): Promise<RowData> {\n const binary = opts?.binary ?? BINARY_BY_DEFAULT;\n return new Promise((resolve, reject) => {\n const query = new RowDataQuery(\n // Binary results require the extended protocol; `queryMode` forces it for bindings-less queries.\n binary\n ? { text: sql, values: bindings as any[], binary: true, queryMode: \"extended\" }\n : { text: sql, values: bindings as any[] },\n (err: unknown) => {\n if (err) reject(err);\n else resolve(query.rowData);\n },\n );\n client.query(query as any);\n });\n}\n\n/** Returns whether `client` supports the lazy row-data query path, before submitting anything. */\nfunction isRowDataCapableClient(client: unknown): client is pg.PoolClient {\n // Require the pure-JS pg client (pg-native has no `connection` and different query internals).\n return (\n typeof client === \"object\" &&\n client !== null &&\n typeof (client as any).query === \"function\" &&\n (client as any).connection !== undefined &&\n (client as any).native === undefined\n );\n}\n\n/**\n * Resolves each column's decoder from the query's RowDescription.\n *\n * Binary-format fields decode through Joist's own binary registry only (see\n * `setBinaryTypeParser`) — `pg.types`/`TypeOverrides` are never consulted, and a column whose\n * oid has no registered binary parser fails the query here, before any rows arrive, rather\n * than guessing at a lossy decoding. Text-format fields (the `binary: false` escape hatch)\n * decode by utf8-slicing the cell into the active text parser, resolved via `getTypeParser`\n * (i.e. the pool/client `TypeOverrides` chain) or the global registry.\n */\nexport function pgColumnDecoders(\n fields: Array<{ name: string; dataTypeID: number; format?: string }>,\n getTypeParser?: (dataTypeID: number) => (value: any) => any,\n) {\n return fields.map((field) => {\n const { name, dataTypeID, format } = field;\n let decode;\n if (format === \"binary\") {\n decode = getBinaryTypeParser(dataTypeID);\n if (decode === undefined) {\n throw new Error(\n `joist-orm: no binary type parser registered for oid ${dataTypeID} (column \"${name}\");` +\n ` register one with setBinaryTypeParser (i.e. binaryTextParser for text-like types)`,\n );\n }\n } else {\n const parse = getTypeParser?.(dataTypeID) ?? pg.types.getTypeParser(dataTypeID, \"text\");\n decode = textCellDecoder(parse);\n }\n return { name, decode };\n });\n}\n\n/** Builds a text-format cell decoder: utf8-slice the cell bytes into the active text parser. */\nfunction textCellDecoder(parse: (value: any) => any): (chunk: Buffer, start: number, length: number) => any {\n return (chunk, start, length) => parse(chunk.toString(\"utf8\", start, start + length));\n}\n\n/** Warns once when lazyRows degrades to classic rows for an unsupported client, i.e. pg-native. */\nfunction warnUnsupportedClientOnce(): void {\n if (warnedUnsupportedClient) return;\n warnedUnsupportedClient = true;\n console.warn(\"joist-orm: lazyRows is enabled, but this client does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